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/// The window's size, as the Renderer last measured it.
14///
15/// `width_dp` and `height_dp` are density-independent pixels, the same unit gesture
16/// coordinates use. They are the measurements taken at the moment the class last changed,
17/// not a value that follows every pixel of a drag: a size that changed every layout pass
18/// would run the runtime every layout pass.
19#[derive(Clone, Copy, Debug, PartialEq)]
20pub struct WindowSize {
21    pub width_dp: f32,
22    pub height_dp: f32,
23    pub class: WindowSizeClass,
24    pub height_class: WindowHeightClass,
25}
26
27impl WindowSize {
28    pub const fn new(
29        width_dp: f32,
30        height_dp: f32,
31        class: WindowSizeClass,
32        height_class: WindowHeightClass,
33    ) -> Self {
34        Self {
35            width_dp,
36            height_dp,
37            class,
38            height_class,
39        }
40    }
41
42    /// Phone-shaped: narrower than 600dp. One column.
43    pub fn is_compact(&self) -> bool {
44        matches!(self.class, WindowSizeClass::Compact)
45    }
46
47    /// Tablet-shaped: 600dp to 840dp.
48    pub fn is_medium(&self) -> bool {
49        matches!(self.class, WindowSizeClass::Medium)
50    }
51
52    /// Desktop-shaped: 840dp and wider. Room for a permanent sidebar.
53    pub fn is_expanded(&self) -> bool {
54        matches!(self.class, WindowSizeClass::Expanded)
55    }
56
57    /// Short: under 480dp tall. A phone lying on its side is the usual one, and a column
58    /// of stacked sections is what has to fold there.
59    pub fn is_short(&self) -> bool {
60        matches!(self.height_class, WindowHeightClass::Compact)
61    }
62
63    /// The ordinary height: 480dp to 900dp.
64    pub fn is_medium_height(&self) -> bool {
65        matches!(self.height_class, WindowHeightClass::Medium)
66    }
67
68    /// Tall: 900dp and more. A portrait tablet, or a window someone stretched.
69    pub fn is_tall(&self) -> bool {
70        matches!(self.height_class, WindowHeightClass::Expanded)
71    }
72}
73
74impl Default for WindowSize {
75    /// What a component sees before the Renderer has measured anything.
76    ///
77    /// Compact rather than a wider guess: a one-column layout is usable at any width, so
78    /// the single render that happens before the first measurement arrives is never
79    /// broken, only narrower than it needs to be.
80    fn default() -> Self {
81        Self::new(
82            0.0,
83            0.0,
84            WindowSizeClass::Compact,
85            WindowHeightClass::Compact,
86        )
87    }
88}
89
90struct Subscriber {
91    id: u64,
92    notify: Arc<dyn Fn() + Send + Sync>,
93}
94
95thread_local! {
96    /// What each observed node last measured, by the token its screen gave it.
97    ///
98    /// A map rather than a field, because nothing is in it until a screen asks: a tree
99    /// with no observers keeps an empty map and pays for nothing.
100    static NODES: RefCell<Vec<(u32, WindowSize)>> = const { RefCell::new(Vec::new()) };
101    static NODE_SUBSCRIBERS: RefCell<Vec<(u32, Subscriber)>> = const { RefCell::new(Vec::new()) };
102    static CURRENT: Cell<WindowSize> = const { Cell::new(WindowSize {
103        width_dp: 0.0,
104        height_dp: 0.0,
105        class: WindowSizeClass::Compact,
106        height_class: WindowHeightClass::Compact,
107    }) };
108    static SUBSCRIBERS: RefCell<Vec<Subscriber>> = const { RefCell::new(Vec::new()) };
109    static NEXT_SUBSCRIBER_ID: Cell<u64> = const { Cell::new(1) };
110}
111
112/// The size the Renderer last reported. Available outside a component too.
113pub fn window_size() -> WindowSize {
114    CURRENT.with(Cell::get)
115}
116
117/// Records a new measurement and wakes the components that asked about it.
118///
119/// Returns whether anything changed. Nothing is allocated here: the subscriber list is
120/// walked in place, and waking a component only marks its scope dirty.
121pub(crate) fn publish(size: WindowSize) -> bool {
122    if CURRENT.with(Cell::get) == size {
123        return false;
124    }
125    CURRENT.with(|current| current.set(size));
126    SUBSCRIBERS.with_borrow(|subscribers| {
127        for subscriber in subscribers {
128            (subscriber.notify)();
129        }
130    });
131    true
132}
133
134/// The size a node last measured, or a zero size for one nothing has reported yet.
135pub fn node_size(token: u32) -> WindowSize {
136    NODES.with_borrow(|nodes| {
137        nodes
138            .iter()
139            .find(|(name, _)| *name == token)
140            .map(|(_, size)| *size)
141            .unwrap_or_default()
142    })
143}
144
145/// Records a node's measurement and wakes whoever asked about that one.
146///
147/// Returns whether anything was woken, so a report about a node nobody is reading costs
148/// a lookup and nothing else.
149pub(crate) fn publish_node(token: u32, size: WindowSize) -> bool {
150    let changed =
151        NODES.with_borrow_mut(
152            |nodes| match nodes.iter_mut().find(|(name, _)| *name == token) {
153                Some(entry) => {
154                    if entry.1 == size {
155                        return false;
156                    }
157                    entry.1 = size;
158                    true
159                }
160                None => {
161                    nodes.push((token, size));
162                    true
163                }
164            },
165        );
166    if !changed {
167        return false;
168    }
169    NODE_SUBSCRIBERS.with_borrow(|subscribers| {
170        let mut woke = false;
171        for (name, subscriber) in subscribers {
172            if *name == token {
173                (subscriber.notify)();
174                woke = true;
175            }
176        }
177        woke
178    })
179}
180
181/// Clears the measurement and every subscription. Used between tests.
182#[doc(hidden)]
183pub fn reset_window_size() {
184    CURRENT.with(|current| current.set(WindowSize::default()));
185    SUBSCRIBERS.with_borrow_mut(Vec::clear);
186    NODES.with_borrow_mut(Vec::clear);
187    NODE_SUBSCRIBERS.with_borrow_mut(Vec::clear);
188}
189
190/// A registration for changes of the window's size class. Dropping it ends the
191/// registration, so a runtime keeps it for as long as the reader it wakes is alive.
192pub struct WindowSizeSubscription {
193    id: u64,
194}
195
196/// Registers `notify` to be called each time the window's measured size changes. What
197/// `notify` does is the runtime's business: mark a scope dirty, most often.
198pub fn subscribe(notify: Arc<dyn Fn() + Send + Sync>) -> WindowSizeSubscription {
199    let id = next_subscriber_id();
200    SUBSCRIBERS.with_borrow_mut(|subscribers| subscribers.push(Subscriber { id, notify }));
201    WindowSizeSubscription { id }
202}
203
204fn next_subscriber_id() -> u64 {
205    NEXT_SUBSCRIBER_ID.with(|next| {
206        let id = next.get();
207        next.set(id + 1);
208        id
209    })
210}
211
212impl Drop for WindowSizeSubscription {
213    fn drop(&mut self) {
214        SUBSCRIBERS.with_borrow_mut(|subscribers| {
215            subscribers.retain(|subscriber| subscriber.id != self.id);
216        });
217    }
218}
219
220/// A node whose measured size a reader follows.
221///
222/// The token is the name the screen gives the node, because a node id belongs to the
223/// Renderer and never crosses back as something the Host chose. Attach it with
224/// `observe_size` and read the size here. The Dioxus adapter hands one out from its
225/// `use_node_size` hook.
226///
227/// ```ignore
228/// let panel = use_node_size();
229/// rsx! {
230///     Card {
231///         observe_size: panel.token(),
232///         if panel.is_expanded() { Row { Left {} Right {} } } else { Left {} }
233///     }
234/// }
235/// ```
236///
237/// A component that never calls this costs nothing: the modifier is the only thing that
238/// makes the Renderer measure, and the modifier comes from here.
239#[derive(Clone, Copy, Debug, PartialEq)]
240pub struct NodeSize {
241    token: u32,
242    size: WindowSize,
243}
244
245impl NodeSize {
246    /// The node `token` names, with whatever it last measured.
247    pub fn of(token: u32) -> Self {
248        Self {
249            token,
250            size: node_size(token),
251        }
252    }
253
254    /// The value to hand to `observe_size`.
255    pub const fn token(&self) -> i64 {
256        self.token as i64
257    }
258
259    /// Phone-shaped: narrower than 600dp.
260    pub fn is_compact(&self) -> bool {
261        self.size.is_compact()
262    }
263
264    /// Tablet-shaped.
265    pub fn is_medium(&self) -> bool {
266        self.size.is_medium()
267    }
268
269    /// Desktop-shaped.
270    pub fn is_expanded(&self) -> bool {
271        self.size.is_expanded()
272    }
273
274    /// The measurement itself, zero until the Renderer has reported one.
275    pub const fn measured(&self) -> WindowSize {
276        self.size
277    }
278}
279
280thread_local! {
281    static NEXT_TOKEN: Cell<u32> = const { Cell::new(1) };
282}
283
284/// A fresh name for a node a screen wants measured. Never zero, which is the window's.
285pub fn next_node_token() -> u32 {
286    NEXT_TOKEN.with(|next| {
287        let token = next.get();
288        next.set(token + 1);
289        token
290    })
291}
292
293/// A registration for one node's measured size, made with [`subscribe_node`].
294///
295/// Dropping it ends the registration and forgets what that node measured: the node going
296/// out of the tree takes its measurement with it.
297pub struct NodeSizeSubscription {
298    token: u32,
299    id: u64,
300}
301
302impl NodeSizeSubscription {
303    /// The token this registration follows, the value `observe_size` takes.
304    pub fn token(&self) -> u32 {
305        self.token
306    }
307}
308
309/// Registers `notify` to be called each time the node named `token` reports a size in a
310/// different class.
311pub fn subscribe_node(token: u32, notify: Arc<dyn Fn() + Send + Sync>) -> NodeSizeSubscription {
312    let id = next_subscriber_id();
313    NODE_SUBSCRIBERS.with_borrow_mut(|subscribers| {
314        subscribers.push((token, Subscriber { id, notify }));
315    });
316    NodeSizeSubscription { token, id }
317}
318
319impl Drop for NodeSizeSubscription {
320    fn drop(&mut self) {
321        // The node going out of the tree takes the subscription with it, which is the
322        // third thing this requirement asks for.
323        NODE_SUBSCRIBERS.with_borrow_mut(|subscribers| {
324            subscribers.retain(|(_, subscriber)| subscriber.id != self.id);
325        });
326        NODES.with_borrow_mut(|nodes| nodes.retain(|(token, _)| *token != self.token));
327    }
328}
329
330#[cfg(test)]
331mod tests {
332    use super::*;
333
334    #[test]
335    fn fr20_window_size_starts_compact_before_the_renderer_measures_anything() {
336        reset_window_size();
337        assert_eq!(window_size(), WindowSize::default());
338        assert!(window_size().is_compact());
339    }
340
341    #[test]
342    fn fr20_publishing_the_same_size_twice_wakes_nobody() {
343        reset_window_size();
344        let size = WindowSize::new(
345            700.0,
346            800.0,
347            WindowSizeClass::Medium,
348            WindowHeightClass::Medium,
349        );
350        assert!(publish(size));
351        assert!(!publish(size));
352        reset_window_size();
353    }
354}