compose-rust 0.0.6

Declarative UI in Rust, rendered by an AOT-compiled Compose Multiplatform engine.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
//! The window's measured size, and the registrations a runtime wakes its readers through.
//!
//! The UI is authored here but measured by the Renderer, so the only way a Rust component
//! can know how wide the window is, is for the Renderer to tell it. The Renderer sends one
//! event when the size class changes and nothing in between, so this module is a single
//! current value plus the list of readers that asked to be told when it changes. The
//! Dioxus adapter's `use_window_size` and `use_node_size` hooks are such readers.

use crate::schema::{WindowHeightClass, WindowSizeClass};
use std::cell::{Cell, RefCell};
use std::sync::Arc;

/// Insets in dp needed to avoid the window controls.
#[derive(Clone, Copy, Debug, Default, PartialEq)]
pub struct WindowSafeArea {
    pub top: f32,
    pub leading: f32,
    pub trailing: f32,
}

/// The window's size, as the Renderer last measured it.
///
/// `width_dp` and `height_dp` are density-independent pixels, the same unit gesture
/// coordinates use. They are the measurements taken at the moment the class last changed,
/// not a value that follows every pixel of a drag: a size that changed every layout pass
/// would run the runtime every layout pass.
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct WindowSize {
    pub width_dp: f32,
    pub height_dp: f32,
    pub class: WindowSizeClass,
    pub height_class: WindowHeightClass,
    pub safe_area: WindowSafeArea,
}

impl WindowSize {
    pub const fn new(
        width_dp: f32,
        height_dp: f32,
        class: WindowSizeClass,
        height_class: WindowHeightClass,
    ) -> Self {
        Self {
            width_dp,
            height_dp,
            class,
            height_class,
            safe_area: WindowSafeArea {
                top: 0.0,
                leading: 0.0,
                trailing: 0.0,
            },
        }
    }

    pub const fn with_safe_area(mut self, safe_area: WindowSafeArea) -> Self {
        self.safe_area = safe_area;
        self
    }

    /// Phone-shaped: narrower than 600dp. One column.
    pub fn is_compact(&self) -> bool {
        matches!(self.class, WindowSizeClass::Compact)
    }

    /// Tablet-shaped: 600dp to 840dp.
    pub fn is_medium(&self) -> bool {
        matches!(self.class, WindowSizeClass::Medium)
    }

    /// Desktop-shaped: 840dp and wider. Room for a permanent sidebar.
    pub fn is_expanded(&self) -> bool {
        matches!(self.class, WindowSizeClass::Expanded)
    }

    /// Short: under 480dp tall. A phone lying on its side is the usual one, and a column
    /// of stacked sections is what has to fold there.
    pub fn is_short(&self) -> bool {
        matches!(self.height_class, WindowHeightClass::Compact)
    }

    /// The ordinary height: 480dp to 900dp.
    pub fn is_medium_height(&self) -> bool {
        matches!(self.height_class, WindowHeightClass::Medium)
    }

    /// Tall: 900dp and more. A portrait tablet, or a window someone stretched.
    pub fn is_tall(&self) -> bool {
        matches!(self.height_class, WindowHeightClass::Expanded)
    }
}

impl Default for WindowSize {
    /// What a component sees before the Renderer has measured anything.
    ///
    /// Compact rather than a wider guess: a one-column layout is usable at any width, so
    /// the single render that happens before the first measurement arrives is never
    /// broken, only narrower than it needs to be.
    fn default() -> Self {
        Self::new(
            0.0,
            0.0,
            WindowSizeClass::Compact,
            WindowHeightClass::Compact,
        )
    }
}

struct Subscriber {
    id: u64,
    notify: Arc<dyn Fn() + Send + Sync>,
}

