Skip to main content

sui_runtime/
motion.rs

1//! Runtime-driven motion: the motion policy shared by every widget on a UI
2//! thread, [`Motion`] values the runtime animates for widgets, and how a
3//! window's animation frames are timed.
4//!
5//! The platform reports the operating system's motion preference, an app can
6//! override it (for example from a settings page), and a time scale slows
7//! every transition down for debugging. Widgets read the combined
8//! [`MotionPolicy`] when they start a transition, so changes apply to the
9//! next animation rather than cutting running ones short.
10
11use std::cell::Cell;
12
13use sui_animation::{AnimationSpec, Interpolate, MotionValue};
14use sui_core::{InvalidationKind, MotionPolicy, MotionPreference};
15
16#[derive(Debug, Clone, Copy, PartialEq)]
17struct MotionSettings {
18    system: MotionPreference,
19    app: Option<MotionPreference>,
20    time_scale: f32,
21}
22
23impl MotionSettings {
24    const DEFAULT: Self = Self {
25        system: MotionPreference::Full,
26        app: None,
27        time_scale: 1.0,
28    };
29}
30
31thread_local! {
32    static MOTION_SETTINGS: Cell<MotionSettings> = const { Cell::new(MotionSettings::DEFAULT) };
33}
34
35fn update(change: impl FnOnce(&mut MotionSettings)) {
36    MOTION_SETTINGS.with(|settings| {
37        let mut next = settings.get();
38        change(&mut next);
39        settings.set(next);
40    });
41}
42
43fn settings() -> MotionSettings {
44    MOTION_SETTINGS.with(Cell::get)
45}
46
47/// The motion policy in effect on this UI thread: the app's preference if it
48/// set one, otherwise the system's, with the current time scale.
49pub fn motion_policy() -> MotionPolicy {
50    let settings = settings();
51    MotionPolicy::new(settings.app.unwrap_or(settings.system)).with_time_scale(settings.time_scale)
52}
53
54/// The operating system's motion preference, as reported by the platform.
55pub fn system_motion_preference() -> MotionPreference {
56    settings().system
57}
58
59/// Record the operating system's motion preference. Platform backends call
60/// this at startup and when the setting may have changed.
61pub fn set_system_motion_preference(preference: MotionPreference) {
62    update(|settings| settings.system = preference);
63}
64
65/// The app's motion preference override, if any.
66pub fn app_motion_preference() -> Option<MotionPreference> {
67    settings().app
68}
69
70/// Override the system's motion preference for this app, or pass `None` to
71/// follow the system again.
72pub fn set_app_motion_preference(preference: Option<MotionPreference>) {
73    update(|settings| settings.app = preference);
74}
75
76/// How fast transitions play relative to their nominal durations.
77pub fn motion_time_scale() -> f32 {
78    settings().time_scale
79}
80
81/// Play transitions at `time_scale` speed: `0.25` shows them at quarter
82/// speed. Meant for inspecting motion while developing.
83pub fn set_motion_time_scale(time_scale: f32) {
84    let time_scale = MotionPolicy::FULL.with_time_scale(time_scale).time_scale();
85    update(|settings| settings.time_scale = time_scale);
86}
87
88/// Forget the system preference, app override, and time scale. Test
89/// harnesses call this so each app starts from full motion.
90pub fn reset_motion_settings() {
91    MOTION_SETTINGS.with(|settings| settings.set(MotionSettings::DEFAULT));
92}
93
94/// How a window's animation frames are timed.
95#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
96pub enum FramePacing {
97    /// The runtime times animation frames itself, up to 120 per second. Used
98    /// by headless hosts and by windows that are not presenting.
99    #[default]
100    Timer,
101    /// The platform starts each animation frame when the display is ready
102    /// for one, with [`crate::Runtime::begin_animation_frame`], stamped with
103    /// the time the frame is expected on screen.
104    Display,
105}
106
107/// Something that knows the time of the frame being produced: widget
108/// contexts, or a plain time in seconds.
109pub trait FrameClock {
110    fn frame_time(&self) -> f64;
111}
112
113impl FrameClock for f64 {
114    fn frame_time(&self) -> f64 {
115        *self
116    }
117}
118
119/// A context that can start [`Motion`] transitions: event, measure, and
120/// arrange contexts.
121pub trait AnimateCtx: FrameClock {
122    /// See [`crate::EventCtx::animate_after`].
123    fn animate_after<T>(
124        &mut self,
125        motion: &mut Motion<T>,
126        target: T,
127        delay: f64,
128        spec: AnimationSpec,
129    ) -> bool
130    where
131        T: Interpolate + Copy + PartialEq;
132
133    /// See [`crate::EventCtx::animate`].
134    fn animate<T>(&mut self, motion: &mut Motion<T>, target: T, spec: AnimationSpec) -> bool
135    where
136        T: Interpolate + Copy + PartialEq,
137    {
138        self.animate_after(motion, target, 0.0, spec)
139    }
140}
141
142/// A value the runtime animates for a widget.
143///
144/// Start a transition with `ctx.animate(&mut motion, target, spec)` and read
145/// the value while painting with `motion.get(ctx)`. The runtime invalidates the
146/// widget every frame until the transition ends, so the widget needs no
147/// animation-frame handling of its own. The value is a function of time, so
148/// reading it at a frame's time gives what is on screen then.
149///
150/// Transitions follow the [`MotionPolicy`]; retargeting mid-flight keeps
151/// momentum (see [`MotionValue`]).
152#[derive(Debug, Clone, Copy, PartialEq)]
153pub struct Motion<T> {
154    value: MotionValue<T>,
155    invalidation: InvalidationKind,
156    movement: bool,
157}
158
159impl<T: Copy> Motion<T> {
160    pub const fn new(value: T) -> Self {
161        Self {
162            value: MotionValue::new(value),
163            invalidation: InvalidationKind::Paint,
164            movement: false,
165        }
166    }
167
168    /// What the runtime invalidates each frame while this animates: `Paint`
169    /// (the default) for values read while painting, `Transform` or `Effect`
170    /// for layer properties, `Measure` for sizes.
171    pub const fn invalidating(mut self, kind: InvalidationKind) -> Self {
172        self.invalidation = kind;
173        self
174    }
175
176    /// Mark this as movement, such as a sliding indicator: reduced motion
177    /// finishes it immediately instead of animating it.
178    pub const fn movement(mut self) -> Self {
179        self.movement = true;
180        self
181    }
182
183    pub const fn invalidation(&self) -> InvalidationKind {
184        self.invalidation
185    }
186
187    pub const fn is_movement(&self) -> bool {
188        self.movement
189    }
190
191    /// The value this motion is heading to.
192    pub fn target(&self) -> T {
193        self.value.target()
194    }
195
196    /// Stop animating and rest at `value`.
197    pub fn jump_to(&mut self, value: T) {
198        self.value.jump_to(value);
199    }
200}
201
202impl<T> Motion<T>
203where
204    T: Interpolate + Copy + PartialEq,
205{
206    /// The value at the time of the frame `clock` is producing.
207    pub fn get(&self, clock: &impl FrameClock) -> T {
208        self.at(clock.frame_time())
209    }
210
211    /// The value at `time`.
212    pub fn at(&self, time: f64) -> T {
213        self.value.value(time)
214    }
215
216    /// Whether a transition is running at the time of `clock`'s frame.
217    pub fn is_animating(&self, clock: &impl FrameClock) -> bool {
218        self.value.is_animating_at(clock.frame_time())
219    }
220
221    /// When the running transition ends, or `None` at rest.
222    pub fn end_time(&self) -> Option<f64> {
223        self.value.end_time()
224    }
225
226    /// Start toward `target` at `time` with `spec` under the motion policy.
227    /// Returns when the transition ends if one started. Contexts' `animate`
228    /// methods call this and keep the widget invalidated until then.
229    pub fn start(&mut self, target: T, time: f64, spec: AnimationSpec) -> Option<f64> {
230        self.start_after(target, time, 0.0, spec)
231    }
232
233    /// Like [`Motion::start`], `delay` seconds after `time`. The delay
234    /// follows the policy's time scale, and is skipped when the policy makes
235    /// the transition instant.
236    pub fn start_after(
237        &mut self,
238        target: T,
239        time: f64,
240        delay: f64,
241        spec: AnimationSpec,
242    ) -> Option<f64> {
243        let policy = motion_policy();
244        let allowed = if self.movement {
245            policy.allows_movement()
246        } else {
247            policy.allows_motion()
248        };
249        let spec = if self.movement {
250            spec.with_movement_policy(policy)
251        } else {
252            spec.with_policy(policy)
253        };
254        let delay = if allowed {
255            delay / f64::from(policy.time_scale())
256        } else {
257            0.0
258        };
259        // Drop finished transitions so the end time reflects only what runs.
260        self.value.advance(time);
261        if self.value.animate_to_after(target, time, delay, spec) {
262            self.value.end_time()
263        } else {
264            None
265        }
266    }
267}
268
269#[cfg(test)]
270mod tests {
271    use super::*;
272
273    #[test]
274    fn app_preference_overrides_the_system_until_cleared() {
275        reset_motion_settings();
276        set_system_motion_preference(MotionPreference::Reduced);
277        assert_eq!(motion_policy().preference, MotionPreference::Reduced);
278
279        set_app_motion_preference(Some(MotionPreference::Full));
280        assert_eq!(motion_policy().preference, MotionPreference::Full);
281        assert_eq!(system_motion_preference(), MotionPreference::Reduced);
282
283        set_app_motion_preference(None);
284        assert_eq!(motion_policy().preference, MotionPreference::Reduced);
285        reset_motion_settings();
286    }
287
288    #[test]
289    fn motion_reads_its_value_at_the_frame_time() {
290        reset_motion_settings();
291        let mut motion = Motion::new(0.0_f32);
292        let until = motion
293            .start(
294                1.0,
295                10.0,
296                AnimationSpec::tween(0.2, sui_animation::Easing::Linear),
297            )
298            .expect("a transition starts");
299
300        assert!((until - 10.2).abs() < 1e-9);
301        assert!((motion.get(&10.1) - 0.5).abs() < 1e-5);
302        assert!(motion.is_animating(&10.1));
303        assert_eq!(motion.get(&10.3), 1.0);
304        assert!(!motion.is_animating(&10.3));
305        assert_eq!(motion.target(), 1.0);
306    }
307
308    #[test]
309    fn motion_follows_the_policy_for_movement() {
310        reset_motion_settings();
311        set_app_motion_preference(Some(MotionPreference::Reduced));
312        let spec = AnimationSpec::tween(0.2, sui_animation::Easing::Linear);
313
314        let mut fade = Motion::new(0.0_f32);
315        assert!(fade.start(1.0, 0.0, spec).is_some());
316        let mut slide = Motion::new(0.0_f32).movement();
317        assert!(slide.start(1.0, 0.0, spec).is_none());
318        assert_eq!(slide.get(&0.0), 1.0);
319        reset_motion_settings();
320    }
321
322    #[test]
323    fn delays_follow_the_time_scale_and_vanish_without_motion() {
324        reset_motion_settings();
325        let spec = AnimationSpec::tween(0.2, sui_animation::Easing::Linear);
326        set_motion_time_scale(0.5);
327        let mut slow = Motion::new(0.0_f32);
328        let until = slow
329            .start_after(1.0, 0.0, 0.1, spec)
330            .expect("a transition starts");
331        assert!(
332            (until - 0.6).abs() < 1e-9,
333            "delay and duration both double: {until}"
334        );
335        assert_eq!(slow.get(&0.15), 0.0);
336
337        reset_motion_settings();
338        set_app_motion_preference(Some(MotionPreference::Off));
339        let mut off = Motion::new(0.0_f32);
340        assert!(off.start_after(1.0, 0.0, 0.1, spec).is_none());
341        assert_eq!(off.get(&0.0), 1.0);
342        reset_motion_settings();
343    }
344
345    #[test]
346    fn time_scale_is_kept_positive() {
347        reset_motion_settings();
348        set_motion_time_scale(0.25);
349        assert_eq!(motion_policy().time_scale, 0.25);
350
351        set_motion_time_scale(-1.0);
352        assert_eq!(motion_time_scale(), MotionPolicy::MIN_TIME_SCALE);
353        reset_motion_settings();
354        assert_eq!(motion_policy(), MotionPolicy::FULL);
355    }
356}