native-gui-core 1.0.0

Core abstraction, widget model, and layout engine for Native GUI
Documentation
//! Native top-level window handles and optional `raw-window-handle` interop.
//!
//! [`NativeWindowHandle`] is a plain, always-available descriptor of a
//! window's platform handles, returned by [`crate::Ui::native_window_handle`].
//! With the `raw-window-handle` feature, `crate::Ui::window_handle` wraps
//! it in `UiWindowHandle`, which implements `raw_window_handle` 0.6's
//! `HasWindowHandle` and `HasDisplayHandle`, so a window can be handed to
//! renderers such as `wgpu`, `glutin`, or `softbuffer`.

/// Platform handles of a realized top-level window.
///
/// The integers are raw pointers / ids owned by the toolkit. They are only
/// meaningful while the window exists and is realized (shown at least once).
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
#[non_exhaustive]
pub enum NativeWindowHandle {
    /// Win32 `HWND` and the module `HINSTANCE`.
    Win32 { hwnd: usize, hinstance: usize },
    /// Wayland `wl_surface*` and `wl_display*`.
    Wayland { surface: usize, display: usize },
    /// X11 window XID and Xlib `Display*` (screen 0 is reported).
    X11 { window: u64, display: usize },
    /// AppKit content `NSView*` of the window.
    AppKit { ns_view: usize },
}

#[cfg(feature = "raw-window-handle")]
pub use rwh::UiWindowHandle;

/// The `raw-window-handle` crate version this library implements (0.6).
#[cfg(feature = "raw-window-handle")]
pub use raw_window_handle;

#[cfg(feature = "raw-window-handle")]
mod rwh {
    use super::NativeWindowHandle;
    use core::marker::PhantomData;
    use core::num::NonZeroIsize;
    use core::ptr::NonNull;
    use raw_window_handle::{
        AppKitDisplayHandle, AppKitWindowHandle, DisplayHandle, HandleError, HasDisplayHandle,
        HasWindowHandle, RawDisplayHandle, RawWindowHandle, WaylandDisplayHandle,
        WaylandWindowHandle, Win32WindowHandle, WindowHandle, WindowsDisplayHandle,
        XlibDisplayHandle, XlibWindowHandle,
    };

    /// A window's handles borrowed from the [`crate::Ui`] that owns it.
    ///
    /// Returned by [`crate::Ui::window_handle`]. Because it borrows the `Ui`,
    /// the window cannot be removed through the `Ui` while this value is
    /// alive. Hiding or closing the window natively can still invalidate the
    /// underlying surface, as with any toolkit handle; re-query after the
    /// window is shown again.
    #[derive(Debug, Clone, Copy)]
    pub struct UiWindowHandle<'a> {
        native: NativeWindowHandle,
        _ui: PhantomData<&'a ()>,
    }

    impl UiWindowHandle<'_> {
        pub(crate) fn new(native: NativeWindowHandle) -> Self {
            Self {
                native,
                _ui: PhantomData,
            }
        }

        /// The plain descriptor behind this handle.
        pub fn native(&self) -> NativeWindowHandle {
            self.native
        }

        fn raw_window(&self) -> Result<RawWindowHandle, HandleError> {
            Ok(match self.native {
                NativeWindowHandle::Win32 { hwnd, hinstance } => {
                    let hwnd = NonZeroIsize::new(hwnd as isize).ok_or(HandleError::Unavailable)?;
                    let mut handle = Win32WindowHandle::new(hwnd);
                    handle.hinstance = NonZeroIsize::new(hinstance as isize);
                    RawWindowHandle::Win32(handle)
                }
                NativeWindowHandle::Wayland { surface, .. } => {
                    let surface = NonNull::new(surface as *mut core::ffi::c_void)
                        .ok_or(HandleError::Unavailable)?;
                    RawWindowHandle::Wayland(WaylandWindowHandle::new(surface))
                }
                NativeWindowHandle::X11 { window, .. } => {
                    if window == 0 {
                        return Err(HandleError::Unavailable);
                    }
                    RawWindowHandle::Xlib(XlibWindowHandle::new(window as _))
                }
                NativeWindowHandle::AppKit { ns_view } => {
                    let view = NonNull::new(ns_view as *mut core::ffi::c_void)
                        .ok_or(HandleError::Unavailable)?;
                    RawWindowHandle::AppKit(AppKitWindowHandle::new(view))
                }
            })
        }

        fn raw_display(&self) -> Result<RawDisplayHandle, HandleError> {
            Ok(match self.native {
                NativeWindowHandle::Win32 { .. } => {
                    RawDisplayHandle::Windows(WindowsDisplayHandle::new())
                }
                NativeWindowHandle::Wayland { display, .. } => {
                    let display = NonNull::new(display as *mut core::ffi::c_void)
                        .ok_or(HandleError::Unavailable)?;
                    RawDisplayHandle::Wayland(WaylandDisplayHandle::new(display))
                }
                NativeWindowHandle::X11 { display, .. } => RawDisplayHandle::Xlib(
                    XlibDisplayHandle::new(NonNull::new(display as *mut core::ffi::c_void), 0),
                ),
                NativeWindowHandle::AppKit { .. } => {
                    RawDisplayHandle::AppKit(AppKitDisplayHandle::new())
                }
            })
        }
    }

    impl HasWindowHandle for UiWindowHandle<'_> {
        fn window_handle(&self) -> Result<WindowHandle<'_>, HandleError> {
            let raw = self.raw_window()?;
            // SAFETY: the descriptor came from the backend for a live, realized
            // window, and `self` borrows the owning `Ui`, so the window cannot
            // be removed through the library while the returned handle lives.
            Ok(unsafe { WindowHandle::borrow_raw(raw) })
        }
    }

    impl HasDisplayHandle for UiWindowHandle<'_> {
        fn display_handle(&self) -> Result<DisplayHandle<'_>, HandleError> {
            let raw = self.raw_display()?;
            // SAFETY: the display connection is owned by the toolkit for the
            // lifetime of the process (GDK / AppKit / Win32), which outlives
            // the `Ui` borrow carried by `self`.
            Ok(unsafe { DisplayHandle::borrow_raw(raw) })
        }
    }

    #[cfg(test)]
    mod tests {
        use super::*;

        #[test]
        fn descriptors_convert_to_raw_handles() {
            let x11 = UiWindowHandle::new(NativeWindowHandle::X11 {
                window: 0x400_0001,
                display: 0x1000,
            });
            assert!(matches!(
                x11.window_handle().unwrap().as_raw(),
                RawWindowHandle::Xlib(h) if h.window == 0x400_0001
            ));
            assert!(matches!(
                x11.display_handle().unwrap().as_raw(),
                RawDisplayHandle::Xlib(_)
            ));
            let wl = UiWindowHandle::new(NativeWindowHandle::Wayland {
                surface: 0x2000,
                display: 0x3000,
            });
            assert!(matches!(
                wl.window_handle().unwrap().as_raw(),
                RawWindowHandle::Wayland(_)
            ));
            let win = UiWindowHandle::new(NativeWindowHandle::Win32 {
                hwnd: 0x10,
                hinstance: 0,
            });
            assert!(matches!(
                win.window_handle().unwrap().as_raw(),
                RawWindowHandle::Win32(h) if h.hinstance.is_none()
            ));
            let null = UiWindowHandle::new(NativeWindowHandle::AppKit { ns_view: 0 });
            assert!(null.window_handle().is_err());
        }
    }
}