1use std::collections::HashMap;
41use std::time::Duration;
42
43use egui::{Context, Id};
44use egui_pop_model::clock::{ManualClock, SharedClock};
45
46use crate::state::{lock, shared};
47use crate::theme::Tokens;
48
49pub const FRAME: f64 = 1.0 / 60.0;
51pub const BACKGROUND_FRAME: f64 = 0.25;
53
54#[derive(Default)]
55struct State {
56 clock: Option<SharedClock>,
57 busy: HashMap<Id, (Option<f64>, Option<f64>)>,
60}
61
62impl std::fmt::Debug for State {
63 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
64 f.debug_struct("State")
65 .field("clock", &self.clock.is_some())
66 .field("busy", &self.busy.len())
67 .finish()
68 }
69}
70
71fn state(ctx: &Context) -> std::sync::Arc<std::sync::Mutex<State>> {
72 shared::<State>(ctx, "core.motion")
73}
74
75pub fn set_clock(ctx: &Context, clock: Option<SharedClock>) {
78 lock(&state(ctx)).clock = clock;
79 ctx.request_repaint();
80}
81
82pub fn freeze(ctx: &Context, at: f64) -> ManualClock {
85 let clock = ManualClock::new(at);
86 set_clock(ctx, Some(clock.shared()));
87 clock
88}
89
90pub fn controlled(ctx: &Context) -> bool {
92 lock(&state(ctx)).clock.is_some()
93}
94
95pub fn now(ctx: &Context) -> f64 {
97 let clock = lock(&state(ctx)).clock.clone();
98 match clock {
99 Some(c) => c.now(),
100 None => ctx.input(|i| i.time),
101 }
102}
103
104pub fn reduced(ctx: &Context) -> bool {
107 Tokens::of(ctx).motion_duration <= 0.0
108}
109
110pub fn phase(ctx: &Context, period: f64, still: f32) -> f32 {
113 if reduced(ctx) || period <= 0.0 {
114 return still;
115 }
116 (now(ctx) / period).rem_euclid(1.0) as f32
117}
118
119pub fn animate(ctx: &Context) {
124 if reduced(ctx) || controlled(ctx) {
125 return;
126 }
127 let focused = ctx.input(|i| i.focused);
128 let after = if focused { FRAME } else { BACKGROUND_FRAME };
129 after_frame(ctx, after);
130}
131
132pub fn wake_at(ctx: &Context, at: f64) {
137 if controlled(ctx) {
138 return;
139 }
140 let wait = at - now(ctx);
141 if wait > 0.0 {
142 after_frame(ctx, wait);
143 }
144}
145
146fn after_frame(ctx: &Context, seconds: f64) {
150 let frame = f64::from(ctx.input(|i| i.predicted_dt));
151 ctx.request_repaint_after(Duration::from_secs_f64(seconds.max(0.0) + frame));
152}
153
154#[derive(Clone, Copy, Debug, PartialEq)]
158pub struct Busy {
159 pub id: Id,
160 pub since: f64,
161 pub delay: Option<f64>,
163 pub min: Option<f64>,
165}
166
167impl Busy {
168 pub fn new(id: Id, since: f64) -> Self {
169 Self {
170 id,
171 since,
172 delay: None,
173 min: None,
174 }
175 }
176
177 pub fn delay(mut self, seconds: f64) -> Self {
178 self.delay = Some(seconds);
179 self
180 }
181
182 pub fn min(mut self, seconds: f64) -> Self {
183 self.min = Some(seconds);
184 self
185 }
186
187 pub fn visible(&self, ctx: &Context, busy: bool) -> bool {
190 let t = Tokens::of(ctx);
191 let delay = self.delay.unwrap_or(f64::from(t.motion.spinner_delay));
192 let min = self.min.unwrap_or(f64::from(t.motion.spinner_min));
193 let now = now(ctx);
194 let (visible, wake) = self.decide(ctx, busy, now, delay, min);
195 if let Some(at) = wake {
197 wake_at(ctx, at);
198 }
199 visible
200 }
201
202 fn decide(
204 &self,
205 ctx: &Context,
206 busy: bool,
207 now: f64,
208 delay: f64,
209 min: f64,
210 ) -> (bool, Option<f64>) {
211 let st = state(ctx);
212 let mut s = lock(&st);
213 let entry = s.busy.entry(self.id).or_insert((None, None));
214 if busy {
215 entry.1 = None;
216 if entry.0.is_none() {
217 let at = self.since + delay;
218 if now < at {
219 return (false, Some(at));
220 }
221 entry.0 = Some(now);
222 }
223 return (true, None);
224 }
225 let Some(from) = entry.0 else {
226 s.busy.remove(&self.id);
227 return (false, None);
228 };
229 let until = from + min;
230 if now < until {
231 entry.1 = Some(entry.1.unwrap_or(now));
232 (true, Some(until))
233 } else {
234 s.busy.remove(&self.id);
235 (false, None)
236 }
237 }
238}
239
240#[cfg(test)]
241mod tests {
242 use super::*;
243
244 #[test]
245 fn a_short_job_never_shows_and_a_long_one_stays_its_minimum() {
246 let ctx = Context::default();
247 let clock = freeze(&ctx, 10.0);
248 let id = Id::unique("a");
249 clock.set(10.2);
251 assert!(!Busy::new(id, 10.0).visible(&ctx, true));
252 assert!(!Busy::new(id, 10.0).visible(&ctx, false));
253 let id = Id::unique("b");
255 clock.set(11.0);
256 assert!(Busy::new(id, 10.0).visible(&ctx, true));
257 clock.set(12.0);
258 assert!(Busy::new(id, 10.0).visible(&ctx, true));
259 assert!(!Busy::new(id, 10.0).visible(&ctx, false), "shown 1 s");
260 }
261
262 #[test]
263 fn a_frozen_clock_gives_the_same_phase_and_reduced_motion_a_still_one() {
264 let ctx = Context::default();
265 let clock = freeze(&ctx, 0.25);
266 assert_eq!(phase(&ctx, 1.0, 0.0), 0.25);
267 clock.advance(0.5);
268 assert_eq!(phase(&ctx, 1.0, 0.0), 0.75);
269 assert!(controlled(&ctx));
270 crate::theme::install(
271 &ctx,
272 &crate::theme::ThemeSpec::new("pop-dark").reduced_motion(true),
273 );
274 assert!(reduced(&ctx));
275 assert_eq!(phase(&ctx, 1.0, 0.4), 0.4);
276 set_clock(&ctx, None);
277 assert!(!controlled(&ctx));
278 }
279}