winit icon indicating copy to clipboard operation
winit copied to clipboard

Make `with_parent_window` safe

Open madsmtm opened this issue 10 months ago • 6 comments

Alternative to https://github.com/rust-windowing/winit/pull/3136. EDIT: We'd still need some more work to make Fullscreen Send + Sync on all platforms.

Builds upon https://github.com/rust-windowing/winit/pull/3126 to remove the unsafe from WindowBuilder::with_parent_window, by taking the lifetime inherent in that, and extending it on the platforms where it is relevant.

TODO:

  • [ ] Merge the aforementioned PR.
  • [ ] Test on all platforms changed
  • [ ] Add entry to CHANGELOG.md

madsmtm avatar Oct 13 '23 21:10 madsmtm

Alternative to https://github.com/rust-windowing/winit/pull/3136.

This is not an alternative since it doesn't achieve what said PR achieves.

However doing something like that is fine.

kchibisov avatar Oct 13 '23 22:10 kchibisov

After looking into it, I don't think it's a good idea as of now to accept owned handler if winit can only provide Raw handles.

This update should be a part of the winit safe handles work.

kchibisov avatar Oct 17 '23 01:10 kchibisov

That should actually be good to go now, right?

daxpedda avatar Dec 25 '23 06:12 daxpedda

After looking at this a bit more closely, I question how thread safety is achieved here exactly. WindowBuilder is Send, but with_parent() can be called on any thread, but WindowHandle isn't Send. So a WindowHandle that has been passed into with_parent() that would be valid on a thread that is not the main thread, is suddenly being used in the main thread.

daxpedda avatar Dec 25 '23 06:12 daxpedda

thread safety

I think this works on platforms with a "main-thread only" concept, unsure about platforms where a handle may be bound to a specific thread (Windows?)

My reasoning for main thread only being safe on macOS/iOS:

  • WindowHandle<'_> is !Send + !Sync, because it is bound to the main thread.
  • If we get that in with_parent_window, we hence know we're running on the main thread (because of the yet-to-be-documented contract on WindowHandle<'_>).
  • This we put it into OwnedWindowHandle, which contains a MainThreadBound.
  • So now, even though WindowBuilder is moved, we're guaranteed to only access the parent window on the main thread.

madsmtm avatar Dec 25 '23 17:12 madsmtm

If the only valid thread is the main thread, I agree there is no problem, because WindowBuilder only gets consumed in the main thread, which is checked by Winit.

Summarizing remaining problems:

  • How to correctly implement OwnedWindowHandle on all platforms if at all possible, alternatively we have to discuss adding a lifetime to WindowBuilder.
  • Determine thread safety for all platforms. See https://github.com/rust-windowing/raw-window-handle/pull/154 for documenting this in raw-window-handle.

daxpedda avatar Dec 25 '23 17:12 daxpedda