bevy_window/
raw_handle.rs

1#![expect(
2    unsafe_code,
3    reason = "This module acts as a wrapper around the `raw_window_handle` crate, which exposes many unsafe interfaces; thus, we have to use unsafe code here."
4)]
5
6use alloc::sync::Arc;
7use bevy_ecs::prelude::Component;
8use bevy_platform::sync::Mutex;
9use core::{any::Any, marker::PhantomData, ops::Deref};
10use raw_window_handle::{
11    DisplayHandle, HandleError, HasDisplayHandle, HasWindowHandle, RawDisplayHandle,
12    RawWindowHandle, WindowHandle,
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    window_handle: RawWindowHandle,
56    /// Raw handle to the display server.
57    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    /// Gets the stored window handle.
83    pub fn get_window_handle(&self) -> RawWindowHandle {
84        self.window_handle
85    }
86
87    /// Sets the window handle.
88    ///
89    /// # Safety
90    ///
91    /// The passed in [`RawWindowHandle`] must be a valid window handle.
92    // NOTE: The use of an explicit setter instead of a getter for a mutable reference is to limit the amount of time unsoundness can happen.
93    //       If we handed out a mutable reference the user would have to maintain safety invariants throughout its lifetime. For consistency
94    //       we also prefer to handout copies of the handles instead of immutable references.
95    pub unsafe fn set_window_handle(&mut self, window_handle: RawWindowHandle) -> &mut Self {
96        self.window_handle = window_handle;
97
98        self
99    }
100
101    /// Gets the stored display handle
102    pub fn get_display_handle(&self) -> RawDisplayHandle {
103        self.display_handle
104    }
105
106    /// Sets the display handle.
107    ///
108    /// # Safety
109    ///
110    /// The passed in [`RawDisplayHandle`] must be a valid display handle.
111    pub fn set_display_handle(&mut self, display_handle: RawDisplayHandle) -> &mut Self {
112        self.display_handle = display_handle;
113
114        self
115    }
116}
117
118// SAFETY: [`RawHandleWrapper`] is just a normal "raw pointer", which doesn't impl Send/Sync. However the pointer is only
119// exposed via an unsafe method that forces the user to make a call for a given platform. (ex: some platforms don't
120// support doing window operations off of the main thread).
121// A recommendation for this pattern (and more context) is available here:
122// https://github.com/rust-windowing/raw-window-handle/issues/59
123unsafe impl Send for RawHandleWrapper {}
124// SAFETY: This is safe for the same reasons as the Send impl above.
125unsafe impl Sync for RawHandleWrapper {}
126
127/// A [`RawHandleWrapper`] that cannot be sent across threads.
128///
129/// This safely exposes [`RawWindowHandle`] and [`RawDisplayHandle`], but care must be taken to ensure that the construction itself is correct.
130///
131/// This can only be constructed via the [`RawHandleWrapper::get_handle()`] method;
132/// be sure to read the safety docs there about platform-specific limitations.
133/// In many cases, this should only be constructed on the main thread.
134pub struct ThreadLockedRawWindowHandleWrapper(RawHandleWrapper);
135
136impl HasWindowHandle for ThreadLockedRawWindowHandleWrapper {
137    fn window_handle(&self) -> Result<WindowHandle, HandleError> {
138        // SAFETY: the caller has validated that this is a valid context to get [`RawHandleWrapper`]
139        // as otherwise an instance of this type could not have been constructed
140        // NOTE: we cannot simply impl HasRawWindowHandle for RawHandleWrapper,
141        // as the `raw_window_handle` method is safe. We cannot guarantee that all calls
142        // of this method are correct (as it may be off the main thread on an incompatible platform),
143        // and so exposing a safe method to get a [`RawWindowHandle`] directly would be UB.
144        Ok(unsafe { WindowHandle::borrow_raw(self.0.window_handle) })
145    }
146}
147
148impl HasDisplayHandle for ThreadLockedRawWindowHandleWrapper {
149    fn display_handle(&self) -> Result<DisplayHandle, HandleError> {
150        // SAFETY: the caller has validated that this is a valid context to get [`RawDisplayHandle`]
151        // as otherwise an instance of this type could not have been constructed
152        // NOTE: we cannot simply impl HasRawDisplayHandle for RawHandleWrapper,
153        // as the `raw_display_handle` method is safe. We cannot guarantee that all calls
154        // of this method are correct (as it may be off the main thread on an incompatible platform),
155        // and so exposing a safe method to get a [`RawDisplayHandle`] directly would be UB.
156        Ok(unsafe { DisplayHandle::borrow_raw(self.0.display_handle) })
157    }
158}
159
160/// Holder of the [`RawHandleWrapper`] with wrappers, to allow use in asynchronous context
161#[derive(Debug, Clone, Component)]
162pub struct RawHandleWrapperHolder(pub Arc<Mutex<Option<RawHandleWrapper>>>);