1use std::cell::{Cell, RefCell};
17use std::sync::Arc;
18
19pub 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 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
37pub fn density() -> f32 {
42 match crate::windows::current_window_id() {
43 0 => CURRENT.with(Cell::get),
44 window => density_of(window),
45 }
46}
47
48pub 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
59pub(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
76pub(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
112pub(crate) fn window_state_len() -> usize {
114 WINDOW_DENSITIES.with_borrow(Vec::len) + WINDOW_SUBSCRIBERS.with_borrow(Vec::len)
115}
116
117pub(crate) fn forget_window(window: u32) {
119 WINDOW_DENSITIES.with_borrow_mut(|densities| densities.retain(|(id, _)| *id != window));
120}
121
122#[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
139pub struct DensitySubscription {
141 id: u64,
142}
143
144pub 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
159pub struct WindowDensitySubscription {
161 id: u64,
162}
163
164pub 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}