Repository navigation
Description
UPDATE 8/23/18:
A PR for Windows is available at #638
UPDATE 7/12/18:
I've adapted the agreed-upon changes into a changelog here: https://gist.github.com/Osspial/d3a3390807fa95a469d9c9b677db4715. The original proposal is below.
Events Loop 2.0
This issue proposes a series of changes to winit's EventsLoop API, based around the experiences I've had with creating a GUI library that uses winit as a window creation backend. The main goal is to give winit complete control over the event loop, both for event polling and event waiting. These changes should let us fix various implementation bugs on the win32 backend, as well as fix what I believe are design bugs in the current API.
Technical Motivation:
EDIT: The technical motivation for the Windows backend is included below. However, pretty much every platform winit supports is hacky or broken in some way by necessity of the current API we expose.
Right now, the win32 backend creates a background thread, in which the events loop resides. The biggest problem with this is that it introduces various unexpected synchronization bugs that require a good amount of effort to fix and increase the complexity of the backend (see #415 and #391). However, it's necessary to cleanly handle win32's various modal event loops.
So, what are these modal loops, and why do they matter? On Windows, when a user begins resizing a window, Windows suspends the program's main event loop and begins its own loop, inside of the resize event's handler. Unfortunately, this freezes any processing that's going on outside the Windows event loop, which is currently worked around by having the loop exist in its own thread, introducing quite a few bugs as mentioned above. Inside the loop, Windows does a bunch of additional processing, most notably handling window snapping (although it probably does other stuff too that isn't obvious).
Windows doesn't publicly expose the APIs used to handle snapping, so re-implementing the modal loops ourselves so that they don't suspend the main event loop isn't really an option. However, Windows should still process events we push to the Windows events queue, letting us implement event polling inside the Windows event loop with custom events (using the same mechanisms used for wakeup messages), as long as winit's API lets it assume complete control over program control flow. Right now, it doesn't, but this change would let us remove the second thread and simplify much of the implementation.
Actually removing the second thread isn't that difficult (see #445), but these bugs present pretty major blockers that should be resolved before that's merged.
Design Details
EDIT: The original design has been removed from this post, as it is outdated and may cause confusion for new readers. However, it does contain some useful information about the rationale behind the changes, and can be accessed here: https://gist.github.com/Osspial/53efa87797899872650f6bece14736c0
Activity
elinorbgr commentedon Apr 13, 2018
I don't have much to say about the API itself (I'm not that much used to writing apps with winit tbh), just commenting to say I don't see any strong incompatibility / difficulty with implementing this regarding to the wayland backend.
The most tricky part will be handling
WaitWithTimeout, which will require to do some manualepoll, that's all I see.francesca64 commentedon Apr 13, 2018
I think it's too opaque to have
Refreshmean both "event processing finished" and "OS requested redraw", and if we were to go through with this, the nameRefreshshould probably be changed altogether. I can see some users thinking it represents vertical refresh, and it's just not very descriptive in general.My grasp of your intended
ControlFlowenum is a little unclear. Do you want users to be able to switch between these strategies at will during the event loop? Is that something we can implement effectively?I'm curious how you'd say this proposal is better than #231, as your
Refreshmachinery seems to exist to solve the same problem (andget_eventseems cleaner to me). I definitely agree that the current API has problems, and I'm starting to get the impression that the current model is incompatible with most platforms. At this point, I'm wondering if we should just invert the control flow, since unless I'm missing something, it seems like the most straightforward solution.Additionally, since this is an area that has such an immediate and substantial impact on users, before acting on anything I'd want to see a lot of feedback. When we've achieved a good enough internal consensus, I think it would be a good idea to discuss it in other places in the community, and we'd hopefully be able to deliver an API change that people are hyped for, rather than one that unceremoniously breaks their application one morning.
willglynn commentedon Apr 18, 2018
I think a breaking API change is necessary, but it must require the user to entirely surrender their thread. A callback-only API would fix Windows, it would fix MacOS (which has nearly identical resizing gotchas described in #219), it would fix the web (which needs to
returnto the browser to deliver more events), it would fix iOS and Android (which likewise expect to run the event loop), etc.Going callback-only is a massive breaking change, but it's the right move. Most platforms expect to call user code from the UI thread when things happen, while
winittells its users that they can keep the UI thread and occasionally call into the platform. That is why this is hard.Dropping
run_forever()in favor of a new API that takes over your thread would be a massive breaking change, but it is possible to glue both models back together again using the pattern from #237. We could make awinit-compatcrate that providesrun_forever()on top of a new callback-only API via coroutines, and it could work on the major platforms.Having said all that, while I am convinced that this is the right way forward, I am not in a position to be the champion of this approach. I no longer use
winitand can't justify investing the required time and effort into making this happen.francesca64 commentedon Apr 19, 2018
@willglynn I'd say I'm in a good position to be the champion of this approach. If necessary, I'd even implement it for every platform, though for my sake it hopefully wouldn't come to that.
At this point, I'm quite convinced that this is of great importance. Interfacing with platform APIs the correct way is already hard enough, and our current approach doesn't seem to be doing any favors for the users, contributors, or maintainers.
I'm not sure how necessary the
winit-compatidea is. Good migration documentation and coordinating with projects could go a long way.Anyway, now we just need to get the approval of... basically everyone.
elinorbgr commentedon Apr 19, 2018
I would be in principle in favor of such a change on the winit API (going callback-only), though I'm not sure how much my opinion count on that, the fact remaining that wayland as a platform remains pretty accommodating regarding control-flow handling.
Though, if such a thing starts going, I'd like to emphasize the need for good planning ahead (maybe going through an RFC-like process ?), in order to clearly define the contents and guarantees of the API, in order to allow easier coherence in backend implementations.
Typical questions that in my opinion need to be clearly addressed are for example:
Sendand/orSync?)kvark commentedon Apr 19, 2018
@francesca64
viva de revolution! I'd be happy to provide limited assistance (got all platforms by hand).
You have my seal of approval. Can also speak about some of the clients of
winit:NSAutoreleasePoolbeing automatic on OSX/Metalwinit(similarly, any middleware usingwinitwould have to own the main loop after the change), also needs to schedule a frame, otherwise should be goodrun_foreverOsspial commentedon Apr 19, 2018
@vberger My instinct is to make Windows
SendandSync, and then have theEventsLoopstructure itself be locked to a single thread. I know this would work on Windows, as it's essentially what's already there, but I don't know how it would work on other platforms.@francesca64 I can see your point with having
Refreshmark the end of event processing, but I'm not sure if I agree with it. An alternative would be to havequeue_refreshimmediately send aRefreshevent to the user, but I don't see a situation arising where someone would want to redraw immediately inside of the event loop. Regardless, there probably should be an event that communicates when the event loop is going to resume waiting -WaitBegin, perhaps? Also, even if this isn't the API we settle on, I do feel like we should renameRefreshtoRedraw, as that communicates its purpose better.My goal with the
ControlFlowenum is to have it tell winit when it should call back into user code, and to allow the application to cleanly switch between updating constantly, updating intermittently and being suspended. This should be possible on Windows by switching between callingGetMessageandPeekMessage, and I'm assuming there's equivalent code to do this on other platforms, but I couldn't say with any certainty.@willglynn basically explained the advantages of this API over the
get_eventAPI - whileget_eventis cleaner, and I'd rather use it if the underlying platforms allowed for it, the majority of platforms assume the OS is driving the event loop. A callback-based API fits into the OS event loop way better than the iterative design you get withget_event.Osspial commentedon Apr 19, 2018
I'd be able to implement this on Windows, at least, as it should be a fairly simple change to my current single-threaded win32 branch.
willglynn commentedon Apr 19, 2018
A common pattern that pops up in this space is sending yourself a message, particularly to communicate things from other threads onto a UI thread. This can usually be expressed directly using platform-specific hooks, and when it can't, it can be synthesized.
This pattern often separates concerns: you end up writing event handling code to handle the message you sent from some other context and do whatever it asks you to do.
An alternative to consider:
Instead of sending custom events to the event loop, send closures to run within the event loop. (Platforms could implement this by sending themselves a message – though there are a few alternatives on Mac/iOS and a native closure queueing mechanism on the web.) This ability to easily execute code within the event loop from arbitrary contexts could substantially reduce the need for other thread-safe interfaces.
Osspial commentedon Apr 19, 2018
@willglynn An issue I can see with that is that any closures you pass through that function don't gain access to the data in the main UI closure, which would limit pretty heavily what you could do with the passed closure. Passing custom events which are handled by the main event closure gives you access to that data. How would that be handled? The best solution I can see would be to wrap all the data in the main UI closure in a
Rc<RefCell<...>>, but that doesn't seem ideal.elinorbgr commentedon Apr 19, 2018
@Osspial
An other possibility would be to add a type argument to the event loop :
EventLoop<Data>, and require the user to provide an instance of this type at creation, and then all closures run on the event loop would take an additional&mut Dataargument.However, I suspect several of the platform backend would implement it by using an
Rc<RefCell<Data>>internally (or some other more costly mechanism), so...For what it's worth, I've kind of struggled with this question for quite some time in wayland-client, for a very similar mechanism (allow closures run by the event loop to share data without using
Rc<RefCell<_>>), and in the end, it appeared to me that in all,Rc<RefCell<_>>was actually not that bad, and I suspect its runtime cost should be quite negligible in the context of UI events dispatching.willglynn commentedon Apr 19, 2018
@Osspial Sure; there's definitely API design to do here.
It's generally not sufficient just to be on the right thread, you also need the ability to use resources which are exclusive to that thread. That relationship – "there are things which are exclusive to this thread, but you can interact with them until your function returns" – should be described via the type system. This sounds
winitshould provide a&mut TwhereTis neitherSendnorSyncgating access to the windowing system.The user probably has application-wide state which is synchronized with the windowing system. Parameterizing
winitaround the user's state seems like a valid approach, e.g. this sketch in #231.Thing is: this same thing (providing thread-local exclusive access to the platform and exclusive access to some application data) is needed for the event handling callback too. Whatever solution is used there should inform the parameter(s) to the
run_in_event_loop()closure. I just wanted to plant the idea that the ability to asynchronously execute a closure within the event loop could greatly reduce the scope of things which need to be made thread-safe.Osspial commentedon Apr 20, 2018
@willglynn Regardless, I think that custom event passing is a more flexible solution than closure passing. My big reason for that is it allows users to implement a much more flexible closure-passing system than we could by just exposing a closure API, while the same couldn't be done the other way around. By letting users define their own closures (or enums of closures) as events, they can send closures with more return types or parameters than we could expose through the
Fntrait. That also means we don't have to keep track of some user-defined type withinwinit, as any custom types that need to be used in a closure can just be passed by the main, event-loop closure.sodiumjoe commentedon May 2, 2018
Speaking from almost complete ignorance here, but I wanted to throw out a suggestion.
Is it conceivable to try to invert winit's model, so it's more of a set of ui toolkits for the various backends, rather than an abstraction over the various windowing apis? I'm not sure that even makes sense as an idea, or whether there are more granular abstractions that make sense to make over parts of the different backends enough to warrant them all being in a single project. I also don't know how this would interact with glutin.
Please don't take this as criticism of your great work!
85 remaining items
Osspial commentedon Mar 10, 2019
@ryanisaacg Regarding returning
!- what the emscripten backend currently does is call theemscripten_set_main_loopfunction, which throws an exception in order to kill the stack and give control back over to the browser. Would it work to call into JavaScript to do something similar? After an exception is thrown you could add in anunreachable!()call to make it type-check.Also, this is probably me just being unfamiliar with the web APIs, but why can't you set a timeout for longer than 0 milliseconds?
set_timeoutseems like it would allow you to do that, but I assume there's some technical problem with doing that which I don't see.elliegoldstein commentedon Mar 11, 2019
I hadn't considered throwing a Javascript exception. That works great, thanks.
I was worried that a larger timeout would introduce unacceptable latency into applications (though I suppose for applications that care about it, PlatformSpecificWindowBuilder could have an option.) My understanding was that the intended behavior of
Waitwas that it would near-instantly dispatch the event, though that could be wrong.Osspial commentedon Mar 11, 2019
Oh whoops, I mixed up
WaitandWaitUntil. You're right that that'sWait's intended behavior. In that case, couldn't you just do nothing afterEventsClearedand wait until the browser dispatches another event?elliegoldstein commentedon Mar 11, 2019
I'm having trouble creating a solution where the user's event handler function is available to event handlers, because sharing an FnMut seems to be disallowed.
Osspial commentedon Mar 11, 2019
Ah, ok! You can use an
Rc<RefCell<{event handler, other data}>>for that, which is essentially what we're doing for the Windows backend to share the user event callback between windows and it's worked fine there. The secondRefCellin that implementation is so that we can buffer events if the user invokes a winapi call that results in the user callback being invoked a second time before the first invocation returns, which may or may not be necessary for wasm.Osspial commentedon Apr 5, 2019
@mtak- We've slowly been merging backends on the
eventloop-2.0branch. Would you be able to submit a PR for the iOS backend?nvzqz commentedon Jun 10, 2019
Since the main discussion seems to be happening here regarding these changes, I'll address #638 (comment) here.
The extension traits have been renamed to include the operating system name, which feels very awkward in my opinion since this isn't standard convention. It's also not documented in
CHANGELOG.md. It would be worth adding since it's a breaking change.goddessfreya commentedon Jun 10, 2019
@nvzqz That does sound awkward, I too wonder why this is the case.
nvzqz commentedon Jun 10, 2019
Not sure if this has been proposed before, but since some platforms may have multiple backends, it may be worth making
winittypes generic over aBackendtrait. See #908.elliegoldstein commentedon Jun 15, 2019
Potential source of difficulty again with wasm: Instant is required in the Winit public API, but as far as I know you cannot obtain an Instant on web.
cheako commentedon Jul 21, 2019
I'm confused!
Hardly anything is explained for the behavior, what happens in explicit detail, for winit::event_loop::ControlFlow. The docs should read like a man page in that, after reading, one should have the feeling of being able to write the entire event loop. Every conditional branch(if and match statements) should be explained, as should every other code block.
winit::event::Event would logically have:
Consider redoing winit::event_loop::ControlFlow as a trait instance that has callbacks for set_timer(T, Instant), set_sleeping(), set_polling() and set_exiting().
Edit:
set_timer() needs to return a handle to the timer so it can be altered/canceled.
Edit: #1018
cheako commentedon Jul 21, 2019
Rational:
Given that this event loop is implemented multiple times it's vastly consequential to avoid undefined behavior. Undefined behavior isn't just a collection of unexplained consequence, instead there is an entire field of both theory and practice with as much depth as any paradox.
Users of winit should know, unequivocally, what to expect from the event loop. If instead applications are coded to the probed behavior of the system they are developing on, this will lead to poor support for the other platforms. When behavior is discovered that's unexpected users of winit should know to seek help prior to continuing as a determination of feature or bug must be made and the documentation should be further refined in effect to remove ambiguity.
goddessfreya commentedon Jul 21, 2019
@cheako Make a separate issue please.
Auto merge of rust-windowing#459 - servo:dependabot/npm_and_yarn/exam…