thread_local! {
    /// What each observed node last measured, by the token its screen gave it.
    ///
    /// A map rather than a field, because nothing is in it until a screen asks: a tree
    /// with no observers keeps an empty map and pays for nothing.
    static NODES: RefCell<Vec<(u32, WindowSize)>> = const { RefCell::new(Vec::new()) };
    static NODE_SUBSCRIBERS: RefCell<Vec<(u32, Subscriber)>> = const { RefCell::new(Vec::new()) };
    static CURRENT: Cell<WindowSize> = const { Cell::new(WindowSize {
        width_dp: 0.0,
        height_dp: 0.0,
        class: WindowSizeClass::Compact,
        height_class: WindowHeightClass::Compact,
        safe_area: WindowSafeArea { top: 0.0, leading: 0.0, trailing: 0.0 },
    }) };
    static SUBSCRIBERS: RefCell<Vec<Subscriber>> = const { RefCell::new(Vec::new()) };
    /// What each window of a multi-window application last measured, by the id of its
    /// `Window` node. Empty in a single-window application, which keeps its one
    /// value in `CURRENT`.
    static WINDOWS: RefCell<Vec<(u32, WindowSize)>> = const { RefCell::new(Vec::new()) };
    static WINDOW_SUBSCRIBERS: RefCell<Vec<(u32, Subscriber)>> = const { RefCell::new(Vec::new()) };
    static NEXT_SUBSCRIBER_ID: Cell<u64> = const { Cell::new(1) };
}

/// The size the Renderer last reported. Available outside a component too.
///
/// In a multi-window application it is the size of the window the caller is in:
/// the window a composable is composed in, or the window whose node a handler was called
/// for. Outside any window it is the single window's, which a multi-window application
/// never has, so it reads as the default.
pub fn window_size() -> WindowSize {
    match crate::windows::current_window_id() {
        0 => CURRENT.with(Cell::get),
        window => window_size_of(window),
    }
}

/// The size a window last measured, by the id of its `Window` node, or the default for one
/// nothing has reported yet.
pub fn window_size_of(window: u32) -> WindowSize {
    WINDOWS.with_borrow(|windows| {
        windows
            .iter()
            .find(|(id, _)| *id == window)
            .map(|(_, size)| *size)
            .unwrap_or_default()
    })
}

/// Records one window's measurement and wakes the components in that window that read it.
/// Returns whether anything was woken. A report for another window wakes nobody here.
pub(crate) fn publish_window(window: u32, size: WindowSize) -> bool {
    let changed =
        WINDOWS.with_borrow_mut(
            |windows| match windows.iter_mut().find(|(id, _)| *id == window) {
                Some(entry) => {
                    if entry.1 == size {
                        return false;
                    }
                    entry.1 = size;
                    true
                }
                None => {
                    windows.push((window, size));
                    true
                }
            },
        );
    if !changed {
        return false;
    }
    WINDOW_SUBSCRIBERS.with_borrow(|subscribers| {
        let mut woke = false;
        for (id, subscriber) in subscribers {
            if *id == window {
                (subscriber.notify)();
                woke = true;
            }
        }
        woke
    })
}

/// How many windows' sizes and subscriptions are held.
pub(crate) fn window_state_len() -> usize {
    WINDOWS.with_borrow(Vec::len) + WINDOW_SUBSCRIBERS.with_borrow(Vec::len)
}

/// Forgets a window that left the tree, and what it measured.
pub(crate) fn forget_window(window: u32) {
    WINDOWS.with_borrow_mut(|windows| windows.retain(|(id, _)| *id != window));
}

/// A registration for one window's size class. Dropping it ends the registration.
pub struct WindowSubscription {
    id: u64,
}

/// Registers `notify` to be called each time the window `window` measures a different
/// size class.
pub fn subscribe_window(window: u32, notify: Arc<dyn Fn() + Send + Sync>) -> WindowSubscription {
    let id = next_subscriber_id();
    WINDOW_SUBSCRIBERS.with_borrow_mut(|subscribers| {
        subscribers.push((window, Subscriber { id, notify }));
    });
    WindowSubscription { id }
}

impl Drop for WindowSubscription {
    fn drop(&mut self) {
        WINDOW_SUBSCRIBERS.with_borrow_mut(|subscribers| {
            subscribers.retain(|(_, subscriber)| subscriber.id != self.id);
        });
    }
}

