Skip to main content

compose_rust/
density.rs

1//! How many device pixels one dp of a window covers, as the Renderer reports it.
2//!
3//! The Host lays out in dp and never needs the number to place a box. It needs it for the
4//! things that are about pixels: a page's `devicePixelRatio` and its resolution media
5//! queries, which image of a set to load, and snapping a hairline to the pixel grid. The
6//! Renderer says what it is once before the first frame and again whenever it changes, as
7//! when a window moves to a screen of another scale. Until it has, the value is 1.0.
8//!
9//! It is separate from the zoom. A move between screens changes the density and leaves
10//! the zoom alone, and a zoom step does the reverse, so each has its own report.
11//!
12//! Anything derived from the density (a cache of measurements, a chosen image) is stale
13//! once it changes. [`subscribe`] is how its owner hears: the callback runs when a
14//! different value arrives and never for a repeat of the same one.
15
16use std::cell::{Cell, RefCell};
17use std::sync::Arc;
18
19/// The density before the Renderer has reported one: one device pixel to the dp.
20pub const DEFAULT_DENSITY: f32 = 1.0;
21
22struct Subscriber {
23    id: u64,
24    notify: Arc<dyn Fn() + Send + Sync>,
25}
26
27thread_local! {
28    static CURRENT: Cell<f32> = const { Cell::new(DEFAULT_DENSITY) };
29    static SUBSCRIBERS: RefCell<Vec<Subscriber>> = const { RefCell::new(Vec::new()) };
30    /// The density of each window of a multi-window application, by the id of its
31    /// `Window` node. Two windows can sit on screens of different scales.
32    static WINDOW_DENSITIES: RefCell<Vec<(u32, f32)>> = const { RefCell::new(Vec::new()) };
33    static WINDOW_SUBSCRIBERS: RefCell<Vec<(u32, Subscriber)>> = const { RefCell::new(Vec::new()) };
34    static NEXT_SUBSCRIBER_ID: Cell<u64> = const { Cell::new(1) };
35}
36
37/// What the Renderer last reported, or 1.0 before it has. Available outside a component
38/// too.
39///
40/// In a multi-window application it is the density of the window the caller is in.
41pub fn density() -> f32 {
42    match crate::windows::current_window_id() {
43        0 => CURRENT.with(Cell::get),
44        window => density_of(window),
45    }
46}
47
48/// The density of one window, by the id of its `Window` node, or 1.0 for one that has
49/// not reported yet.
50pub fn density_of(window: u32) -> f32 {
51    WINDOW_DENSITIES.with_borrow(|densities| {
52        densities
53            .iter()
54            .find(|(id, _)| *id == window)
55            .map_or(DEFAULT_DENSITY, |(_, scale)| *scale)
56    })
57}
58
59/// Records the Renderer's report and wakes whoever reads it.
60///
61/// Returns whether anyone was woken. A report nobody reads is still recorded, so a reader
62/// that arrives later sees it, but nothing is redrawn for it.
63pub(crate) fn publish(scale: f32) -> bool {
64    if CURRENT.with(Cell::get) == scale {
65        return false;
66    }
67    CURRENT.with(|current| current.set(scale));
68    SUBSCRIBERS.with_borrow(|subscribers| {
69        for subscriber in subscribers {
70            (subscriber.notify)();
71        }
72        !subscribers.is_empty()
73    })
74}
75
76/// Records one window's report and wakes whoever reads it for that window. Returns
77/// whether anyone was woken.
78///
79/// A window's first report of 1.0 changes nothing a reader could have seen, because 1.0
80/// is what it read before, so it wakes nobody either.
81pub(crate) fn publish_window(window: u32, scale: f32) -> bool {
82    let changed = WINDOW_DENSITIES.with_borrow_mut(|densities| {
83        match densities.iter_mut().find(|(id, _)| *id == window) {
84            Some(entry) => {
85                if entry.1 == scale {
86                    return false;
87                }
88                entry.1 = scale;
89                true
90            }
91            None => {
92                densities.push((window, scale));
93                scale != DEFAULT_DENSITY
94            }
95        }
96    });
97    if !changed {
98        return false;
99    }
100    WINDOW_SUBSCRIBERS.with_borrow(|subscribers| {
101        let mut woke = false;
102        for (id, subscriber) in subscribers {
103            if *id == window {
104                (subscriber.notify)();
105                woke = true;
106            }
107        }
108        woke
109    })
110}
111
112/// How many windows' densities and subscriptions are held.
113pub(crate) fn window_state_len() -> usize {
114    WINDOW_DENSITIES.with_borrow(Vec::len) + WINDOW_SUBSCRIBERS.with_borrow(Vec::len)
115}
116
117/// Forgets a window that left the tree, and what it reported.
118pub(crate) fn forget_window(window: u32) {
119    WINDOW_DENSITIES.with_borrow_mut(|densities| densities.retain(|(id, _)| *id != window));
120}
121
122/// Clears the report and every subscription. Used when a Host is made and between tests.
123#[doc(hidden)]
124pub fn reset_density() {
125    CURRENT.with(|current| current.set(DEFAULT_DENSITY));
126    SUBSCRIBERS.with_borrow_mut(Vec::clear);
127    WINDOW_DENSITIES.with_borrow_mut(Vec::clear);
128    WINDOW_SUBSCRIBERS.with_borrow_mut(Vec::clear);
129}
130
131fn next_subscriber_id() -> u64 {
132    NEXT_SUBSCRIBER_ID.with(|next| {
133        let id = next.get();
134        next.set(id + 1);
135        id
136    })
137}
138
139/// A registration for changes to the density. Dropping it ends the registration.
140pub struct DensitySubscription {
141    id: u64,
142}
143
144/// Registers `notify` to be called each time the Renderer reports a different density.
145pub fn subscribe(notify: Arc<dyn Fn() + Send + Sync>) -> DensitySubscription {
146    let id = next_subscriber_id();
147    SUBSCRIBERS.with_borrow_mut(|subscribers| subscribers.push(Subscriber { id, notify }));
148    DensitySubscription { id }
149}
150
151impl Drop for DensitySubscription {
152    fn drop(&mut self) {
153        SUBSCRIBERS.with_borrow_mut(|subscribers| {
154            subscribers.retain(|subscriber| subscriber.id != self.id);
155        });
156    }
157}
158
159/// A registration for one window's density. Dropping it ends the registration.
160pub struct WindowDensitySubscription {
161    id: u64,
162}
163
164/// Registers `notify` to be called each time the window `window` reports a different
165/// density.
166pub fn subscribe_window(
167    window: u32,
168    notify: Arc<dyn Fn() + Send + Sync>,
169) -> WindowDensitySubscription {
170    let id = next_subscriber_id();
171    WINDOW_SUBSCRIBERS.with_borrow_mut(|subscribers| {
172        subscribers.push((window, Subscriber { id, notify }));
173    });
174    WindowDensitySubscription { id }
175}
176
177impl Drop for WindowDensitySubscription {
178    fn drop(&mut self) {
179        WINDOW_SUBSCRIBERS.with_borrow_mut(|subscribers| {
180            subscribers.retain(|(_, subscriber)| subscriber.id != self.id);
181        });
182    }
183}
184
185#[cfg(test)]
186mod tests {
187    use super::*;
188    use std::sync::atomic::{AtomicUsize, Ordering};
189
190    #[test]
191    fn fr43_density_defaults_to_one_before_the_first_event() {
192        reset_density();
193        assert_eq!(density(), 1.0);
194        assert_eq!(density_of(7), 1.0);
195    }
196
197    #[test]
198    fn fr43_a_density_report_wakes_only_on_change() {
199        reset_density();
200        let woken = Arc::new(AtomicUsize::new(0));
201        let counter = woken.clone();
202        let _subscription = subscribe(Arc::new(move || {
203            counter.fetch_add(1, Ordering::SeqCst);
204        }));
205        assert!(!publish(1.0), "1.0 is what was read before any report");
206        assert!(publish(2.0));
207        assert!(!publish(2.0), "the same report twice is one change");
208        assert_eq!(woken.load(Ordering::SeqCst), 1);
209        assert_eq!(density(), 2.0);
210        reset_density();
211    }
212
213    #[test]
214    fn fr43_a_window_density_wakes_only_that_window() {
215        reset_density();
216        let woken = Arc::new(AtomicUsize::new(0));
217        let counter = woken.clone();
218        let _subscription = subscribe_window(
219            4,
220            Arc::new(move || {
221                counter.fetch_add(1, Ordering::SeqCst);
222            }),
223        );
224        assert!(!publish_window(5, 2.0), "nobody reads window 5");
225        assert!(!publish_window(4, 1.0), "1.0 is what window 4 read before");
226        assert!(publish_window(4, 1.5));
227        assert!(!publish_window(4, 1.5));
228        assert_eq!(woken.load(Ordering::SeqCst), 1);
229        assert_eq!((density_of(4), density_of(5)), (1.5, 2.0));
230        forget_window(4);
231        assert_eq!(density_of(4), 1.0);
232        reset_density();
233    }
234}