Skip to main content

native_gui_core/
motion.rs

1use std::time::Duration;
2
3use crate::timer::TimerId;
4use crate::{GuiError, GuiResult, WidgetId};
5
6/// Bounded cadence for coalesced motion progress updates.
7pub const MOTION_TICK_CADENCE: Duration = Duration::from_millis(16);
8
9/// Stable identifier for one motion allocated by a `Ui`.
10#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord)]
11pub struct MotionId(pub u64);
12
13/// Linear progress timing for a motion.
14#[derive(Debug, Clone, Copy, PartialEq, Eq)]
15pub struct MotionSpec {
16    /// Positive duration from start to completion. Zero is rejected by
17    /// [`MotionSpec::validate`]; addition to the backend clock must also fit
18    /// in `Duration`, or starting the motion returns a deadline error.
19    pub duration: Duration,
20}
21
22impl MotionSpec {
23    /// Rejects zero-length motions.
24    pub fn validate(self) -> GuiResult<()> {
25        if self.duration.is_zero() {
26            return Err(GuiError::Backend(
27                "Motion duration must be non-zero".to_owned(),
28            ));
29        }
30        Ok(())
31    }
32}
33
34/// Motion support implemented by a backend.
35#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
36pub struct MotionCapabilities {
37    /// Motions can be driven by this backend's timer/event loop.
38    pub motions: bool,
39}
40
41impl MotionCapabilities {
42    /// Returns a capability set with all motion operations disabled.
43    pub const fn none() -> Self {
44        Self { motions: false }
45    }
46}
47
48#[derive(Debug, Clone, Copy)]
49pub(crate) struct ActiveMotion {
50    pub(crate) timer: TimerId,
51    pub(crate) widget_id: WidgetId,
52    pub(crate) spec: MotionSpec,
53}
54
55#[cfg(test)]
56mod tests {
57    use std::time::Duration;
58
59    use crate::test_support::MockBackend;
60    use crate::{
61        GuiError, MotionCapabilities, MotionId, MotionSpec, TimerSpec, Ui, UiEvent, WidgetKind,
62        MOTION_TICK_CADENCE,
63    };
64
65    fn motion(duration_ms: u64) -> MotionSpec {
66        MotionSpec {
67            duration: Duration::from_millis(duration_ms),
68        }
69    }
70
71    #[test]
72    fn motion_progress_and_finish_follow_virtual_timer_deadlines() {
73        let mut ui = Ui::new(MockBackend::default());
74        let widget = ui.create(WidgetKind::Button, Some("move")).unwrap();
75        let motion = ui.start_motion(widget, motion(32)).unwrap();
76
77        ui.backend_mut()
78            .advance_time(MOTION_TICK_CADENCE - Duration::from_millis(1))
79            .unwrap();
80        assert_eq!(ui.poll_event().unwrap(), None);
81
82        ui.backend_mut()
83            .advance_time(Duration::from_millis(1))
84            .unwrap();
85        assert_eq!(
86            ui.poll_event().unwrap(),
87            Some(UiEvent::MotionTicked {
88                motion,
89                widget_id: widget,
90                progress: 0.5,
91            })
92        );
93
94        ui.backend_mut().advance_time(MOTION_TICK_CADENCE).unwrap();
95        assert_eq!(
96            ui.poll_event().unwrap(),
97            Some(UiEvent::MotionTicked {
98                motion,
99                widget_id: widget,
100                progress: 1.0,
101            })
102        );
103        assert_eq!(
104            ui.poll_event().unwrap(),
105            Some(UiEvent::MotionFinished {
106                motion,
107                widget_id: widget,
108            })
109        );
110        assert_eq!(ui.poll_event().unwrap(), None);
111        assert_eq!(
112            ui.cancel_motion(motion),
113            Err(GuiError::Backend("Motion not found: 1".to_owned()))
114        );
115    }
116
117    #[test]
118    fn motion_coalesces_elapsed_deadlines_and_finishes_once() {
119        let mut ui = Ui::new(MockBackend::default());
120        let widget = ui.create(WidgetKind::Button, Some("coalesced")).unwrap();
121        let motion = ui.start_motion(widget, motion(32)).unwrap();
122
123        ui.backend_mut()
124            .advance_time(Duration::from_millis(48))
125            .unwrap();
126        assert_eq!(
127            ui.poll_event().unwrap(),
128            Some(UiEvent::MotionTicked {
129                motion,
130                widget_id: widget,
131                progress: 1.0,
132            })
133        );
134        assert_eq!(
135            ui.poll_event().unwrap(),
136            Some(UiEvent::MotionFinished {
137                motion,
138                widget_id: widget,
139            })
140        );
141        assert_eq!(ui.poll_event().unwrap(), None);
142    }
143
144    #[test]
145    fn cancellation_purges_queued_ticks_and_stops_future_progress() {
146        let mut ui = Ui::new(MockBackend::default());
147        let widget = ui.create(WidgetKind::Button, Some("cancel")).unwrap();
148        let motion = ui.start_motion(widget, motion(64)).unwrap();
149
150        ui.backend_mut().advance_time(MOTION_TICK_CADENCE).unwrap();
151        ui.cancel_motion(motion).unwrap();
152        assert_eq!(ui.poll_event().unwrap(), None);
153
154        ui.backend_mut()
155            .advance_time(Duration::from_secs(1))
156            .unwrap();
157        assert_eq!(ui.poll_event().unwrap(), None);
158    }
159
160    #[test]
161    fn removing_widget_cancels_motion_and_purges_queued_ticks() {
162        let mut ui = Ui::new(MockBackend::default());
163        let widget = ui.create(WidgetKind::Button, Some("removed")).unwrap();
164        let motion = ui.start_motion(widget, motion(64)).unwrap();
165
166        ui.backend_mut().advance_time(MOTION_TICK_CADENCE).unwrap();
167        ui.remove(widget).unwrap();
168        assert_eq!(ui.poll_event().unwrap(), None);
169        assert_eq!(
170            ui.cancel_motion(motion),
171            Err(GuiError::Backend("Motion not found: 1".to_owned()))
172        );
173    }
174
175    #[test]
176    fn hiding_widget_does_not_stop_its_motion() {
177        let mut ui = Ui::new(MockBackend::default());
178        let widget = ui.create(WidgetKind::Button, Some("hidden")).unwrap();
179        let motion = ui.start_motion(widget, motion(32)).unwrap();
180        ui.hide(widget).unwrap();
181        ui.backend_mut().advance_time(MOTION_TICK_CADENCE).unwrap();
182
183        assert!(matches!(
184            ui.poll_event().unwrap(),
185            Some(UiEvent::MotionTicked {
186                motion: event_motion,
187                widget_id,
188                progress,
189            }) if event_motion == motion && widget_id == widget && progress == 0.5
190        ));
191    }
192
193    #[test]
194    fn native_refusal_zero_duration_and_timer_deadline_overflow_are_explicit() {
195        let mut backend = MockBackend::default();
196        backend.set_motion_capabilities(MotionCapabilities::none());
197        let mut ui = Ui::new(backend);
198        let widget = ui.create(WidgetKind::Button, Some("refused")).unwrap();
199
200        assert_eq!(
201            ui.start_motion(widget, motion(32)),
202            Err(GuiError::UnsupportedCapability("ui_motion".to_owned()))
203        );
204        assert_eq!(
205            ui.start_motion(widget, motion(0)),
206            Err(GuiError::Backend(
207                "Motion duration must be non-zero".to_owned()
208            ))
209        );
210
211        ui.backend_mut()
212            .set_motion_capabilities(MotionCapabilities { motions: true });
213        ui.backend_mut().advance_time(Duration::MAX).unwrap();
214        assert!(matches!(
215            ui.start_motion(widget, motion(32)),
216            Err(GuiError::Backend(message)) if message.contains("deadline overflow")
217        ));
218    }
219
220    #[test]
221    fn short_motions_finish_at_their_first_deadline() {
222        let mut ui = Ui::new(MockBackend::default());
223        let widget = ui.create(WidgetKind::Button, Some("short")).unwrap();
224        let motion = ui.start_motion(widget, motion(5)).unwrap();
225        ui.backend_mut()
226            .advance_time(Duration::from_millis(4))
227            .unwrap();
228        assert_eq!(ui.poll_event().unwrap(), None);
229        ui.backend_mut()
230            .advance_time(Duration::from_millis(1))
231            .unwrap();
232
233        assert_eq!(
234            ui.poll_event().unwrap(),
235            Some(UiEvent::MotionTicked {
236                motion,
237                widget_id: widget,
238                progress: 1.0,
239            })
240        );
241        assert_eq!(
242            ui.poll_event().unwrap(),
243            Some(UiEvent::MotionFinished {
244                motion,
245                widget_id: widget,
246            })
247        );
248    }
249
250    #[test]
251    fn motion_ids_are_monotonic_and_timer_events_remain_distinct() {
252        let mut ui = Ui::new(MockBackend::default());
253        let widget = ui.create(WidgetKind::Button, Some("ids")).unwrap();
254        let timer = ui
255            .start_timer(TimerSpec {
256                first_delay: MOTION_TICK_CADENCE,
257                interval: Some(MOTION_TICK_CADENCE),
258                coalesce: true,
259            })
260            .unwrap();
261        let first = ui.start_motion(widget, motion(64)).unwrap();
262        ui.cancel_motion(first).unwrap();
263        let second = ui.start_motion(widget, motion(64)).unwrap();
264        assert_eq!(first, MotionId(1));
265        assert_eq!(second, MotionId(2));
266
267        ui.backend_mut().advance_time(MOTION_TICK_CADENCE).unwrap();
268        assert_eq!(
269            ui.poll_event().unwrap(),
270            Some(UiEvent::TimerFired {
271                timer,
272                elapsed: MOTION_TICK_CADENCE,
273                missed: 0,
274            })
275        );
276        assert!(matches!(
277            ui.poll_event().unwrap(),
278            Some(UiEvent::MotionTicked {
279                motion,
280                widget_id,
281                ..
282            }) if motion == second && widget_id == widget
283        ));
284    }
285}