Skip to main content

mitsuami_core/
surface.rs

1//! What a `GpuSurface` hands the app: a native surface to present to with
2//! its own GPU API, from any thread.
3
4use std::fmt;
5use std::sync::{Arc, Mutex};
6
7use raw_window_handle::{
8    DisplayHandle, HandleError, HasDisplayHandle, HasWindowHandle, RawDisplayHandle, RawWindowHandle, WindowHandle,
9};
10
11/// A backend's native surface: what `raw-window-handle` describes for a
12/// GPU API to present to (an `NSView` backed by a `CAMetalLayer`, a
13/// Wayland surface, a child window).
14///
15/// It lives as long as any [`SurfaceHandle`] to it, even after its widget
16/// is gone, so a GPU surface made on it never outlives it. It may be
17/// dropped on any thread: a backend whose native objects must be freed on
18/// the UI thread sends them there.
19///
20/// # Safety
21///
22/// The handles it returns stay valid for as long as it lives:
23/// [`SurfaceHandle`] lends them to GPU APIs on that promise.
24pub unsafe trait NativeSurface: Send + Sync + 'static {
25    fn window_handle(&self) -> Result<RawWindowHandle, HandleError>;
26    fn display_handle(&self) -> Result<RawDisplayHandle, HandleError>;
27}
28
29/// How large a `GpuSurface` is, in the physical pixels a GPU surface on it
30/// should be configured with, and the scale they are at (pixels to a
31/// point).
32#[derive(Clone, Copy, Debug, Default, PartialEq)]
33pub struct SurfaceSize {
34    pub width: u32,
35    pub height: u32,
36    pub scale: f32,
37}
38
39impl SurfaceSize {
40    pub fn is_empty(self) -> bool {
41        self.width == 0 || self.height == 0
42    }
43}
44
45/// A `GpuSurface`'s native surface, for the app to present to with its own
46/// GPU API (wgpu, Vulkan, Metal, Direct3D), at its own pace and on its own
47/// thread. It implements `raw-window-handle`'s traits, so wgpu takes it as
48/// is: `instance.create_surface(handle.clone())`.
49///
50/// Clones share the surface, which lives until the last one is dropped.
51/// [`size`](SurfaceHandle::size) is kept current by the backend, so a
52/// render thread can read it before each frame.
53#[derive(Clone)]
54pub struct SurfaceHandle {
55    native: Arc<dyn NativeSurface>,
56    size: Arc<Mutex<SurfaceSize>>,
57}
58
59impl SurfaceHandle {
60    /// For backends.
61    pub fn new(native: impl NativeSurface) -> SurfaceHandle {
62        SurfaceHandle { native: Arc::new(native), size: Arc::default() }
63    }
64
65    /// Its size now, in physical pixels.
66    pub fn size(&self) -> SurfaceSize {
67        *self.size.lock().unwrap()
68    }
69
70    /// For backends: the surface's new size. They report it as
71    /// [`UiEvent::SurfaceResized`](crate::UiEvent::SurfaceResized) too.
72    /// Returns whether it changed.
73    pub fn set_size(&self, size: SurfaceSize) -> bool {
74        let mut current = self.size.lock().unwrap();
75        let changed = *current != size;
76        *current = size;
77        changed
78    }
79}
80
81/// Compared by identity: two handles are equal if they share a surface.
82impl PartialEq for SurfaceHandle {
83    fn eq(&self, other: &SurfaceHandle) -> bool {
84        Arc::ptr_eq(&self.size, &other.size)
85    }
86}
87
88impl fmt::Debug for SurfaceHandle {
89    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
90        let SurfaceSize { width, height, scale } = self.size();
91        write!(f, "SurfaceHandle({width}×{height} @{scale}x)")
92    }
93}
94
95impl HasWindowHandle for SurfaceHandle {
96    fn window_handle(&self) -> Result<WindowHandle<'_>, HandleError> {
97        // SAFETY: the native surface lives as long as `self`.
98        self.native.window_handle().map(|raw| unsafe { WindowHandle::borrow_raw(raw) })
99    }
100}
101
102impl HasDisplayHandle for SurfaceHandle {
103    fn display_handle(&self) -> Result<DisplayHandle<'_>, HandleError> {
104        // SAFETY: the native surface keeps its display connection open.
105        self.native.display_handle().map(|raw| unsafe { DisplayHandle::borrow_raw(raw) })
106    }
107}