Skip to main content

cranpose_services/
host_surface.rs

1//! The surface the host gives the application, and what the application may
2//! ask of it.
3//!
4//! On the web that is the canvas inside its page; on desktop the window's
5//! client area; on mobile the activity's content view. An application that
6//! wants to lay out against it — or, on a host that allows it, ask for a
7//! different size — reads observable state here instead of reaching for a
8//! platform API and a resize callback of its own.
9
10use std::sync::{Arc, Mutex, OnceLock, atomic::Ordering};
11
12use cranpose_core::{State, rememberEventStream};
13use portable_atomic::AtomicU64;
14
15use crate::registry::ServiceRegistry;
16
17/// The size of the host surface, in logical pixels, with the scale the host
18/// renders it at.
19#[derive(Clone, Copy, Debug, PartialEq)]
20pub struct HostSurfaceSize {
21    /// Logical width.
22    pub width: f32,
23    /// Logical height.
24    pub height: f32,
25    /// Physical pixels per logical pixel.
26    pub scale: f32,
27}
28
29impl Default for HostSurfaceSize {
30    fn default() -> Self {
31        Self {
32            width: 0.0,
33            height: 0.0,
34            scale: 1.0,
35        }
36    }
37}
38
39impl HostSurfaceSize {
40    /// The size in physical pixels.
41    pub fn physical(&self) -> (u32, u32) {
42        (
43            (self.width * self.scale).round().max(0.0) as u32,
44            (self.height * self.scale).round().max(0.0) as u32,
45        )
46    }
47}
48
49/// Why a resize request was refused.
50#[derive(Clone, Copy, Debug, PartialEq, Eq, thiserror::Error)]
51pub enum ResizeRefused {
52    /// This host does not let an application choose its surface size — a
53    /// fullscreen mobile activity, a maximised window, a fixed canvas.
54    #[error("this host does not accept surface resize requests")]
55    Unsupported,
56    /// The host accepted the idea but refused these dimensions.
57    #[error("the host refused the requested surface size")]
58    Rejected,
59}
60
61/// What an application may ask of the host's surface.
62///
63/// The surface's *size* is not asked of a backend: every host publishes it as
64/// it lays the surface out, and [`host_surface_size`] answers from that. What a
65/// backend adds is the other direction — whether this host lets the application
66/// choose a size, and how to ask for one.
67pub trait HostSurface: Send + Sync {
68    /// Whether this host accepts resize requests at all.
69    fn can_resize(&self) -> bool {
70        false
71    }
72
73    /// Asks the host for a different surface size.
74    ///
75    /// Hosts are free to clamp or ignore the request, so the answer is only
76    /// "the request was accepted": the size that actually took effect arrives
77    /// through the observable state.
78    fn request_size(&self, width: f32, height: f32) -> Result<(), ResizeRefused> {
79        let _ = (width, height);
80        Err(ResizeRefused::Unsupported)
81    }
82}
83
84/// Shared handle to a [`HostSurface`].
85pub type HostSurfaceRef = Arc<dyn HostSurface>;
86
87struct NoHostSurface;
88
89impl HostSurface for NoHostSurface {}
90
91static PLATFORM_HOST_SURFACE: ServiceRegistry<dyn HostSurface> = ServiceRegistry::new();
92
93/// Installs the platform host surface.
94pub fn set_platform_host_surface(surface: HostSurfaceRef) {
95    PLATFORM_HOST_SURFACE.set(surface);
96}
97
98/// Removes the installed host surface (tests and teardown).
99pub fn clear_platform_host_surface() {
100    PLATFORM_HOST_SURFACE.clear();
101    if let Ok(mut observers) = observers().lock() {
102        observers.clear();
103    }
104    if let Ok(mut last) = last_published().lock() {
105        *last = HostSurfaceSize::default();
106    }
107}
108
109/// Whether this host lets the application choose its surface size.
110pub fn host_surface_can_resize() -> bool {
111    host_surface().can_resize()
112}
113
114/// The installed host surface, or one that accepts no resize requests.
115pub fn host_surface() -> HostSurfaceRef {
116    PLATFORM_HOST_SURFACE
117        .get()
118        .unwrap_or_else(|| Arc::new(NoHostSurface))
119}
120
121/// The size the host last reported.
122///
123/// Read from what the host published rather than asked of a backend: every host
124/// publishes its surface as it lays it out, and a host that has no resize
125/// facility to install a backend for still reports its size. Before the first
126/// frame this is the empty surface at scale one — nothing has been measured
127/// yet — so a caller that needs the real value observes
128/// [`rememberHostSurfaceSize`] rather than sampling once at startup.
129pub fn host_surface_size() -> HostSurfaceSize {
130    last_published()
131        .lock()
132        .map(|size| *size)
133        .unwrap_or_default()
134}
135
136fn last_published() -> &'static Mutex<HostSurfaceSize> {
137    static SLOT: OnceLock<Mutex<HostSurfaceSize>> = OnceLock::new();
138    SLOT.get_or_init(|| Mutex::new(HostSurfaceSize::default()))
139}
140
141/// Asks the host for a different surface size.
142pub fn request_host_surface_size(width: f32, height: f32) -> Result<(), ResizeRefused> {
143    host_surface().request_size(width, height)
144}
145
146type Observer = Arc<dyn Fn(HostSurfaceSize) + Send + Sync>;
147
148fn observers() -> &'static Mutex<Vec<(u64, Observer)>> {
149    static SLOT: OnceLock<Mutex<Vec<(u64, Observer)>>> = OnceLock::new();
150    SLOT.get_or_init(|| Mutex::new(Vec::new()))
151}
152
153static NEXT_OBSERVER: AtomicU64 = AtomicU64::new(1);
154
155/// Keeps a host-surface observer registered until it is dropped.
156pub struct HostSurfaceObserver {
157    id: u64,
158}
159
160impl Drop for HostSurfaceObserver {
161    fn drop(&mut self) {
162        if let Ok(mut observers) = observers().lock() {
163            observers.retain(|(id, _)| *id != self.id);
164        }
165    }
166}
167
168/// Registers `observer` for host-surface size changes. Applications collect
169/// [`rememberHostSurfaceSize`] instead of calling this.
170pub fn observe_host_surface_size(
171    observer: impl Fn(HostSurfaceSize) + Send + Sync + 'static,
172) -> HostSurfaceObserver {
173    let id = NEXT_OBSERVER.fetch_add(1, Ordering::Relaxed);
174    if let Ok(mut observers) = observers().lock() {
175        observers.push((id, Arc::new(observer)));
176    }
177    HostSurfaceObserver { id }
178}
179
180/// Publishes a new host-surface size. Platform backends call this whenever the
181/// host resizes the surface.
182pub fn publish_host_surface_size(size: HostSurfaceSize) {
183    if let Ok(mut last) = last_published().lock() {
184        if *last == size {
185            return;
186        }
187        *last = size;
188    }
189    let observers = observers()
190        .lock()
191        .map(|observers| {
192            observers
193                .iter()
194                .map(|(_, observer)| Arc::clone(observer))
195                .collect::<Vec<_>>()
196        })
197        .unwrap_or_default();
198    for observer in observers {
199        observer(size);
200    }
201}
202
203/// The host surface's size, observed for as long as this call stays in the
204/// composition.
205#[expect(non_snake_case)]
206#[track_caller]
207pub fn rememberHostSurfaceSize() -> State<HostSurfaceSize> {
208    let updates = rememberEventStream((), |sender| {
209        observe_host_surface_size(move |size| sender.send(size))
210    });
211    cranpose_core::collectAsState(updates, (), host_surface_size())
212}
213
214#[cfg(test)]
215#[path = "tests/host_surface_tests.rs"]
216mod tests;