Skip to main content

egui_pop_core/
motion.rs

1//! The motion clock: where spinners, travelling bars, shimmer and the
2//! busy delay take their time from, instead of `input.time` directly.
3//!
4//! - [`now`]: the clock's time, in seconds: the interface's time, or a
5//!   clock the application or a test gives ([`set_clock`], [`freeze`]).
6//!   A given clock moves only when told: a test freezes motion, steps
7//!   it, and gets the same frames on every run;
8//! - [`phase`]: where a looping animation is (0 to 1), static under
9//!   reduced motion (`motion.duration` is 0) so spinners and bars give
10//!   still frames;
11//! - [`animate`]: asks for the next frame of an animation shown: never
12//!   at once (a frame later, at most 60 a second; four a second while
13//!   the window is not focused), never under reduced motion or a given
14//!   clock; [`wake_at`] asks for the frame where something changes;
15//! - [`Busy`]: the delayed busy indicator: nothing before
16//!   `motion.spinner.delay` (300 ms), then shown at least
17//!   `motion.spinner.min` (500 ms), counted from when the work started
18//!   (a job's or a command's start, not when the widget was first
19//!   drawn).
20//!
21//! ```
22//! use egui_pop_core::motion::{self, Busy};
23//! use egui_pop_model::clock::ManualClock;
24//!
25//! let ctx = egui::Context::default();
26//! let clock = ManualClock::new(0.0);
27//! motion::set_clock(&ctx, Some(clock.shared()));
28//! let id = egui::Id::new("export");
29//! clock.set(0.29);
30//! assert!(!Busy::new(id, 0.0).visible(&ctx, true), "not before 300 ms");
31//! clock.set(0.31);
32//! assert!(Busy::new(id, 0.0).visible(&ctx, true));
33//! // The work ends at once: the indicator stays 500 ms.
34//! clock.set(0.4);
35//! assert!(Busy::new(id, 0.0).visible(&ctx, false));
36//! clock.set(0.82);
37//! assert!(!Busy::new(id, 0.0).visible(&ctx, false));
38//! ```
39
40use 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
49/// Frames of an animation, at most this often (seconds).
50pub const FRAME: f64 = 1.0 / 60.0;
51/// Frames while the window is not focused.
52pub const BACKGROUND_FRAME: f64 = 0.25;
53
54#[derive(Default)]
55struct State {
56    clock: Option<SharedClock>,
57    /// When each busy indicator was first shown, and when its work
58    /// ended.
59    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
75/// Gives the motion clock a clock of its own (the application's, a
76/// test's), or gives it back the interface's time (`None`).
77pub fn set_clock(ctx: &Context, clock: Option<SharedClock>) {
78    lock(&state(ctx)).clock = clock;
79    ctx.request_repaint();
80}
81
82/// Stops the motion clock at `at` seconds; returns the clock, to step
83/// it by hand.
84pub fn freeze(ctx: &Context, at: f64) -> ManualClock {
85    let clock = ManualClock::new(at);
86    set_clock(ctx, Some(clock.shared()));
87    clock
88}
89
90/// Whether a clock was given (motion moves only when told).
91pub fn controlled(ctx: &Context) -> bool {
92    lock(&state(ctx)).clock.is_some()
93}
94
95/// Now, by the motion clock, in seconds.
96pub 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
104/// Whether motion is reduced (`motion.duration` is 0): animations give
105/// still frames.
106pub fn reduced(ctx: &Context) -> bool {
107    Tokens::of(ctx).motion_duration <= 0.0
108}
109
110/// Where a looping animation of `period` seconds is, from 0 to 1;
111/// `still` under reduced motion.
112pub 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
119/// Asks for the next frame of an animation on screen: a frame later
120/// (never at once, so a headless harness settles), four a second while
121/// the window is not focused; nothing under reduced motion or a given
122/// clock.
123pub 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
132/// Asks for a frame when the motion clock reaches `at` (seconds): the
133/// moment a delayed indicator shows, or work ends. Nothing under a given
134/// clock: it moves only when told, and whoever moves it asks for the
135/// frame.
136pub 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
146/// A repaint `seconds` after this frame. egui counts a delay from the
147/// next frame (it takes the predicted frame time off); it is put back
148/// so the delay never becomes an immediate repaint.
149fn 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/// A delayed busy indicator for work that started at `since` (motion
155/// clock seconds): shown after the delay, kept for the minimum once
156/// shown. Its state is kept per id.
157#[derive(Clone, Copy, Debug, PartialEq)]
158pub struct Busy {
159    pub id: Id,
160    pub since: f64,
161    /// Seconds before showing (`motion.spinner.delay` by default).
162    pub delay: Option<f64>,
163    /// Seconds shown at least (`motion.spinner.min` by default).
164    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    /// Whether the indicator shows now, the work going on (`busy`) or
188    /// not; asks for the frame where that changes.
189    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        // The state's lock is let go before asking for a frame.
196        if let Some(at) = wake {
197            wake_at(ctx, at);
198        }
199        visible
200    }
201
202    /// Whether it shows, and when that changes next.
203    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        // Done in 200 ms: nothing ever shown.
250        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        // A long one shows after the delay, until it ends.
254        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}