Skip to main content

compose_rust/
window.rs

1//! The window's measured size, and the registrations a runtime wakes its readers through.
2//!
3//! The UI is authored here but measured by the Renderer, so the only way a Rust component
4//! can know how wide the window is, is for the Renderer to tell it. The Renderer sends one
5//! event when the size class changes and nothing in between, so this module is a single
6//! current value plus the list of readers that asked to be told when it changes. The
7//! Dioxus adapter's `use_window_size` and `use_node_size` hooks are such readers.
8
9use crate::schema::{WindowHeightClass, WindowSizeClass};
10use std::cell::{Cell, RefCell};
11use std::sync::Arc;
12
13/// Insets in dp needed to avoid the window controls.
14///
15/// The controls are the operating system's, whatever design system the application chose,
16/// so which side is non-zero follows the platform: `leading` on macOS, where the system
17/// draws its traffic lights, and `trailing` on Windows (three 46 dp buttons, 138 dp) and on
18/// a Linux window whose buttons the Renderer draws (the desktop's own set). `top` is the
19/// caption's height. All three are zero where the window has no caption to share.
20#[derive(Clone, Copy, Debug, Default, PartialEq)]
21pub struct WindowSafeArea {
22    pub top: f32,
23    pub leading: f32,
24    pub trailing: f32,
25}
26
27/// The window's size, as the Renderer last measured it.
28///
29/// `width_dp` and `height_dp` are density-independent pixels, the same unit gesture
30/// coordinates use. They are the measurements taken at the moment the class last changed,
31/// not a value that follows every pixel of a drag: a size that changed every layout pass
32/// would run the runtime every layout pass.
33#[derive(Clone, Copy, Debug, PartialEq)]
34pub struct WindowSize {
35    pub width_dp: f32,
36    pub height_dp: f32,
37    pub class: WindowSizeClass,
38    pub height_class: WindowHeightClass,
39    pub safe_area: WindowSafeArea,
40}
41
42impl WindowSize {
43    pub const fn new(
44        width_dp: f32,
45        height_dp: f32,
46        class: WindowSizeClass,
47        height_class: WindowHeightClass,
48    ) -> Self {
49        Self {
50            width_dp,
51            height_dp,
52            class,
53            height_class,
54            safe_area: WindowSafeArea {
55                top: 0.0,
56                leading: 0.0,
57                trailing: 0.0,
58            },
59        }
60    }
61
62    pub const fn with_safe_area(mut self, safe_area: WindowSafeArea) -> Self {
63        self.safe_area = safe_area;
64        self
65    }
66
67    /// Phone-shaped: narrower than 600dp. One column.
68    pub fn is_compact(&self) -> bool {
69        matches!(self.class, WindowSizeClass::Compact)
70    }
71
72    /// Tablet-shaped: 600dp to 840dp.
73    pub fn is_medium(&self) -> bool {
74        matches!(self.class, WindowSizeClass::Medium)
75    }
76
77    /// Desktop-shaped: 840dp and wider. Room for a permanent sidebar.
78    pub fn is_expanded(&self) -> bool {
79        matches!(self.class, WindowSizeClass::Expanded)
80    }
81
82    /// Short: under 480dp tall. A phone lying on its side is the usual one, and a column
83    /// of stacked sections is what has to fold there.
84    pub fn is_short(&self) -> bool {
85        matches!(self.height_class, WindowHeightClass::Compact)
86    }
87
88    /// The ordinary height: 480dp to 900dp.
89    pub fn is_medium_height(&self) -> bool {
90        matches!(self.height_class, WindowHeightClass::Medium)
91    }
92
93    /// Tall: 900dp and more. A portrait tablet, or a window someone stretched.
94    pub fn is_tall(&self) -> bool {
95        matches!(self.height_class, WindowHeightClass::Expanded)
96    }
97}
98
99impl Default for WindowSize {
100    /// What a component sees before the Renderer has measured anything.
101    ///
102    /// Compact rather than a wider guess: a one-column layout is usable at any width, so
103    /// the single render that happens before the first measurement arrives is never
104    /// broken, only narrower than it needs to be.
105    fn default() -> Self {
106        Self::new(
107            0.0,
108            0.0,
109            WindowSizeClass::Compact,
110            WindowHeightClass::Compact,
111        )
112    }
113}
114
115struct Subscriber {
116    id: u64,
117    notify: Arc<dyn Fn() + Send + Sync>,
118}
119
120thread_local! {
121    /// What each observed node last measured, by the token its screen gave it.
122    ///
123    /// A map rather than a field, because nothing is in it until a screen asks: a tree
124    /// with no observers keeps an empty map and pays for nothing.
125    static NODES: RefCell<Vec<(u32, WindowSize)>> = const { RefCell::new(Vec::new()) };
126    static NODE_SUBSCRIBERS: RefCell<Vec<(u32, Subscriber)>> = const { RefCell::new(Vec::new()) };
127    static CURRENT: Cell<WindowSize> = const { Cell::new(WindowSize {
128        width_dp: 0.0,
129        height_dp: 0.0,
130        class: WindowSizeClass::Compact,
131        height_class: WindowHeightClass::Compact,
132        safe_area: WindowSafeArea { top: 0.0, leading: 0.0, trailing: 0.0 },
133    }) };
134    static SUBSCRIBERS: RefCell<Vec<Subscriber>> = const { RefCell::new(Vec::new()) };
135    /// What each window of a multi-window application last measured, by the id of its
136    /// `Window` node. Empty in a single-window application, which keeps its one
137    /// value in `CURRENT`.
138    static WINDOWS: RefCell<Vec<(u32, WindowSize)>> = const { RefCell::new(Vec::new()) };
139    static WINDOW_SUBSCRIBERS: RefCell<Vec<(u32, Subscriber)>> = const { RefCell::new(Vec::new()) };
140    static NEXT_SUBSCRIBER_ID: Cell<u64> = const { Cell::new(1) };
141}
142
143/// The size the Renderer last reported. Available outside a component too.
144///
145/// In a multi-window application it is the size of the window the caller is in:
146/// the window a composable is composed in, or the window whose node a handler was called
147/// for. Outside any window it is the single window's, which a multi-window application
148/// never has, so it reads as the default.
149pub fn window_size() -> WindowSize {
150    match crate::windows::current_window_id() {
151        0 => CURRENT.with(Cell::get),
152        window => window_size_of(window),
153    }
154}
155
156/// The size a window last measured, by the id of its `Window` node, or the default for one
157/// nothing has reported yet.
158pub fn window_size_of(window: u32) -> WindowSize {
159    WINDOWS.with_borrow(|windows| {
160        windows
161            .iter()
162            .find(|(id, _)| *id == window)
163            .map(|(_, size)| *size)
164            .unwrap_or_default()
165    })
166}
167
168/// Records one window's measurement and wakes the components in that window that read it.
169/// Returns whether anything was woken. A report for another window wakes nobody here.
170pub(crate) fn publish_window(window: u32, size: WindowSize) -> bool {
171    let changed =
172        WINDOWS.with_borrow_mut(
173            |windows| match windows.iter_mut().find(|(id, _)| *id == window) {
174                Some(entry) => {
175                    if entry.1 == size {
176                        return false;
177                    }
178                    entry.1 = size;
179                    true
180                }
181                None => {
182                    windows.push((window, size));
183                    true
184                }
185            },
186        );
187    if !changed {
188        return false;
189    }
190    WINDOW_SUBSCRIBERS.with_borrow(|subscribers| {
191        let mut woke = false;
192        for (id, subscriber) in subscribers {
193            if *id == window {
194                (subscriber.notify)();
195                woke = true;
196            }
197        }
198        woke
199    })
200}
201
202/// How many windows' sizes and subscriptions are held.
203pub(crate) fn window_state_len() -> usize {
204    WINDOWS.with_borrow(Vec::len) + WINDOW_SUBSCRIBERS.with_borrow(Vec::len)
205}
206
207/// Forgets a window that left the tree, and what it measured.
208pub(crate) fn forget_window(window: u32) {
209    WINDOWS.with_borrow_mut(|windows| windows.retain(|(id, _)| *id != window));
210}
211
212/// A registration for one window's size class. Dropping it ends the registration.
213pub struct WindowSubscription {
214    id: u64,
215}
216
217/// Registers `notify` to be called each time the window `window` measures a different
218/// size class.
219pub fn subscribe_window(window: u32, notify: Arc<dyn Fn() + Send + Sync>) -> WindowSubscription {
220    let id = next_subscriber_id();
221    WINDOW_SUBSCRIBERS.with_borrow_mut(|subscribers| {
222        subscribers.push((window, Subscriber { id, notify }));
223    });
224    WindowSubscription { id }
225}
226
227impl Drop for WindowSubscription {
228    fn drop(&mut self) {
229        WINDOW_SUBSCRIBERS.with_borrow_mut(|subscribers| {
230            subscribers.retain(|(_, subscriber)| subscriber.id != self.id);
231        });
232    }
233}
234
235/// Records a new measurement and wakes the components that asked about it.
236///
237/// Returns whether anything changed. Nothing is allocated here: the subscriber list is
238/// walked in place, and waking a component only marks its scope dirty.
239pub(crate) fn publish(size: WindowSize) -> bool {
240    if CURRENT.with(Cell::get) == size {
241        return false;
242    }
243    CURRENT.with(|current| current.set(size));
244    SUBSCRIBERS.with_borrow(|subscribers| {
245        for subscriber in subscribers {
246            (subscriber.notify)();
247        }
248    });
249    true
250}
251
252/// The size a node last measured, or a zero size for one nothing has reported yet.
253pub fn node_size(token: u32) -> WindowSize {
254    NODES.with_borrow(|nodes| {
255        nodes
256            .iter()
257            .find(|(name, _)| *name == token)
258            .map(|(_, size)| *size)
259            .unwrap_or_default()
260    })
261}
262
263/// Records a node's measurement and wakes whoever asked about that one.
264///
265/// Returns whether anything was woken, so a report about a node nobody is reading costs
266/// a lookup and nothing else.
267pub(crate) fn publish_node(token: u32, size: WindowSize) -> bool {
268    let changed =
269        NODES.with_borrow_mut(
270            |nodes| match nodes.iter_mut().find(|(name, _)| *name == token) {
271                Some(entry) => {
272                    if entry.1 == size {
273                        return false;
274                    }
275                    entry.1 = size;
276                    true
277                }
278                None => {
279                    nodes.push((token, size));
280                    true
281                }
282            },
283        );
284    if !changed {
285        return false;
286    }
287    NODE_SUBSCRIBERS.with_borrow(|subscribers| {
288        let mut woke = false;
289        for (name, subscriber) in subscribers {
290            if *name == token {
291                (subscriber.notify)();
292                woke = true;
293            }
294        }
295        woke
296    })
297}
298
299/// Clears the measurement and every subscription. Used between tests.
300#[doc(hidden)]
301pub fn reset_window_size() {
302    CURRENT.with(|current| current.set(WindowSize::default()));
303    SUBSCRIBERS.with_borrow_mut(Vec::clear);
304    NODES.with_borrow_mut(Vec::clear);
305    NODE_SUBSCRIBERS.with_borrow_mut(Vec::clear);
306    WINDOWS.with_borrow_mut(Vec::clear);
307    WINDOW_SUBSCRIBERS.with_borrow_mut(Vec::clear);
308}
309
310/// A registration for changes of the window's size class. Dropping it ends the
311/// registration, so a runtime keeps it for as long as the reader it wakes is alive.
312pub struct WindowSizeSubscription {
313    id: u64,
314}
315
316/// Registers `notify` to be called each time the window's measured size changes. What
317/// `notify` does is the runtime's business: mark a scope dirty, most often.
318pub fn subscribe(notify: Arc<dyn Fn() + Send + Sync>) -> WindowSizeSubscription {
319    let id = next_subscriber_id();
320    SUBSCRIBERS.with_borrow_mut(|subscribers| subscribers.push(Subscriber { id, notify }));
321    WindowSizeSubscription { id }
322}
323
324fn next_subscriber_id() -> u64 {
325    NEXT_SUBSCRIBER_ID.with(|next| {
326        let id = next.get();
327        next.set(id + 1);
328        id
329    })
330}
331
332impl Drop for WindowSizeSubscription {
333    fn drop(&mut self) {
334        SUBSCRIBERS.with_borrow_mut(|subscribers| {
335            subscribers.retain(|subscriber| subscriber.id != self.id);
336        });
337    }
338}
339
340/// A node whose measured size a reader follows.
341///
342/// The token is the name the screen gives the node, because a node id belongs to the
343/// Renderer and never crosses back as something the Host chose. Attach it with
344/// `observe_size` and read the size here. The Dioxus adapter hands one out from its
345/// `use_node_size` hook.
346///
347/// ```ignore
348/// let panel = use_node_size();
349/// rsx! {
350///     Card {
351///         observe_size: panel.token(),
352///         if panel.is_expanded() { Row { Left {} Right {} } } else { Left {} }
353///     }
354/// }
355/// ```
356///
357/// A component that never calls this costs nothing: the modifier is the only thing that
358/// makes the Renderer measure, and the modifier comes from here.
359#[derive(Clone, Copy, Debug, PartialEq)]
360pub struct NodeSize {
361    token: u32,
362    size: WindowSize,
363}
364
365impl NodeSize {
366    /// The node `token` names, with whatever it last measured.
367    pub fn of(token: u32) -> Self {
368        Self {
369            token,
370            size: node_size(token),
371        }
372    }
373
374    /// The value to hand to `observe_size`.
375    pub const fn token(&self) -> i64 {
376        self.token as i64
377    }
378
379    /// Phone-shaped: narrower than 600dp.
380    pub fn is_compact(&self) -> bool {
381        self.size.is_compact()
382    }
383
384    /// Tablet-shaped.
385    pub fn is_medium(&self) -> bool {
386        self.size.is_medium()
387    }
388
389    /// Desktop-shaped.
390    pub fn is_expanded(&self) -> bool {
391        self.size.is_expanded()
392    }
393
394    /// The measurement itself, zero until the Renderer has reported one.
395    pub const fn measured(&self) -> WindowSize {
396        self.size
397    }
398}
399
400thread_local! {
401    static NEXT_TOKEN: Cell<u32> = const { Cell::new(1) };
402}
403
404/// A fresh name for a node a screen wants measured. Never zero, which is the window's.
405pub fn next_node_token() -> u32 {
406    NEXT_TOKEN.with(|next| {
407        let token = next.get();
408        next.set(token + 1);
409        token
410    })
411}
412
413/// A registration for one node's measured size, made with [`subscribe_node`].
414///
415/// Dropping it ends the registration and forgets what that node measured: the node going
416/// out of the tree takes its measurement with it.
417pub struct NodeSizeSubscription {
418    token: u32,
419    id: u64,
420}
421
422impl NodeSizeSubscription {
423    /// The token this registration follows, the value `observe_size` takes.
424    pub fn token(&self) -> u32 {
425        self.token
426    }
427}
428
429/// Registers `notify` to be called each time the node named `token` reports a size in a
430/// different class.
431pub fn subscribe_node(token: u32, notify: Arc<dyn Fn() + Send + Sync>) -> NodeSizeSubscription {
432    let id = next_subscriber_id();
433    NODE_SUBSCRIBERS.with_borrow_mut(|subscribers| {
434        subscribers.push((token, Subscriber { id, notify }));
435    });
436    NodeSizeSubscription { token, id }
437}
438
439impl Drop for NodeSizeSubscription {
440    fn drop(&mut self) {
441        // The node going out of the tree takes the subscription with it, which is the
442        // third thing this requirement asks for.
443        NODE_SUBSCRIBERS.with_borrow_mut(|subscribers| {
444            subscribers.retain(|(_, subscriber)| subscriber.id != self.id);
445        });
446        NODES.with_borrow_mut(|nodes| nodes.retain(|(token, _)| *token != self.token));
447    }
448}
449
450#[cfg(test)]
451mod tests {
452    use super::*;
453
454    #[test]
455    fn fr19_9_safe_area_only_change_republishes() {
456        use std::sync::atomic::{AtomicUsize, Ordering};
457        reset_window_size();
458        let calls = Arc::new(AtomicUsize::new(0));
459        let counter = Arc::clone(&calls);
460        let _subscription = subscribe(Arc::new(move || {
461            counter.fetch_add(1, Ordering::SeqCst);
462        }));
463        let size = WindowSize::default().with_safe_area(WindowSafeArea {
464            top: 28.0,
465            leading: 70.0,
466            trailing: 0.0,
467        });
468        assert!(publish(size));
469        assert_eq!(window_size(), size);
470        assert_eq!(calls.load(Ordering::SeqCst), 1);
471        assert!(!publish(size));
472        assert_eq!(calls.load(Ordering::SeqCst), 1);
473    }
474
475    #[test]
476    fn fr20_window_size_starts_compact_before_the_renderer_measures_anything() {
477        reset_window_size();
478        assert_eq!(window_size(), WindowSize::default());
479        assert!(window_size().is_compact());
480    }
481
482    #[test]
483    fn fr20_publishing_the_same_size_twice_wakes_nobody() {
484        reset_window_size();
485        let size = WindowSize::new(
486            700.0,
487            800.0,
488            WindowSizeClass::Medium,
489            WindowHeightClass::Medium,
490        );
491        assert!(publish(size));
492        assert!(!publish(size));
493        reset_window_size();
494    }
495}