/// Records a new measurement and wakes the components that asked about it.
///
/// Returns whether anything changed. Nothing is allocated here: the subscriber list is
/// walked in place, and waking a component only marks its scope dirty.
pub(crate) fn publish(size: WindowSize) -> bool {
    if CURRENT.with(Cell::get) == size {
        return false;
    }
    CURRENT.with(|current| current.set(size));
    SUBSCRIBERS.with_borrow(|subscribers| {
        for subscriber in subscribers {
            (subscriber.notify)();
        }
    });
    true
}

/// The size a node last measured, or a zero size for one nothing has reported yet.
pub fn node_size(token: u32) -> WindowSize {
    NODES.with_borrow(|nodes| {
        nodes
            .iter()
            .find(|(name, _)| *name == token)
            .map(|(_, size)| *size)
            .unwrap_or_default()
    })
}

/// Records a node's measurement and wakes whoever asked about that one.
///
/// Returns whether anything was woken, so a report about a node nobody is reading costs
/// a lookup and nothing else.
pub(crate) fn publish_node(token: u32, size: WindowSize) -> bool {
    let changed =
        NODES.with_borrow_mut(
            |nodes| match nodes.iter_mut().find(|(name, _)| *name == token) {
                Some(entry) => {
                    if entry.1 == size {
                        return false;
                    }
                    entry.1 = size;
                    true
                }
                None => {
                    nodes.push((token, size));
                    true
                }
            },
        );
    if !changed {
        return false;
    }
    NODE_SUBSCRIBERS.with_borrow(|subscribers| {
        let mut woke = false;
        for (name, subscriber) in subscribers {
            if *name == token {
                (subscriber.notify)();
                woke = true;
            }
        }
        woke
    })
}

/// Clears the measurement and every subscription. Used between tests.
#[doc(hidden)]
pub fn reset_window_size() {
    CURRENT.with(|current| current.set(WindowSize::default()));
    SUBSCRIBERS.with_borrow_mut(Vec::clear);
    NODES.with_borrow_mut(Vec::clear);
    NODE_SUBSCRIBERS.with_borrow_mut(Vec::clear);
    WINDOWS.with_borrow_mut(Vec::clear);
    WINDOW_SUBSCRIBERS.with_borrow_mut(Vec::clear);
}

/// A registration for changes of the window's size class. Dropping it ends the
/// registration, so a runtime keeps it for as long as the reader it wakes is alive.
pub struct WindowSizeSubscription {
    id: u64,
}

/// Registers `notify` to be called each time the window's measured size changes. What
/// `notify` does is the runtime's business: mark a scope dirty, most often.
pub fn subscribe(notify: Arc<dyn Fn() + Send + Sync>) -> WindowSizeSubscription {
    let id = next_subscriber_id();
    SUBSCRIBERS.with_borrow_mut(|subscribers| subscribers.push(Subscriber { id, notify }));
    WindowSizeSubscription { id }
}

fn next_subscriber_id() -> u64 {
    NEXT_SUBSCRIBER_ID.with(|next| {
        let id = next.get();
        next.set(id + 1);
        id
    })
}

impl Drop for WindowSizeSubscription {
    fn drop(&mut self) {
        SUBSCRIBERS.with_borrow_mut(|subscribers| {
            subscribers.retain(|subscriber| subscriber.id != self.id);
        });
    }
}

/// A node whose measured size a reader follows.
///
/// The token is the name the screen gives the node, because a node id belongs to the
/// Renderer and never crosses back as something the Host chose. Attach it with
/// `observe_size` and read the size here. The Dioxus adapter hands one out from its
/// `use_node_size` hook.
///
/// ```ignore
/// let panel = use_node_size();
/// rsx! {
///     Card {
///         observe_size: panel.token(),
///         if panel.is_expanded() { Row { Left {} Right {} } } else { Left {} }
///     }
/// }
/// ```
///
/// A component that never calls this costs nothing: the modifier is the only thing that
/// makes the Renderer measure, and the modifier comes from here.
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct NodeSize {
    token: u32,
    size: WindowSize,
}

