bevy_window/raw_handle.rs
1#![allow(unsafe_code)]
2
3use bevy_ecs::prelude::Component;
4use raw_window_handle::{
5 DisplayHandle, HandleError, HasDisplayHandle, HasWindowHandle, RawDisplayHandle,
6 RawWindowHandle, WindowHandle,
7};
8use std::{
9 any::Any,
10 marker::PhantomData,
11 ops::Deref,
12 sync::{Arc, Mutex},
13};
14
15/// A wrapper over a window.
16///
17/// This allows us to extend the lifetime of the window, so it doesn't get eagerly dropped while a
18/// pipelined renderer still has frames in flight that need to draw to it.
19///
20/// This is achieved by storing a shared reference to the window in the [`RawHandleWrapper`],
21/// which gets picked up by the renderer during extraction.
22#[derive(Debug)]
23pub struct WindowWrapper<W> {
24 reference: Arc<dyn Any + Send + Sync>,
25 ty: PhantomData<W>,
26}
27
28impl<W: Send + Sync + 'static> WindowWrapper<W> {
29 /// Creates a `WindowWrapper` from a window.
30 pub fn new(window: W) -> WindowWrapper<W> {
31 WindowWrapper {
32 reference: Arc::new(window),
33 ty: PhantomData,
34 }
35 }
36}
37
38impl<W: 'static> Deref for WindowWrapper<W> {
39 type Target = W;
40
41 fn deref(&self) -> &Self::Target {
42 self.reference.downcast_ref::<W>().unwrap()
43 }
44}
45
46/// A wrapper over [`RawWindowHandle`] and [`RawDisplayHandle`] that allows us to safely pass it across threads.
47///
48/// Depending on the platform, the underlying pointer-containing handle cannot be used on all threads,
49/// and so we cannot simply make it (or any type that has a safe operation to get a [`RawWindowHandle`] or [`RawDisplayHandle`])
50/// thread-safe.
51#[derive(Debug, Clone, Component)]
52pub struct RawHandleWrapper {
53 _window: Arc<dyn Any + Send + Sync>,
54 /// Raw handle to a window.
55 pub window_handle: RawWindowHandle,
56 /// Raw handle to the display server.
57 pub display_handle: RawDisplayHandle,
58}
59
60impl RawHandleWrapper {
61 /// Creates a `RawHandleWrapper` from a `WindowWrapper`.
62 pub fn new<W: HasWindowHandle + HasDisplayHandle + 'static>(
63 window: &WindowWrapper<W>,
64 ) -> Result<RawHandleWrapper, HandleError> {
65 Ok(RawHandleWrapper {
66 _window: window.reference.clone(),
67 window_handle: window.window_handle()?.as_raw(),
68 display_handle: window.display_handle()?.as_raw(),
69 })
70 }
71
72 /// Returns a [`HasWindowHandle`] + [`HasDisplayHandle`] impl, which exposes [`WindowHandle`] and [`DisplayHandle`].
73 ///
74 /// # Safety
75 ///
76 /// Some platforms have constraints on where/how this handle can be used. For example, some platforms don't support doing window
77 /// operations off of the main thread. The caller must ensure the [`RawHandleWrapper`] is only used in valid contexts.
78 pub unsafe fn get_handle(&self) -> ThreadLockedRawWindowHandleWrapper {
79 ThreadLockedRawWindowHandleWrapper(self.clone())
80 }
81}
82
83// SAFETY: [`RawHandleWrapper`] is just a normal "raw pointer", which doesn't impl Send/Sync. However the pointer is only
84// exposed via an unsafe method that forces the user to make a call for a given platform. (ex: some platforms don't
85// support doing window operations off of the main thread).
86// A recommendation for this pattern (and more context) is available here:
87// https://github.com/rust-windowing/raw-window-handle/issues/59
88unsafe impl Send for RawHandleWrapper {}
89// SAFETY: This is safe for the same reasons as the Send impl above.
90unsafe impl Sync for RawHandleWrapper {}
91
92/// A [`RawHandleWrapper`] that cannot be sent across threads.
93///
94/// This safely exposes [`RawWindowHandle`] and [`RawDisplayHandle`], but care must be taken to ensure that the construction itself is correct.
95///
96/// This can only be constructed via the [`RawHandleWrapper::get_handle()`] method;
97/// be sure to read the safety docs there about platform-specific limitations.
98/// In many cases, this should only be constructed on the main thread.
99pub struct ThreadLockedRawWindowHandleWrapper(RawHandleWrapper);
100
101impl HasWindowHandle for ThreadLockedRawWindowHandleWrapper {
102 fn window_handle(&self) -> Result<WindowHandle, HandleError> {
103 // SAFETY: the caller has validated that this is a valid context to get [`RawHandleWrapper`]
104 // as otherwise an instance of this type could not have been constructed
105 // NOTE: we cannot simply impl HasRawWindowHandle for RawHandleWrapper,
106 // as the `raw_window_handle` method is safe. We cannot guarantee that all calls
107 // of this method are correct (as it may be off the main thread on an incompatible platform),
108 // and so exposing a safe method to get a [`RawWindowHandle`] directly would be UB.
109 Ok(unsafe { WindowHandle::borrow_raw(self.0.window_handle) })
110 }
111}
112
113impl HasDisplayHandle for ThreadLockedRawWindowHandleWrapper {
114 fn display_handle(&self) -> Result<DisplayHandle, HandleError> {
115 // SAFETY: the caller has validated that this is a valid context to get [`RawDisplayHandle`]
116 // as otherwise an instance of this type could not have been constructed
117 // NOTE: we cannot simply impl HasRawDisplayHandle for RawHandleWrapper,
118 // as the `raw_display_handle` method is safe. We cannot guarantee that all calls
119 // of this method are correct (as it may be off the main thread on an incompatible platform),
120 // and so exposing a safe method to get a [`RawDisplayHandle`] directly would be UB.
121 Ok(unsafe { DisplayHandle::borrow_raw(self.0.display_handle) })
122 }
123}
124
125/// Holder of the [`RawHandleWrapper`] with wrappers, to allow use in asynchronous context
126#[derive(Debug, Clone, Component)]
127pub struct RawHandleWrapperHolder(pub Arc<Mutex<Option<RawHandleWrapper>>>);