Repository navigation
Description
EDIT: THIS ISSUE HAS BEEN SUPERSEDED by #459.
In #219, I examined some unfortunate event handling complexities on MacOS X. That examination led me to view and re-implement both poll_events() and run_forever() as special cases of a more general API, get_event(Timeout) -> Option<Event>.
I propose:
- Refactoring each platform to expose this
get_event(Timeout)interface, - Refactoring
poll_events()andrun_forever()to be implemented in terms ofget_event(Timeout), and - Deprecating
poll_events()andrun_forever()in favor ofget_event(Timeout).
This is a user-facing API change, so I'm accompanying this proposal with a larger than usual explanation.
Receive-with-time-constraint is the fundamental operation
poll_events() allows the user to communicate "I want all the events that are ready, but I don't want you to wait". Let's call that get_event(Timeout::Now), and make the loop explicit:
// current
events_loop.poll_events(|event| {
match event {
Event::WindowEvent { event: WindowEvent::Resized(w, h), .. } => {
println!("The window was resized to {}x{}", w, h);
},
_ => ()
}
});
// proposed
while let Some(event) = events_loop.get_event(Timeout::Now) {
match event {
Event::WindowEvent { event: WindowEvent::Resized(w, h), .. }) => {
println!("The window was resized to {}x{}", w, h);
},
_ => (),
}
}run_forever() allows the user to communicate "I want all the events until I tell you to stop", which… is kind of weird, isn't it? At any rate, it's the user's intention to block indefinitely and eventually break out of the loop. Let's call that get_event(Timeout::Forever), and again push down the loop:
// current
events_loop.run_forever(|event| {
match event {
winit::Event::WindowEvent { event: winit::WindowEvent::Closed, .. } => {
winit::ControlFlow::Break
},
_ => winit::ControlFlow::Continue,
}
});
// proposed
loop {
match events_loop.get_event(Timeout::Forever) {
winit::Event::WindowEvent { event: winit::WindowEvent::Closed, .. } => {
break;
},
_ => ()
}
}Some users have additional needs, like "I want all the events between now and when I need to update my state/draw the next frame". pistoncore-glutin_window does this today by unconditionally spawning a thread that wakes up the event loop after a fixed period of time. We should be able to support it efficiently on every platform without needing extra threads, and with a timeout-centric API, we can:
// current
let events_loop_proxy = self.events_loop.create_proxy();
thread::spawn(move || {
thread::sleep(timeout);
events_loop_proxy.wakeup().ok(); // wakeup can fail only if the event loop went away
});
{
let ref mut events = self.events;
self.events_loop.run_forever(|ev| {
events.push_back(ev);
glutin::ControlFlow::Break
});
}
let event = self.events.pop_front();
// proposed
let event = events_loop.get_event(Timeout::Deadline(timeout));Timeouts are sufficient to justify a new API
Consider a game that wants to update and render at 60 fps. If the game is running faster than 60 fps, it should sleep and wait until it's time to start the next frame; if it's running slower, it should busy-wait.
This use case presently requires a calling run_forever(callback) to allow the thread to sleep, plus a second thread keeping track of time and calling Proxy::wakeup() as needed. That's wasteful and unnecessarily complex.
winit should support timeouts pattern directly. Additionally, this is a common requirement; every event loop has some way to block until a specified time, or some idiomaitc way to synthesize a timeout. winit should use this where appropriate.
Simplifies the API
winit puts user code at the bottom of the stack, and does not force the user to organize their code in terms of callbacks… except for event handling. Changing the API so that the user calls get_event(Timeout) in a loop adds consistency, and it lets the user define and manage their event loop with normal Rust statements instead of a callback that returns a ControlFlow enum.
This also makes EventsLoop look more like a futures::stream, or a generator, or many other things that users might already know. "I want to get a message from you" requires less explanation than having two different functions that take two different callbacks.
Reduces duplication
poll_events() and run_forever() have considerable overlap, and in the case of the MacOS platform, considerable code duplication. Not only can get_event(Timeout) provide more functionality, in the case of the MacOS platform, refactoring into this caused a net reduction in code.
Low risk
It's very easy to implement poll_events() and run_forever() in terms of get_event(Timeout), which means there's very little risk in deciding to move that direction.
winit can continue to provide the same poll_events() + run_forever() API to the user while refactoring platforms into get_event(Timeout) behind the scenes. Once they're all ready, winit can update the examples, deprecate poll_events() and run_forever(), and ultimately remove at some later point.
Next steps
I think this covers everything:
pub enum Timeout {
Now,
Forever,
Deadline(std::time::Duration),
}
impl EventsLoop {
pub fn get_event(Timeout) -> Option<Event> {
// …
}
}A change like this requires buy-in, and this isn't my project, so I don't know what all would need to happen. I'm happy to start by soliciting feedback, so: what does everyone think?
Activity
tomaka commentedon Jul 17, 2017
What you describe is more or less winit's old API. We transitioned to callbacks because it solves the fact that MacOS uses a resize callback, and also in the longer term because of Android and Emscripten.
It's the opposite, the
futureslibrary is based on callbacks.Ralith commentedon Jul 17, 2017
Huh?
futuresis based on structs that have apollmethod which you call to see if they're ready or not, and get a value from if they are.Couldn't this (and any similar system) be handled by putting the message in a queue in the event loop struct and waking it up?
tomaka commentedon Jul 17, 2017
This is missing half of the documentation. If the future is not ready when you call
poll()then it will later automatically callTask::unparkwithout the user's intervention.mitchmindtree commentedon Jul 17, 2017
@Ralith see #219 - The main problem is that in the macOS backend,
nextEventMatchingMaskblocks from the moment the user presses their mouse to begin a resize until the end when the user releases the mouse. This means we can't return fromrun_forever,poll_eventsor the proposedget_eventmethod until the user ends the resize, at which point all theResizedevents would be dumped at once. @willglynn I just tested the window.rs example with your coroutines branch on my macOS machine and it has re-introduced this problem now that you have re-implementedrun_foreverin terms ofget_event.I would recommend breaking this proposal into two distinct proposals:
1. Offer a way to timeout on waiting for events.
I agree that this makes sense (as long as all platforms offer a native API for this) to avoid the need for users to spawn a thread.
2. Change the event emitting API by removing the user callback approach in favour of returning events from a function.
From my understanding this is a much harder problem due to the frustrating behaviour of macOS that I mentioned above. As it stands, I can't really get behind this proposal without first solving this problem. As tomaka mentioned, this problem is one of the reasons we changed the API from returning Event iterators to user callbacks in the first place. That said, if we can work out how to solve this issue, I would love for a more control-flow friendly approach like we used to have! I just don't yet see a solution that will allow this with consistent behaviour across all platforms.
willglynn commentedon Jul 17, 2017
@Ralith:
Yes, with the caveat that the thread receiving the callback is the caller's thread, and there's an internal event loop that we don't control sitting between
poll_events()/run_forever()and the callback. I moved the part of the code that can trigger a second internal event loop into a coroutine, and now it works exactly the way you describe: callbacks post a message to a queue, which wakes the event loop, which hops back toget_event()and lets it return.@mitchmindtree:
The MacOS problem is sticky because the normal event handling scheme can wander into an internal event loop. Sure, you can get callbacks at various points --
NSWindowDelegate, runloop observers, timers -- but you can't actually return to the caller.The current approach plumbs the user's callback all the way down so that the MacOS callbacks can trigger them. That delivers resize events as they happen, yes, but it breaks the contract in other ways.
poll_events()can hang for the entire duration of a window drag instead of returning immediately, which blocks the example game loop.run_forever()seems like it would be unaffected, butEvent::Awakenednever gets delivered during a resize, and in practice, callers rely on making it return, which it also can't do during a resize.My changes in #219 address the core of that issue, which is that some parts of the MacOS event loop can block for a long time.
get_event()is responsible for driving those parts forward, but now that happens in a coroutine that periodically returns control toget_event()so that it can check its timeout and return if needed. This makespoll_events()always return without blocking and makesrun_forever()respond promptly toControlFlow::Breakandwakeup().@tomaka:
Callbacks are insufficient to solve the MacOS problem; if
poll_events()happens to see a resize start, it'll block for seconds. The only solution that fits the constraints is stack switching, as I describe and implemented in #219. With that in place,get_event(Timeout)seems like the underlying primitive we should expose.Emscripten bring me to another question: is this the wrong model entirely? Should
winitcode be running at the bottom of the call stack, instead of running on top of user code? That would letwinithide the difference between aloop {}on most platforms andemscripten::set_main_loop_callback()on JS. That would also fix the MacOS problem without needing coroutines: if everything were a callback, it wouldn't matter if the callbacks were delivered directly from the normal runloop or the middle-of-a-resize runloop. It's only difficult becauseEventsLooppromises to return to the caller, instead of the caller always running insideEventsLoop.How does Android fit in?
mitchmindtree commentedon Jul 17, 2017
Ahh you're totally right, this is a pretty major issue with the current implementation.
For anyone else reading along here: As I just mentioned in #219, I'd forgotten to enable
--features "context"when testing @willglynn's coroutines branch. It does indeed return during the live resize, and seems like a promising solution for the bug where macOS becomes blocked on an inner loop.fschutt commentedon Sep 1, 2017
Well yes, but as it is right now, the EventsLoop runs for literally every event, causing the whole app to lag, because there are way too many events and the closure-based design blocks on every event. Try resizing a window with the new
winitAPI - it lags like hell.The old
wait_eventsis missing and there is no replacement in sight, which is very bad. It maps 1:1 to the OS-native event loop, which is good for applications. Macs could use the current closure design, but just abandoning the OS-native loop is a very bad idea.Boscop commentedon Jan 22, 2018
I'm using it without issues (high CPU usage) like this:
My FpsLoop does the necessary sleeping.
It's an "inversion of control" but in a good way, winit gives you the control of how fast you want to loop.
Boscop commentedon Jan 22, 2018
@Portstrom But the issue above says:
Ok, that's my use case, too.
Yes, that's what my
FpsLoopiterator does.Why does it require that? It seems to work without that for me..
@Portstrom I'm not trying to be a dick. What is your use case and why can't it be done by looping at high FPS and only drawing sometimes?
fschutt commentedon Jan 22, 2018
@Portstrom In case you are looking for a workaround, I ran into the same problem. I forked and backported important patches to both glium (https://github.com/fschutt/glium-backport/tree/glium_backport - use the branch "glium_backport") and vulkano (https://github.com/fschutt/vulkano-win-backport). They are the last versions to use the old API. I am currently using those because of this issue.
So if you have old code depending on the old glium API, you can depend on those. If you have issues, I'll help to backport fixes. It's not a perfect solution, but it's something until this situation is resolved. I can't accept performance problems just because of a macOS weirdness (which I don't even use).
Boscop commentedon Jan 22, 2018
@Portstrom So you want to avoid unnecessary redrawing? Why not set a flag from within your
poll_eventscallback when events happen that require a redraw? Then check the flag afterpoll_eventsto see if you should redraw.willglynn commentedon Jan 22, 2018
@fschutt: the worst part is, the
poll_events()+run_forever()model doesn't even fix MacOS.I describe the problem in #219, but it boils down to a fundamental design mismatch:
winitis designed such that the user's code primarily controls the main thread and calls into the platform, whereas MacOS is designed such that the platform primarily controls the main thread and calls into the user's code. I developed a changset to fix this (#237) which does stack switching trickery: the user's code calls into MacOS while also letting MacOS call into the user's code. I maintained it for a while but it never got merged, and while I recently indicated I'd be happy to update it again, the maintainers have yet to express interest.That PR would fix the problem on MacOS, which would eliminate the only technical blocker in this issue. Having said that, the fundamental design disagreement remains: some platforms want to run the event loop themselves, and
winitassumes they don't. We can fix MacOS by dancing around with coroutines, but is that the only instance of this problem? Web browsers don't much like infinite loops in JS or WebAssembly…13 remaining items
Switch from .run_forever() to .poll_events()
Switch from .run_forever() to .poll_events()
Merge #1822
francesca64 commentedon Apr 18, 2018
So, if I'm understanding things correctly, combining what's been outlined here with the problems we have with Windows, then doesn't this mean that our current design is at odds with most platforms?
mitchmindtree commentedon Jan 31, 2019
They care very much so - I believe most of the points in this issue are being addressed in #638 in @Osspial's heroic effort to rewrite the event loop, though I'm not familiar enough with the PR to know for sure if everything in this issue has been addressed. That PR is just about ready to go - feel free to have a look, test it and share any constructive input you might have. The maintainers are a group of collaborators working on this in their limited, free time and for many, winit is just one of many open source crates to which they contribute, each with their own slew of "showstopper" issues to address.
Osspial commentedon Feb 4, 2019
Honestly, I understand being frustrated about the lack of visible progress - there are several issues that can't be fixed without updating the main event loop API, and the changes have been in the pipeline for... uh... oh jeez has it really been over six months? Those changes should land Very Soon, though.
Anyhow, I'm going to close this issue in favor of #459 since that's where the discussion on the event loop API ended up getting finished.
Merge next back to dev branch (rust-windowing#305)
Publish New Versions (rust-windowing#234)