impl NodeSize {
    /// The node `token` names, with whatever it last measured.
    pub fn of(token: u32) -> Self {
        Self {
            token,
            size: node_size(token),
        }
    }

    /// The value to hand to `observe_size`.
    pub const fn token(&self) -> i64 {
        self.token as i64
    }

    /// Phone-shaped: narrower than 600dp.
    pub fn is_compact(&self) -> bool {
        self.size.is_compact()
    }

    /// Tablet-shaped.
    pub fn is_medium(&self) -> bool {
        self.size.is_medium()
    }

    /// Desktop-shaped.
    pub fn is_expanded(&self) -> bool {
        self.size.is_expanded()
    }

    /// The measurement itself, zero until the Renderer has reported one.
    pub const fn measured(&self) -> WindowSize {
        self.size
    }
}

thread_local! {
    static NEXT_TOKEN: Cell<u32> = const { Cell::new(1) };
}

/// A fresh name for a node a screen wants measured. Never zero, which is the window's.
pub fn next_node_token() -> u32 {
    NEXT_TOKEN.with(|next| {
        let token = next.get();
        next.set(token + 1);
        token
    })
}

/// A registration for one node's measured size, made with [`subscribe_node`].
///
/// Dropping it ends the registration and forgets what that node measured: the node going
/// out of the tree takes its measurement with it.
pub struct NodeSizeSubscription {
    token: u32,
    id: u64,
}

impl NodeSizeSubscription {
    /// The token this registration follows, the value `observe_size` takes.
    pub fn token(&self) -> u32 {
        self.token
    }
}

/// Registers `notify` to be called each time the node named `token` reports a size in a
/// different class.
pub fn subscribe_node(token: u32, notify: Arc<dyn Fn() + Send + Sync>) -> NodeSizeSubscription {
    let id = next_subscriber_id();
    NODE_SUBSCRIBERS.with_borrow_mut(|subscribers| {
        subscribers.push((token, Subscriber { id, notify }));
    });
    NodeSizeSubscription { token, id }
}

impl Drop for NodeSizeSubscription {
    fn drop(&mut self) {
        // The node going out of the tree takes the subscription with it, which is the
        // third thing this requirement asks for.
        NODE_SUBSCRIBERS.with_borrow_mut(|subscribers| {
            subscribers.retain(|(_, subscriber)| subscriber.id != self.id);
        });
        NODES.with_borrow_mut(|nodes| nodes.retain(|(token, _)| *token != self.token));
    }
}

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

    #[test]
    fn fr19_9_safe_area_only_change_republishes() {
        use std::sync::atomic::{AtomicUsize, Ordering};
        reset_window_size();
        let calls = Arc::new(AtomicUsize::new(0));
        let counter = Arc::clone(&calls);
        let _subscription = subscribe(Arc::new(move || {
            counter.fetch_add(1, Ordering::SeqCst);
        }));
        let size = WindowSize::default().with_safe_area(WindowSafeArea {
            top: 28.0,
            leading: 70.0,
            trailing: 0.0,
        });
        assert!(publish(size));
        assert_eq!(window_size(), size);
        assert_eq!(calls.load(Ordering::SeqCst), 1);
        assert!(!publish(size));
        assert_eq!(calls.load(Ordering::SeqCst), 1);
    }

    #[test]
    fn fr20_window_size_starts_compact_before_the_renderer_measures_anything() {
        reset_window_size();
        assert_eq!(window_size(), WindowSize::default());
        assert!(window_size().is_compact());
    }

    #[test]
    fn fr20_publishing_the_same_size_twice_wakes_nobody() {
        reset_window_size();
        let size = WindowSize::new(
            700.0,
            800.0,
            WindowSizeClass::Medium,
            WindowHeightClass::Medium,
        );
        assert!(publish(size));
        assert!(!publish(size));
        reset_window_size();
    }
}