Repository navigation
Description
Winit's and glutin's current API look like this:
impl Window {
pub fn wait_events(&self) -> impl Iterator<Item = Event> { ... }
pub fn poll_events(&self) -> impl Iterator<Item = Event> { ... }
}I suggest that instead you'd have to register your window to what's called an events loop. Then, you'd call a method on the events loop to run it. Running the events loop would process events received by the operating system, and call a callback previously registered on the window.
This is essentially the same approach as the future-rs library, except that we're not using future-rs directly because it's not totally stable. I'd like to eventually publish winit 1.0 (in, like, the next nine months or so), and it's unlikely that future-rs publishes its 1.0 before winit.
Example usage with the new API (just to give an overview, the details are not important at the moment):
let events_loop = EventsLoop::new();
let window = WindowBuilder::new().with_title("hello").build(&events_loop).unwrap();
window.set_callback(|event| match event { ... });
loop {
events_loop.run_once(); // calls the closure passed to set_callback earlier
}I've always been a bit wary about callbacks because they are often too "magical", like you don't know which thread calls them and at what moment. But the fact that it's the run() method of the events loop that calls the callbacks means that it's a good design in my opinion.
This approach would have some benefits over the current system:
- In the implementation we can decouple the
Windowobject in Rust from the actual window. The actual window could be stored in theEventsLoopfor example. - Right now on Windows winit spawns a background thread for events handling ; this could be removed.
- We can force the
EventsLoopto run on the main thread for OSX while still allowing theWindowobjects to be shared between threads. This has been a huge safety hole in glutin since the beginning. - The
set_resize_callbackfunction of MacOS would be gone. - The
WindowProxywould be gone in favor of an "EventsLoopProxy". - We can later register other kinds of callbacks to the events loop, for example a callback when a monitoring is plugged in or removed that is not tied to particular window.
- This design is also more appropriate for emscripten in glutin, as emscripten/javascript are based on callbacks and not on preemptive multitasking.
Activity
tomaka commentedon Oct 8, 2016
I guess I'll ping some people to get some opinions: @ozkriff @mitchmindtree @kvark @fkaa @vberger @glennw @larsbergstrom
Osspial commentedon Oct 8, 2016
How would this allow winit to not spawn a background thread on Windows? Rescaling a window causes the callback thread to be blocked until the end of the rescale, a behavior which is currently hidden by the background thread, and as far as I know there isn't any way to stop that behavior. Moving it onto the main thread would move the blocking there.
mitchmindtree commentedon Oct 9, 2016
There are two main trade-offs that come to mind with this approach:
FnMut? I can imagine this making it difficult to "share" data between each of the callbacks. It seems like we'd either have to require users wrap their "shared" data inRc<RefCell<>>orArc<Mutex<>>, or that they propagate the events yielded by each callback over some channel to a loop that looks like what glutin currently looks like. I put "shared" in quotations as the closures are only actually ever called from the same thread, right?I'm curious why this is a benefit? Is it because you're unsure how to both make the window handle available to the user while also using it to run the events loop? Another way (using glutin's current style) might be to pass the window to the method that yields the next event, something like:
I'm not familiar enough with the issues related to the other benefits you mentioned to be able to comment on whether they are worth the trade-offs I mentioned above.
tomaka commentedon Oct 9, 2016
@Osspial Are you sure about that? On Win32 you're supposed to poll and dispatch the messages manually with
PeekMessageandDispatchMessage, so I'm not sure how it would block.@mitchmindtree Don't forget that the closure can borrow its environment.
You could write for example this:
Or, this:
It's true that if you want to isolate the window in a struct, then you will need a
Rc<RefCell<>>or anArc<Mutex<>>like this:However I think this use case doesn't happen often.
The benefit of decoupling the window from the events loop is that on MacOS we can run the events loop on the main thread and the window in another thread, and that with X11 we can do everything in a single-threaded fashion by creating one X connection per EventLoop, which will likely lead to less bugs in xlib.
Osspial commentedon Oct 9, 2016
@tomaka Yeah. I was able to get winit working without multithreading on Windows with the current API, and everything worked fine except for rescales, which blocked execution. Apparently, Windows enters an internal loop during rescales that does end up calling the user-defined window procedure, but doesn't return from
DispatchMessage, effectively blocking program execution until the resize ends, exiting the loop.tomaka commentedon Oct 24, 2016
One interesting problem is about leak safety.
In the example above, if we
mem::forgettheWindowand run the events loops, we can access the objects referenced by the callback without having any actual borrow on them. This is undefined behavior.Future-rs's tasks system is very complex and avoids this problem by running the callback only if we call a method on either the future itself or the task that holds the future.
mitchmindtree commentedon Nov 18, 2016
Looking at this issue again and looking over the benefits you mention, I think they're easily worth the issues I mentioned, and the workarounds you shared look really reasonable anyways. 👍 from me.
tschneidereit commentedon Nov 21, 2016
@tomaka would it make sense to actually make this use
futures-rsat this point. According to @aturon Futures should be quite stable at this point. (Also note @alexcrichton's followup ontokio-corestability.aturon commentedon Nov 22, 2016
@tschneidereit I'd be happy to advise more specifically if you decide to go this direction!
tschneidereit commentedon Nov 22, 2016
@aturon thanks! I guess the main question is whether it's prudent to plan on releasing a 1.0 of winit based on
futures-rswithin the next nine months or so:@tomaka, do I understand correctly that with the right stability guarantees you'd go with
futures-rs?tschneidereit commentedon Nov 22, 2016
@pcwalton, do you think a Futures-/Tokio-based event loop for winit would work well for Servo?
aturon commentedon Nov 22, 2016
I think that's reasonable, yes, assuming that today's futures-rs seems to cover your needs. We definitely won't be removing any functionality, and at this point the core future and stream abstractions have gotten quite a bit of vetting. While I do expect a 0.2 release in the coming months, we're already using features like deprecation warnings to make that a smooth transition, and I don't expect core abstractions to be changes much, if at all -- with the exception of the just-added
Sinktrait, which will likely need a bit more design iteration.glennw commentedon Nov 22, 2016
At first reaction, this seems like it would be fine for Servo.
The main parts for us are:
asajeffrey commentedon Nov 22, 2016
This is on my to-do list, probably to look at starting Q1 2017.
tomaka commentedon Nov 29, 2016
I'm still a bit hesitant about depending on
future, though. I don't want to jump into semver hell by exposing another library's internals. When some person's code will inevitably break after they runcargo update, I will get pinged on IRC to tackle the problem.I'm tempted to either wait for the private/shared dependencies system that was advertised in a talk recently, or for futures to be merged in the stdlib.
tomaka commentedon Dec 7, 2016
I've been thinking about it, and for me the future library has too many drawbacks:
Resulteven though errors can't happen. Thepoll_eventsandwait_eventsfunctions don't return aResult.If you except the leakpocalypse-related problem described above, I don't see any good reason to use futures instead of a custom API. On the other hand, it's very easy to wrap the API described in the opening post around futures if one wants to use futures.
tomaka commentedon Dec 7, 2016
Maybe an API like this is better:
The events loop calls a local callback and each event contains an identifier of the window that produced the event (amongst the windows that were registered on the events loop).
I think it would still provide all the advantages described above. We still need to use a callback and not return events by value because of the MacOS resize callback problem, and for emscripten.
Someone would really wants to use futures could easily implement
Future/Streamover this API by taking control of the events loop's callback.norru commentedon Dec 7, 2016
Perhaps this is of interest: https://github.com/gamazeps/RobotS
norru commentedon Dec 7, 2016
rust-lang/futures-rs#50
mitchmindtree commentedon Jan 22, 2017
@tomaka that API looks fine to me!
Would it be worth making a new window-specific event enum to differentiate between general events and events that apply to a specific window? It might save adding a
WindowIdfield to half of the events. E.g. the existing events might be split up something like this:So matching on events might look something like this
Remove Resize events generation now that upstream has been fixed.
Update the macOS backend to the new futures-compatible API.
Update the macOS backend to the new futures-compatible API.