Skip to main content

native_gui_core/
window_handle.rs

1//! Native top-level window handles and optional `raw-window-handle` interop.
2//!
3//! [`NativeWindowHandle`] is a plain, always-available descriptor of a
4//! window's platform handles, returned by [`crate::Ui::native_window_handle`].
5//! With the `raw-window-handle` feature, `crate::Ui::window_handle` wraps
6//! it in `UiWindowHandle`, which implements `raw_window_handle` 0.6's
7//! `HasWindowHandle` and `HasDisplayHandle`, so a window can be handed to
8//! renderers such as `wgpu`, `glutin`, or `softbuffer`.
9
10/// Platform handles of a realized top-level window.
11///
12/// The integers are raw pointers / ids owned by the toolkit. They are only
13/// meaningful while the window exists and is realized (shown at least once).
14#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
15#[non_exhaustive]
16pub enum NativeWindowHandle {
17    /// Win32 `HWND` and the module `HINSTANCE`.
18    Win32 { hwnd: usize, hinstance: usize },
19    /// Wayland `wl_surface*` and `wl_display*`.
20    Wayland { surface: usize, display: usize },
21    /// X11 window XID and Xlib `Display*` (screen 0 is reported).
22    X11 { window: u64, display: usize },
23    /// AppKit content `NSView*` of the window.
24    AppKit { ns_view: usize },
25}
26
27#[cfg(feature = "raw-window-handle")]
28pub use rwh::UiWindowHandle;
29
30/// The `raw-window-handle` crate version this library implements (0.6).
31#[cfg(feature = "raw-window-handle")]
32pub use raw_window_handle;
33
34#[cfg(feature = "raw-window-handle")]
35mod rwh {
36    use super::NativeWindowHandle;
37    use core::marker::PhantomData;
38    use core::num::NonZeroIsize;
39    use core::ptr::NonNull;
40    use raw_window_handle::{
41        AppKitDisplayHandle, AppKitWindowHandle, DisplayHandle, HandleError, HasDisplayHandle,
42        HasWindowHandle, RawDisplayHandle, RawWindowHandle, WaylandDisplayHandle,
43        WaylandWindowHandle, Win32WindowHandle, WindowHandle, WindowsDisplayHandle,
44        XlibDisplayHandle, XlibWindowHandle,
45    };
46
47    /// A window's handles borrowed from the [`crate::Ui`] that owns it.
48    ///
49    /// Returned by [`crate::Ui::window_handle`]. Because it borrows the `Ui`,
50    /// the window cannot be removed through the `Ui` while this value is
51    /// alive. Hiding or closing the window natively can still invalidate the
52    /// underlying surface, as with any toolkit handle; re-query after the
53    /// window is shown again.
54    #[derive(Debug, Clone, Copy)]
55    pub struct UiWindowHandle<'a> {
56        native: NativeWindowHandle,
57        _ui: PhantomData<&'a ()>,
58    }
59
60    impl UiWindowHandle<'_> {
61        pub(crate) fn new(native: NativeWindowHandle) -> Self {
62            Self {
63                native,
64                _ui: PhantomData,
65            }
66        }
67
68        /// The plain descriptor behind this handle.
69        pub fn native(&self) -> NativeWindowHandle {
70            self.native
71        }
72
73        fn raw_window(&self) -> Result<RawWindowHandle, HandleError> {
74            Ok(match self.native {
75                NativeWindowHandle::Win32 { hwnd, hinstance } => {
76                    let hwnd = NonZeroIsize::new(hwnd as isize).ok_or(HandleError::Unavailable)?;
77                    let mut handle = Win32WindowHandle::new(hwnd);
78                    handle.hinstance = NonZeroIsize::new(hinstance as isize);
79                    RawWindowHandle::Win32(handle)
80                }
81                NativeWindowHandle::Wayland { surface, .. } => {
82                    let surface = NonNull::new(surface as *mut core::ffi::c_void)
83                        .ok_or(HandleError::Unavailable)?;
84                    RawWindowHandle::Wayland(WaylandWindowHandle::new(surface))
85                }
86                NativeWindowHandle::X11 { window, .. } => {
87                    if window == 0 {
88                        return Err(HandleError::Unavailable);
89                    }
90                    RawWindowHandle::Xlib(XlibWindowHandle::new(window as _))
91                }
92                NativeWindowHandle::AppKit { ns_view } => {
93                    let view = NonNull::new(ns_view as *mut core::ffi::c_void)
94                        .ok_or(HandleError::Unavailable)?;
95                    RawWindowHandle::AppKit(AppKitWindowHandle::new(view))
96                }
97            })
98        }
99
100        fn raw_display(&self) -> Result<RawDisplayHandle, HandleError> {
101            Ok(match self.native {
102                NativeWindowHandle::Win32 { .. } => {
103                    RawDisplayHandle::Windows(WindowsDisplayHandle::new())
104                }
105                NativeWindowHandle::Wayland { display, .. } => {
106                    let display = NonNull::new(display as *mut core::ffi::c_void)
107                        .ok_or(HandleError::Unavailable)?;
108                    RawDisplayHandle::Wayland(WaylandDisplayHandle::new(display))
109                }
110                NativeWindowHandle::X11 { display, .. } => RawDisplayHandle::Xlib(
111                    XlibDisplayHandle::new(NonNull::new(display as *mut core::ffi::c_void), 0),
112                ),
113                NativeWindowHandle::AppKit { .. } => {
114                    RawDisplayHandle::AppKit(AppKitDisplayHandle::new())
115                }
116            })
117        }
118    }
119
120    impl HasWindowHandle for UiWindowHandle<'_> {
121        fn window_handle(&self) -> Result<WindowHandle<'_>, HandleError> {
122            let raw = self.raw_window()?;
123            // SAFETY: the descriptor came from the backend for a live, realized
124            // window, and `self` borrows the owning `Ui`, so the window cannot
125            // be removed through the library while the returned handle lives.
126            Ok(unsafe { WindowHandle::borrow_raw(raw) })
127        }
128    }
129
130    impl HasDisplayHandle for UiWindowHandle<'_> {
131        fn display_handle(&self) -> Result<DisplayHandle<'_>, HandleError> {
132            let raw = self.raw_display()?;
133            // SAFETY: the display connection is owned by the toolkit for the
134            // lifetime of the process (GDK / AppKit / Win32), which outlives
135            // the `Ui` borrow carried by `self`.
136            Ok(unsafe { DisplayHandle::borrow_raw(raw) })
137        }
138    }
139
140    #[cfg(test)]
141    mod tests {
142        use super::*;
143
144        #[test]
145        fn descriptors_convert_to_raw_handles() {
146            let x11 = UiWindowHandle::new(NativeWindowHandle::X11 {
147                window: 0x400_0001,
148                display: 0x1000,
149            });
150            assert!(matches!(
151                x11.window_handle().unwrap().as_raw(),
152                RawWindowHandle::Xlib(h) if h.window == 0x400_0001
153            ));
154            assert!(matches!(
155                x11.display_handle().unwrap().as_raw(),
156                RawDisplayHandle::Xlib(_)
157            ));
158            let wl = UiWindowHandle::new(NativeWindowHandle::Wayland {
159                surface: 0x2000,
160                display: 0x3000,
161            });
162            assert!(matches!(
163                wl.window_handle().unwrap().as_raw(),
164                RawWindowHandle::Wayland(_)
165            ));
166            let win = UiWindowHandle::new(NativeWindowHandle::Win32 {
167                hwnd: 0x10,
168                hinstance: 0,
169            });
170            assert!(matches!(
171                win.window_handle().unwrap().as_raw(),
172                RawWindowHandle::Win32(h) if h.hinstance.is_none()
173            ));
174            let null = UiWindowHandle::new(NativeWindowHandle::AppKit { ns_view: 0 });
175            assert!(null.window_handle().is_err());
176        }
177    }
178}