Skip to main content

waft_animation/
animation_controller.rs

1//! Flutter counterpart: `animation/animation_controller.dart`.
2
3use std::cell::Cell;
4use std::rc::Rc;
5use std::time::Duration;
6
7use waft_embedder::{clamp_double, lerp_double};
8use waft_foundation::{App, Handle, ListenableObject, Listener, OptionRetained, Ref};
9use waft_physics::{Simulation, SpringDescription, SpringSimulation, SpringType, Tolerance};
10use waft_scheduler::{FrameCallback, Ticker, TickerFuture, TickerProvider};
11
12use crate::animation::{
13    Animation, AnimationStatus, AnimationStatusListener, AnyAnimation, animation_status_symbol,
14};
15use crate::curves::{Curve, Curves};
16use crate::listener_helpers::{
17    AnimationEagerListenerMixin, AnimationLocalListenersData, AnimationLocalListenersMixin,
18    AnimationLocalStatusListenersData, AnimationLocalStatusListenersMixin,
19};
20
21/// Dart's private `_AnimationDirection`: the direction in which an animation
22/// is running.
23#[derive(Debug, Clone, Copy, PartialEq, Eq)]
24enum AnimationDirection {
25    /// The animation is running from beginning to end.
26    Forward,
27
28    /// The animation is running backwards, from end to beginning.
29    Reverse,
30}
31
32/// Dart's `final _kFlingSpringDescription` — computed, so a function rather
33/// than a constant.
34fn k_fling_spring_description() -> SpringDescription {
35    SpringDescription::with_damping_ratio(1.0, 500.0)
36}
37
38const K_FLING_TOLERANCE: Tolerance = Tolerance {
39    velocity: f64::INFINITY,
40    distance: 0.01,
41    time: 1e-3, // Tolerance's default, spelled out — Rust has no partial const
42};
43
44/// Configures how an [`AnimationController`] behaves when animations are
45/// disabled.
46///
47/// When accessibility features such as "remove animations" are enabled, the
48/// device asks Flutter to reduce or disable animations as much as possible.
49#[derive(Debug, Clone, Copy, PartialEq, Eq)]
50pub enum AnimationBehavior {
51    /// The [`AnimationController`] will reduce its duration when animations
52    /// are disabled by the platform.
53    Normal,
54
55    /// The [`AnimationController`] will preserve its behavior.
56    Preserve,
57}
58
59impl AnimationBehavior {
60    /// Dart's `_enableAnimations` reads
61    /// `SemanticsBinding.instance.disableAnimations`; the semantics binding
62    /// is not ported, so animations are always enabled. See `PORTING.md`.
63    fn enable_animations(self) -> bool {
64        match self {
65            AnimationBehavior::Normal => true,
66            AnimationBehavior::Preserve => true,
67        }
68    }
69}
70
71/// A controller for an animation.
72///
73/// This class lets you perform tasks such as:
74///
75/// * Play an animation forward or in reverse, or stop an animation.
76/// * Set the animation to a specific value.
77/// * Define the upper and lower bounds of an animation.
78/// * Create a fling animation effect using a physics simulation.
79///
80/// By default, an [`AnimationController`] linearly produces values that range
81/// from 0.0 to 1.0, during a given duration.
82///
83/// An [`AnimationController`] needs a `TickerProvider`, Dart's `vsync`
84/// constructor argument.
85pub struct AnimationController {
86    /// The value at which this animation is deemed to be dismissed.
87    pub lower_bound: f64,
88
89    /// The value at which this animation is deemed to be completed.
90    pub upper_bound: f64,
91
92    /// The behavior of the controller when accessibility features disable
93    /// animations.
94    pub animation_behavior: AnimationBehavior,
95
96    /// The length of time this animation should last.
97    ///
98    /// If [`reverse_duration`](AnimationController::reverse_duration) is
99    /// specified, then [`duration`](AnimationController::duration) is only
100    /// used when going forward. Otherwise, it specifies the duration going in
101    /// both directions.
102    pub duration: Option<Duration>,
103
104    /// The length of time this animation should last when going in reverse.
105    ///
106    /// The value of [`duration`](AnimationController::duration) is used if
107    /// this is `None`.
108    pub reverse_duration: Option<Duration>,
109
110    ticker: Option<Ref<Ticker>>,
111    simulation: Option<Rc<dyn Simulation>>,
112    value: f64,
113    last_elapsed_duration: Option<Duration>,
114    direction: AnimationDirection,
115    status: AnimationStatus,
116    last_reported_status: AnimationStatus,
117
118    // Dart's `_directionSetter` tear-off, which `_RepeatingSimulation.x`
119    // calls from a context with no App: the setter writes this detached cell
120    // and the controller applies it immediately after each `x()` returns,
121    // before the value assignment — Dart's observable order.
122    pending_direction: Rc<Cell<Option<AnimationDirection>>>,
123
124    // Mixin state: `AnimationEagerListenerMixin` (stateless),
125    // `AnimationLocalListenersMixin`, `AnimationLocalStatusListenersMixin`.
126    local_listeners: AnimationLocalListenersData,
127    local_status_listeners: AnimationLocalStatusListenersData,
128}
129
130impl AnimationController {
131    /// Dart's `AnimationController.toString`, which it inherits from `Animation`.
132    pub fn to_string(self: Handle<Self>, app: &App) -> String {
133        Animation::<f64>::to_string(self, app)
134    }
135
136    /// Creates an animation controller.
137    ///
138    /// `value` is the initial value of the animation; `None` means
139    /// `lower_bound`. `vsync` is the required `TickerProvider`. Dart's
140    /// defaults: `lower_bound` 0.0, `upper_bound` 1.0, `animation_behavior`
141    /// `Normal`; `debugLabel` is not ported.
142    ///
143    /// Dart's constructor registers the `_tick` tear-off with the vended
144    /// ticker, so creation goes through the [`App`].
145    #[allow(clippy::too_many_arguments)]
146    #[track_caller]
147    pub fn new(
148        app: &mut App,
149        value: Option<f64>,
150        duration: Option<Duration>,
151        reverse_duration: Option<Duration>,
152        lower_bound: f64,
153        upper_bound: f64,
154        animation_behavior: AnimationBehavior,
155        vsync: impl TickerProvider,
156    ) -> Ref<AnimationController> {
157        debug_assert!(upper_bound >= lower_bound);
158        let this = app.create(AnimationController {
159            lower_bound,
160            upper_bound,
161            animation_behavior,
162            duration,
163            reverse_duration,
164            ticker: None,
165            simulation: None,
166            value: 0.0,
167            last_elapsed_duration: None,
168            direction: AnimationDirection::Forward,
169            status: AnimationStatus::Dismissed,
170            last_reported_status: AnimationStatus::Dismissed,
171            pending_direction: Rc::new(Cell::new(None)),
172            local_listeners: AnimationLocalListenersData::new(),
173            local_status_listeners: AnimationLocalStatusListenersData::new(),
174        });
175        app.expect_dispose(&this);
176        let ticker = vsync.create_ticker(
177            app,
178            FrameCallback::handle_method(this.handle(), AnimationController::tick),
179        );
180        app.get_mut(&this).ticker = Some(ticker);
181        this.internal_set_value(app, value.unwrap_or(lower_bound));
182        this
183    }
184
185    /// Creates an animation controller with no upper or lower bound for its
186    /// value.
187    ///
188    /// Dart's defaults: `value` 0.0, `animation_behavior` `Preserve`.
189    #[track_caller]
190    pub fn unbounded(
191        app: &mut App,
192        value: f64,
193        duration: Option<Duration>,
194        reverse_duration: Option<Duration>,
195        animation_behavior: AnimationBehavior,
196        vsync: impl TickerProvider,
197    ) -> Ref<AnimationController> {
198        let this = app.create(AnimationController {
199            lower_bound: f64::NEG_INFINITY,
200            upper_bound: f64::INFINITY,
201            animation_behavior,
202            duration,
203            reverse_duration,
204            ticker: None,
205            simulation: None,
206            value: 0.0,
207            last_elapsed_duration: None,
208            direction: AnimationDirection::Forward,
209            status: AnimationStatus::Dismissed,
210            last_reported_status: AnimationStatus::Dismissed,
211            pending_direction: Rc::new(Cell::new(None)),
212            local_listeners: AnimationLocalListenersData::new(),
213            local_status_listeners: AnimationLocalStatusListenersData::new(),
214        });
215        app.expect_dispose(&this);
216        let ticker = vsync.create_ticker(
217            app,
218            FrameCallback::handle_method(this.handle(), AnimationController::tick),
219        );
220        app.get_mut(&this).ticker = Some(ticker);
221        this.internal_set_value(app, value);
222        this
223    }
224
225    /// The current value of the animation.
226    pub fn value(self: Handle<Self>, app: &App) -> f64 {
227        app.get(self).value
228    }
229
230    /// The current status of this animation.
231    pub fn status(self: Handle<Self>, app: &App) -> AnimationStatus {
232        app.get(self).status
233    }
234
235    /// The amount of time that has passed between the time the animation
236    /// started and the most recent tick of the animation.
237    ///
238    /// If the controller is not animating, the last elapsed duration is
239    /// `None`.
240    pub fn last_elapsed_duration(self: Handle<Self>, app: &App) -> Option<Duration> {
241        app.get(self).last_elapsed_duration
242    }
243}
244
245impl AnimationController {
246    fn internal_set_value(self: Handle<Self>, app: &mut App, new_value: f64) {
247        let controller = app.get_mut(self);
248        controller.value = clamp_double(new_value, controller.lower_bound, controller.upper_bound);
249        if controller.value == controller.lower_bound {
250            controller.status = AnimationStatus::Dismissed;
251        } else if controller.value == controller.upper_bound {
252            controller.status = AnimationStatus::Completed;
253        } else {
254            controller.status = match controller.direction {
255                AnimationDirection::Forward => AnimationStatus::Forward,
256                AnimationDirection::Reverse => AnimationStatus::Reverse,
257            };
258        }
259    }
260
261    fn animate_to_internal(
262        self: Handle<Self>,
263        app: &mut App,
264        target: f64,
265        duration: Option<Duration>,
266        curve: Rc<dyn Curve>,
267    ) -> TickerFuture {
268        let controller = app.get(self);
269        let scale = if controller.animation_behavior.enable_animations() {
270            1.0
271        } else {
272            0.05
273        };
274        let mut simulation_duration = duration;
275        if simulation_duration.is_none() {
276            debug_assert!(
277                !(controller.duration.is_none()
278                    && controller.direction == AnimationDirection::Forward)
279            );
280            debug_assert!(
281                !(controller.duration.is_none()
282                    && controller.direction == AnimationDirection::Reverse
283                    && controller.reverse_duration.is_none())
284            );
285            let range = controller.upper_bound - controller.lower_bound;
286            let remaining_fraction = if range.is_finite() {
287                (target - controller.value).abs() / range
288            } else {
289                1.0
290            };
291            // Dart: `(_direction == reverse && reverseDuration != null)
292            // ? reverseDuration! : this.duration!`.
293            let direction_duration = match (controller.direction, controller.reverse_duration) {
294                (AnimationDirection::Reverse, Some(reverse_duration)) => reverse_duration,
295                _ => controller.duration.unwrap(),
296            };
297            // Dart's `Duration operator *`: the product rounded to whole microseconds.
298            simulation_duration = Some(Duration::from_micros(
299                (direction_duration.as_micros() as f64 * remaining_fraction).round() as u64,
300            ));
301        } else if target == controller.value {
302            simulation_duration = Some(Duration::ZERO);
303        }
304        let simulation_duration = simulation_duration.unwrap();
305
306        self.stop(app, true);
307        if simulation_duration == Duration::ZERO {
308            let controller = app.get_mut(self);
309            if controller.value != target {
310                controller.value =
311                    clamp_double(target, controller.lower_bound, controller.upper_bound);
312                self.notify_listeners(app);
313            }
314            let controller = app.get_mut(self);
315            controller.status = if controller.direction == AnimationDirection::Forward {
316                AnimationStatus::Completed
317            } else {
318                AnimationStatus::Dismissed
319            };
320            self.check_status_changed(app);
321            return TickerFuture::complete();
322        }
323        debug_assert!(simulation_duration > Duration::ZERO);
324        debug_assert!(!self.is_animating(app));
325        let value = app.get(self).value;
326        self.start_simulation(
327            app,
328            Rc::new(InterpolationSimulation::new(
329                value,
330                target,
331                simulation_duration,
332                curve,
333                scale,
334            )),
335        )
336    }
337
338    fn direction_setter(self: Handle<Self>, app: &mut App, direction: AnimationDirection) {
339        let controller = app.get_mut(self);
340        controller.direction = direction;
341        controller.status = if direction == AnimationDirection::Forward {
342            AnimationStatus::Forward
343        } else {
344            AnimationStatus::Reverse
345        };
346        self.check_status_changed(app);
347    }
348
349    fn drain_pending_direction(self: Handle<Self>, app: &mut App) {
350        if let Some(direction) = app.get(self).pending_direction.take() {
351            self.direction_setter(app, direction);
352        }
353    }
354
355    fn start_simulation(
356        self: Handle<Self>,
357        app: &mut App,
358        simulation: Rc<dyn Simulation>,
359    ) -> TickerFuture {
360        debug_assert!(!self.is_animating(app));
361        let x = simulation.x(0.0);
362        // The repeating simulation's direction setter fires during `x(0.0)`;
363        // Dart runs it inside that call, before the value assignment.
364        {
365            let controller = app.get_mut(self);
366            controller.simulation = Some(simulation);
367            controller.last_elapsed_duration = Some(Duration::ZERO);
368        }
369        self.drain_pending_direction(app);
370        let controller = app.get_mut(self);
371        controller.value = clamp_double(x, controller.lower_bound, controller.upper_bound);
372        let ticker = controller.ticker.handle().expect("started after dispose");
373        let result = ticker.start(app);
374        let controller = app.get_mut(self);
375        controller.status = if controller.direction == AnimationDirection::Forward {
376            AnimationStatus::Forward
377        } else {
378            AnimationStatus::Reverse
379        };
380        self.check_status_changed(app);
381        result
382    }
383
384    fn check_status_changed(self: Handle<Self>, app: &mut App) {
385        let controller = app.get_mut(self);
386        let new_status = controller.status;
387        if controller.last_reported_status != new_status {
388            controller.last_reported_status = new_status;
389            self.notify_status_listeners(app, new_status);
390        }
391    }
392
393    fn tick(self: Handle<Self>, app: &mut App, elapsed: Duration) {
394        app.get_mut(self).last_elapsed_duration = Some(elapsed);
395        let elapsed_in_seconds = elapsed.as_micros() as f64 / 1_000_000.0;
396        debug_assert!(elapsed_in_seconds >= 0.0);
397        let simulation = app.get(self).simulation.clone().unwrap();
398        let x = simulation.x(elapsed_in_seconds);
399        // The repeating simulation's direction setter fires during `x()`;
400        // Dart runs it inside that call, before the value assignment.
401        self.drain_pending_direction(app);
402        let controller = app.get_mut(self);
403        controller.value = clamp_double(x, controller.lower_bound, controller.upper_bound);
404        // Dart re-derefs `_simulation!` here, so a status listener that
405        // replaced the simulation is consulted, and one that stopped the
406        // controller crashes the tick — the panic is that crash.
407        let simulation = app
408            .get(self)
409            .simulation
410            .clone()
411            .expect("a listener stopped the controller during its own tick");
412        if simulation.is_done(elapsed_in_seconds) {
413            let controller = app.get_mut(self);
414            controller.status = if controller.direction == AnimationDirection::Forward {
415                AnimationStatus::Completed
416            } else {
417                AnimationStatus::Dismissed
418            };
419            self.stop(app, false);
420        }
421        self.notify_listeners(app);
422        self.check_status_changed(app);
423    }
424}
425
426impl AnimationEagerListenerMixin for AnimationController {}
427
428impl AnimationLocalListenersMixin for AnimationController {
429    fn local_listeners_data(self: Handle<Self>, app: &App) -> &AnimationLocalListenersData {
430        &app.get(self).local_listeners
431    }
432
433    fn local_listeners_data_mut(
434        self: Handle<Self>,
435        app: &mut App,
436    ) -> &mut AnimationLocalListenersData {
437        &mut app.get_mut(self).local_listeners
438    }
439
440    // Dart resolves these by mixin order — `AnimationEagerListenerMixin`.
441    fn did_register_listener(self: Handle<Self>, app: &mut App) {
442        AnimationEagerListenerMixin::did_register_listener(self, app)
443    }
444
445    fn did_unregister_listener(self: Handle<Self>, app: &mut App) {
446        AnimationEagerListenerMixin::did_unregister_listener(self, app)
447    }
448}
449
450impl AnimationLocalStatusListenersMixin for AnimationController {
451    fn local_status_listeners_data(
452        self: Handle<Self>,
453        app: &App,
454    ) -> &AnimationLocalStatusListenersData {
455        &app.get(self).local_status_listeners
456    }
457
458    fn local_status_listeners_data_mut(
459        self: Handle<Self>,
460        app: &mut App,
461    ) -> &mut AnimationLocalStatusListenersData {
462        &mut app.get_mut(self).local_status_listeners
463    }
464
465    fn did_register_listener(self: Handle<Self>, app: &mut App) {
466        AnimationEagerListenerMixin::did_register_listener(self, app)
467    }
468
469    fn did_unregister_listener(self: Handle<Self>, app: &mut App) {
470        AnimationEagerListenerMixin::did_unregister_listener(self, app)
471    }
472}
473
474impl ListenableObject for AnimationController {
475    fn add_listener(self: Handle<Self>, app: &mut App, listener: Listener) {
476        AnimationLocalListenersMixin::add_listener(self, app, listener);
477    }
478
479    fn remove_listener(self: Handle<Self>, app: &mut App, listener: &Listener) {
480        AnimationLocalListenersMixin::remove_listener(self, app, listener);
481    }
482}
483
484// Dart: `class AnimationController extends Animation<double> with
485// AnimationEagerListenerMixin, AnimationLocalListenersMixin,
486// AnimationLocalStatusListenersMixin`.
487impl Animation<f64> for AnimationController {
488    fn add_listener(self: Handle<Self>, app: &mut App, listener: Listener) {
489        AnimationLocalListenersMixin::add_listener(self, app, listener)
490    }
491
492    fn remove_listener(self: Handle<Self>, app: &mut App, listener: &Listener) {
493        AnimationLocalListenersMixin::remove_listener(self, app, listener)
494    }
495
496    fn add_status_listener(self: Handle<Self>, app: &mut App, listener: AnimationStatusListener) {
497        AnimationLocalStatusListenersMixin::add_status_listener(self, app, listener)
498    }
499
500    fn remove_status_listener(
501        self: Handle<Self>,
502        app: &mut App,
503        listener: &AnimationStatusListener,
504    ) {
505        AnimationLocalStatusListenersMixin::remove_status_listener(self, app, listener)
506    }
507
508    fn status(self: Handle<Self>, app: &App) -> AnimationStatus {
509        app.get(self).status
510    }
511
512    fn value(self: Handle<Self>, app: &App) -> f64 {
513        app.get(self).value
514    }
515
516    fn to_string_details(self: Handle<Self>, app: &App) -> String {
517        let paused = if Animation::<f64>::is_animating(self, app) {
518            ""
519        } else {
520            "; paused"
521        };
522        let ticker = match app.get(self).ticker.handle() {
523            None => "; DISPOSED",
524            Some(ticker) if ticker.muted(app) => "; silenced",
525            Some(_) => "",
526        };
527        format!(
528            "{} {:.3}{paused}{ticker}",
529            animation_status_symbol(Animation::<f64>::status(self, app)),
530            self.value(app)
531        )
532    }
533
534    // Dart overrides `isAnimating` away from the status-derived default
535    // (`animation_controller.dart:449`): a muted or off-screen controller is
536    // animating even while its status says otherwise.
537    fn is_animating(self: Handle<Self>, app: &App) -> bool {
538        match app.get(self).ticker.handle() {
539            Some(ticker) => ticker.is_active(app),
540            None => false,
541        }
542    }
543}
544
545/// Dart's private `_InterpolationSimulation`.
546struct InterpolationSimulation {
547    duration_in_seconds: f64,
548    begin: f64,
549    end: f64,
550    curve: Rc<dyn Curve>,
551    tolerance: Tolerance,
552}
553
554impl InterpolationSimulation {
555    fn new(
556        begin: f64,
557        end: f64,
558        duration: Duration,
559        curve: Rc<dyn Curve>,
560        scale: f64,
561    ) -> InterpolationSimulation {
562        debug_assert!(duration.as_micros() > 0);
563        InterpolationSimulation {
564            duration_in_seconds: (duration.as_micros() as f64 * scale) / 1_000_000.0,
565            begin,
566            end,
567            curve,
568            tolerance: Tolerance::DEFAULT_TOLERANCE,
569        }
570    }
571}
572
573impl Simulation for InterpolationSimulation {
574    fn x(&self, time_in_seconds: f64) -> f64 {
575        let t = clamp_double(time_in_seconds / self.duration_in_seconds, 0.0, 1.0);
576        if t == 0.0 {
577            self.begin
578        } else if t == 1.0 {
579            self.end
580        } else {
581            self.begin + (self.end - self.begin) * self.curve.transform(t)
582        }
583    }
584
585    fn dx(&self, time_in_seconds: f64) -> f64 {
586        let epsilon = self.tolerance.time;
587        (self.x(time_in_seconds + epsilon) - self.x(time_in_seconds - epsilon)) / (2.0 * epsilon)
588    }
589
590    fn is_done(&self, time_in_seconds: f64) -> bool {
591        time_in_seconds > self.duration_in_seconds
592    }
593
594    fn tolerance(&self) -> Tolerance {
595        self.tolerance
596    }
597
598    fn set_tolerance(&mut self, tolerance: Tolerance) {
599        self.tolerance = tolerance;
600    }
601}
602
603impl std::fmt::Debug for InterpolationSimulation {
604    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
605        f.write_str("_InterpolationSimulation")
606    }
607}
608
609/// Dart's private `_RepeatingSimulation`.
610///
611/// Dart's `directionSetter` is a tear-off of the controller's
612/// `_directionSetter`, called from `x()` — a context with no App here. The
613/// setter's counterpart is the shared `pending_direction` cell, which the
614/// controller drains immediately after each `x()` call.
615struct RepeatingSimulation {
616    min: f64,
617    max: f64,
618    reverse: bool,
619    count: Option<u64>,
620    direction_setter: Rc<Cell<Option<AnimationDirection>>>,
621    period_in_seconds: f64,
622    initial_t: f64,
623    exit_time_in_seconds: Option<f64>,
624    tolerance: Tolerance,
625}
626
627impl RepeatingSimulation {
628    fn new(
629        initial_value: f64,
630        min: f64,
631        max: f64,
632        reverse: bool,
633        period: Duration,
634        direction_setter: Rc<Cell<Option<AnimationDirection>>>,
635        count: Option<u64>,
636    ) -> RepeatingSimulation {
637        debug_assert!(count.is_none_or(|count| count > 0));
638        let period_in_seconds = period.as_micros() as f64 / 1_000_000.0;
639        let initial_t = if max == min {
640            0.0
641        } else {
642            ((clamp_double(initial_value, min, max) - min) / (max - min)) * period_in_seconds
643        };
644        debug_assert!(period_in_seconds > 0.0);
645        debug_assert!(initial_t >= 0.0);
646        // Dart's `late final _exitTimeInSeconds` dereferences `count!` and is
647        // only read when `count != null`.
648        let exit_time_in_seconds =
649            count.map(|count| (count as f64 * period_in_seconds) - initial_t);
650        RepeatingSimulation {
651            min,
652            max,
653            reverse,
654            count,
655            direction_setter,
656            period_in_seconds,
657            initial_t,
658            exit_time_in_seconds,
659            tolerance: Tolerance::DEFAULT_TOLERANCE,
660        }
661    }
662}
663
664impl Simulation for RepeatingSimulation {
665    fn x(&self, time_in_seconds: f64) -> f64 {
666        debug_assert!(time_in_seconds >= 0.0);
667        let total_time_in_seconds = time_in_seconds + self.initial_t;
668        let t = (total_time_in_seconds / self.period_in_seconds) % 1.0;
669        // Dart: `(total ~/ period).isOdd` — truncating integer division.
670        let is_playing_reverse =
671            (total_time_in_seconds / self.period_in_seconds).trunc() as i64 % 2 != 0;
672        if self.reverse && is_playing_reverse {
673            self.direction_setter.set(Some(AnimationDirection::Reverse));
674            // Dart: `ui.lerpDouble(max, min, t)!`.
675            lerp_double(Some(self.max), Some(self.min), t).unwrap()
676        } else {
677            self.direction_setter.set(Some(AnimationDirection::Forward));
678            lerp_double(Some(self.min), Some(self.max), t).unwrap()
679        }
680    }
681
682    fn dx(&self, _time_in_seconds: f64) -> f64 {
683        (self.max - self.min) / self.period_in_seconds
684    }
685
686    fn is_done(&self, time_in_seconds: f64) -> bool {
687        self.count.is_some() && time_in_seconds >= self.exit_time_in_seconds.unwrap()
688    }
689
690    fn tolerance(&self) -> Tolerance {
691        self.tolerance
692    }
693
694    fn set_tolerance(&mut self, tolerance: Tolerance) {
695        self.tolerance = tolerance;
696    }
697}
698
699impl std::fmt::Debug for RepeatingSimulation {
700    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
701        f.write_str("_RepeatingSimulation")
702    }
703}
704
705impl AnimationController {
706    /// An [`AnyAnimation<f64>`] view of this controller — what to pass where a
707    /// Dart API wants an `Animation<double>`. Dart's `view` getter returns
708    /// `this`; the erased handle is that upcast.
709    pub fn view(self: Handle<Self>) -> AnyAnimation<f64> {
710        self.as_animation()
711    }
712
713    /// Recreates the [`Ticker`] with the new `TickerProvider`.
714    pub fn resync(self: Handle<Self>, app: &mut App, vsync: impl TickerProvider) {
715        let ticker = vsync.create_ticker(
716            app,
717            FrameCallback::handle_method(self, AnimationController::tick),
718        );
719        let old_ticker = app
720            .get_mut(self)
721            .ticker
722            .replace(ticker.clone())
723            .expect("resync after dispose");
724        ticker.absorb_ticker(app, old_ticker.handle());
725    }
726
727    /// Stops the animation controller and sets the current value of the
728    /// animation.
729    pub fn set_value(self: Handle<Self>, app: &mut App, new_value: f64) {
730        self.stop(app, true);
731        self.internal_set_value(app, new_value);
732        self.notify_listeners(app);
733        self.check_status_changed(app);
734    }
735
736    /// Sets the controller's value to the lower bound, stopping the animation.
737    pub fn reset(self: Handle<Self>, app: &mut App) {
738        let lower_bound = app.get(self).lower_bound;
739        self.set_value(app, lower_bound);
740    }
741
742    /// The rate of change of [`AnimationController::value`] per second.
743    pub fn velocity(self: Handle<Self>, app: &mut App) -> f64 {
744        if !self.is_animating(app) {
745            return 0.0;
746        }
747        let controller = app.get(self);
748        let elapsed = controller.last_elapsed_duration.unwrap();
749        controller
750            .simulation
751            .as_ref()
752            .unwrap()
753            .dx(elapsed.as_micros() as f64 / 1_000_000.0)
754    }
755
756    /// Whether this animation is currently animating in either the forward or
757    /// reverse direction.
758    #[allow(clippy::wrong_self_convention)]
759    pub fn is_animating(self: Handle<Self>, app: &mut App) -> bool {
760        // One body: Dart has a single isAnimating override, and it lives in
761        // the Animation impl so the erased handle dispatches it too.
762        <AnimationController as Animation<f64>>::is_animating(self, app)
763    }
764
765    /// Starts running this animation forwards (towards the end).
766    pub fn forward(self: Handle<Self>, app: &mut App, from: Option<f64>) -> TickerFuture {
767        debug_assert!(
768            app.get(self).duration.is_some(),
769            "AnimationController::forward() called with no default duration. The \"duration\" \
770             property should be set, either in the constructor or later, before calling forward()."
771        );
772        debug_assert!(
773            app.get(self).ticker.is_some(),
774            "AnimationController::forward() called after AnimationController::dispose()."
775        );
776        app.get_mut(self).direction = AnimationDirection::Forward;
777        if let Some(from) = from {
778            self.set_value(app, from);
779        }
780        let upper_bound = app.get(self).upper_bound;
781        self.animate_to_internal(app, upper_bound, None, Curves::linear())
782    }
783
784    /// Starts running this animation in reverse (towards the beginning).
785    pub fn reverse(self: Handle<Self>, app: &mut App, from: Option<f64>) -> TickerFuture {
786        debug_assert!(
787            app.get(self).duration.is_some() || app.get(self).reverse_duration.is_some(),
788            "AnimationController::reverse() called with no default duration or reverseDuration."
789        );
790        debug_assert!(
791            app.get(self).ticker.is_some(),
792            "AnimationController::reverse() called after AnimationController::dispose()."
793        );
794        app.get_mut(self).direction = AnimationDirection::Reverse;
795        if let Some(from) = from {
796            self.set_value(app, from);
797        }
798        let lower_bound = app.get(self).lower_bound;
799        self.animate_to_internal(app, lower_bound, None, Curves::linear())
800    }
801
802    /// Toggles the direction of this animation.
803    pub fn toggle(self: Handle<Self>, app: &mut App, from: Option<f64>) -> TickerFuture {
804        debug_assert!(
805            {
806                let controller = app.get(self);
807                let mut duration = controller.duration;
808                if controller.status.is_forward_or_completed() {
809                    duration = duration.or(controller.reverse_duration);
810                }
811                duration.is_some()
812            },
813            "AnimationController::toggle() called with no default duration."
814        );
815        debug_assert!(
816            app.get(self).ticker.is_some(),
817            "AnimationController::toggle() called after AnimationController::dispose()."
818        );
819        let forward_or_completed = app.get(self).status.is_forward_or_completed();
820        app.get_mut(self).direction = if forward_or_completed {
821            AnimationDirection::Reverse
822        } else {
823            AnimationDirection::Forward
824        };
825        if let Some(from) = from {
826            self.set_value(app, from);
827        }
828        let target = match app.get(self).direction {
829            AnimationDirection::Forward => app.get(self).upper_bound,
830            AnimationDirection::Reverse => app.get(self).lower_bound,
831        };
832        self.animate_to_internal(app, target, None, Curves::linear())
833    }
834
835    /// Drives the animation from its current value to `target`.
836    pub fn animate_to(
837        self: Handle<Self>,
838        app: &mut App,
839        target: f64,
840        duration: Option<Duration>,
841        curve: Rc<dyn Curve>,
842    ) -> TickerFuture {
843        debug_assert!(
844            app.get(self).duration.is_some() || duration.is_some(),
845            "AnimationController::animate_to() called with no explicit duration and no default \
846             duration."
847        );
848        debug_assert!(
849            app.get(self).ticker.is_some(),
850            "AnimationController::animate_to() called after AnimationController::dispose()."
851        );
852        app.get_mut(self).direction = AnimationDirection::Forward;
853        self.animate_to_internal(app, target, duration, curve)
854    }
855
856    /// Drives the animation from its current value to `target`, going in reverse.
857    pub fn animate_back(
858        self: Handle<Self>,
859        app: &mut App,
860        target: f64,
861        duration: Option<Duration>,
862        curve: Rc<dyn Curve>,
863    ) -> TickerFuture {
864        debug_assert!(
865            app.get(self).duration.is_some()
866                || app.get(self).reverse_duration.is_some()
867                || duration.is_some(),
868            "AnimationController::animate_back() called with no explicit duration and no default \
869             duration or reverseDuration."
870        );
871        debug_assert!(
872            app.get(self).ticker.is_some(),
873            "AnimationController::animate_back() called after AnimationController::dispose()."
874        );
875        app.get_mut(self).direction = AnimationDirection::Reverse;
876        self.animate_to_internal(app, target, duration, curve)
877    }
878
879    /// Starts running this animation in the forward direction, and restarts
880    /// the animation when it completes.
881    pub fn repeat(
882        self: Handle<Self>,
883        app: &mut App,
884        min: Option<f64>,
885        max: Option<f64>,
886        reverse: bool,
887        period: Option<Duration>,
888        count: Option<u64>,
889    ) -> TickerFuture {
890        let controller = app.get(self);
891        let min = min.unwrap_or(controller.lower_bound);
892        let max = max.unwrap_or(controller.upper_bound);
893        let period = period.or(controller.duration);
894        debug_assert!(
895            period.is_some(),
896            "AnimationController::repeat() called without an explicit period and with no default \
897             Duration."
898        );
899        debug_assert!(max >= min);
900        debug_assert!(max <= controller.upper_bound && min >= controller.lower_bound);
901        debug_assert!(count.is_none_or(|count| count > 0));
902        self.stop(app, true);
903        let (value, pending_direction) = {
904            let controller = app.get(self);
905            (controller.value, Rc::clone(&controller.pending_direction))
906        };
907        self.start_simulation(
908            app,
909            Rc::new(RepeatingSimulation::new(
910                value,
911                min,
912                max,
913                reverse,
914                period.unwrap(),
915                pending_direction,
916                count,
917            )),
918        )
919    }
920
921    /// Drives the animation with a spring and initial `velocity`.
922    pub fn fling(
923        self: Handle<Self>,
924        app: &mut App,
925        velocity: f64,
926        spring_description: Option<SpringDescription>,
927        animation_behavior: Option<AnimationBehavior>,
928    ) -> TickerFuture {
929        let spring_description = spring_description.unwrap_or_else(k_fling_spring_description);
930        let controller = app.get_mut(self);
931        controller.direction = if velocity < 0.0 {
932            AnimationDirection::Reverse
933        } else {
934            AnimationDirection::Forward
935        };
936        let target = if velocity < 0.0 {
937            controller.lower_bound - K_FLING_TOLERANCE.distance
938        } else {
939            controller.upper_bound + K_FLING_TOLERANCE.distance
940        };
941        let behavior = animation_behavior.unwrap_or(controller.animation_behavior);
942        let scale = if behavior.enable_animations() {
943            1.0
944        } else {
945            200.0
946        };
947        let mut simulation = SpringSimulation::new(
948            spring_description,
949            controller.value,
950            target,
951            velocity * scale,
952        );
953        simulation.set_tolerance(K_FLING_TOLERANCE);
954        debug_assert!(
955            simulation.spring_type() != SpringType::UnderDamped,
956            "The specified spring simulation is of type SpringType.underDamped. An underdamped \
957             spring results in oscillation rather than a fling."
958        );
959        self.stop(app, true);
960        self.start_simulation(app, Rc::new(simulation))
961    }
962
963    /// Drives the animation according to the given simulation.
964    pub fn animate_with(
965        self: Handle<Self>,
966        app: &mut App,
967        simulation: Box<dyn Simulation>,
968    ) -> TickerFuture {
969        debug_assert!(
970            app.get(self).ticker.is_some(),
971            "AnimationController::animate_with() called after AnimationController::dispose()."
972        );
973        self.stop(app, true);
974        app.get_mut(self).direction = AnimationDirection::Forward;
975        self.start_simulation(app, Rc::from(simulation))
976    }
977
978    /// Like [`animate_with`](AnimationController::animate_with), but the status
979    /// is reported as [`AnimationStatus::Reverse`].
980    pub fn animate_back_with(
981        self: Handle<Self>,
982        app: &mut App,
983        simulation: Box<dyn Simulation>,
984    ) -> TickerFuture {
985        debug_assert!(
986            app.get(self).ticker.is_some(),
987            "AnimationController::animate_back_with() called after AnimationController::dispose()."
988        );
989        self.stop(app, true);
990        app.get_mut(self).direction = AnimationDirection::Reverse;
991        self.start_simulation(app, Rc::from(simulation))
992    }
993
994    /// Stops running this animation.
995    pub fn stop(self: Handle<Self>, app: &mut App, canceled: bool) {
996        debug_assert!(
997            app.get(self).ticker.is_some(),
998            "AnimationController::stop() called after AnimationController::dispose()."
999        );
1000        let controller = app.get_mut(self);
1001        controller.simulation = None;
1002        controller.last_elapsed_duration = None;
1003        let ticker = controller.ticker.handle().unwrap();
1004        ticker.stop(app, canceled);
1005    }
1006
1007    /// Release the resources used by this object. The object is no longer
1008    /// usable after this method is called.
1009    pub fn dispose(self: Handle<Self>, app: &mut App) {
1010        debug_assert!(
1011            app.get(self).ticker.is_some(),
1012            "AnimationController::dispose() called more than once."
1013        );
1014        app.mark_disposed(self);
1015        let ticker = app.get_mut(self).ticker.take().unwrap();
1016        ticker.dispose(app);
1017        self.clear_status_listeners(app);
1018        self.clear_listeners(app);
1019        AnimationEagerListenerMixin::dispose(self, app);
1020    }
1021}
1022
1023#[cfg(test)]
1024mod tests {
1025    use std::cell::{Cell, RefCell};
1026    use std::rc::Rc;
1027    use waft_foundation::AppCell;
1028
1029    use waft_scheduler::{SchedulerBinding, TickerCallback};
1030
1031    use super::*;
1032
1033    fn assert_future_completed(app: &mut App, future: TickerFuture) {
1034        let ran = Rc::new(Cell::new(false));
1035        future.when_complete(
1036            app,
1037            Listener::new({
1038                let ran = Rc::clone(&ran);
1039                move |_app| ran.set(true)
1040            }),
1041        );
1042        app.drain_microtasks();
1043        assert!(ran.get(), "TickerFuture should have completed");
1044    }
1045
1046    fn assert_future_canceled(app: &mut App, future: TickerFuture) {
1047        let completed = Rc::new(Cell::new(false));
1048        let either = Rc::new(Cell::new(false));
1049        future.when_complete(
1050            app,
1051            Listener::new({
1052                let completed = Rc::clone(&completed);
1053                move |_app| completed.set(true)
1054            }),
1055        );
1056        future.when_complete_or_cancel(
1057            app,
1058            Listener::new({
1059                let either = Rc::clone(&either);
1060                move |_app| either.set(true)
1061            }),
1062        );
1063        app.drain_microtasks();
1064        assert!(!completed.get(), "primary future never resolves on cancel");
1065        assert!(either.get(), "when_complete_or_cancel observes cancel");
1066    }
1067
1068    /// flutter_test's `TestVSync`: vends ordinary tickers, in no view.
1069    struct TestVSync;
1070
1071    impl TickerProvider for TestVSync {
1072        fn create_ticker(&self, app: &mut App, on_tick: TickerCallback) -> Ref<Ticker> {
1073            Ticker::new(app, on_tick, None)
1074        }
1075    }
1076
1077    /// A frame at `at`, of no view: the tickers here are in none.
1078    fn pump(app: &mut App, at: Duration) {
1079        SchedulerBinding::handle_begin_frame(app, &[], Some(at));
1080        app.drain_microtasks();
1081        SchedulerBinding::handle_draw_frame(app, &[]);
1082        app.drain_microtasks();
1083    }
1084
1085    fn controller_with_duration(app: &mut App, ms: u64) -> Ref<AnimationController> {
1086        AnimationController::new(
1087            app,
1088            None,
1089            Some(Duration::from_millis(ms)),
1090            None,
1091            0.0,
1092            1.0,
1093            AnimationBehavior::Normal,
1094            TestVSync,
1095        )
1096    }
1097
1098    // Dart's `Duration * double` rounds to whole microseconds, so what is left of a
1099    // 200ms run from 1e-6 short of the end, 0.2µs, is zero, and the run ends at once; an
1100    // unrounded product would leave 200ns to animate.
1101    #[test]
1102    fn a_controller_a_hair_short_of_its_target_completes_at_once() {
1103        let cell = AppCell::new();
1104        let mut app = cell.borrow_mut();
1105        let controller = controller_with_duration(&mut app, 200);
1106        controller.set_value(&mut app, 1.0 - 1e-6);
1107
1108        controller.forward(&mut app, None);
1109
1110        assert_eq!(controller.value(&app), 1.0);
1111        assert_eq!(controller.status(&app), AnimationStatus::Completed);
1112        assert!(!controller.is_animating(&mut app));
1113    }
1114
1115    // animation_controller_test.dart 'Can set value during status callback'
1116    // family reduced to the core drive: forward moves the value linearly and
1117    // ends Completed.
1118    #[test]
1119    fn forward_drives_the_value_to_the_upper_bound() {
1120        let cell = AppCell::new();
1121        let mut app = cell.borrow_mut();
1122        let controller = controller_with_duration(&mut app, 100);
1123
1124        controller.forward(&mut app, None);
1125        assert!(controller.is_animating(&mut app));
1126        assert_eq!(controller.status(&app), AnimationStatus::Forward);
1127
1128        pump(&mut app, Duration::from_millis(0)); // first tick: elapsed 0
1129        assert_eq!(controller.value(&app), 0.0);
1130
1131        pump(&mut app, Duration::from_millis(50)); // elapsed 50ms of 100ms
1132        assert_eq!(controller.value(&app), 0.5);
1133
1134        pump(&mut app, Duration::from_millis(150)); // past the end
1135        assert_eq!(controller.value(&app), 1.0);
1136        assert_eq!(controller.status(&app), AnimationStatus::Completed);
1137        assert!(!controller.is_animating(&mut app));
1138    }
1139
1140    #[test]
1141    fn reverse_drives_the_value_to_the_lower_bound() {
1142        let cell = AppCell::new();
1143        let mut app = cell.borrow_mut();
1144        let controller = controller_with_duration(&mut app, 100);
1145
1146        controller.reverse(&mut app, Some(1.0));
1147        assert_eq!(controller.status(&app), AnimationStatus::Reverse);
1148
1149        pump(&mut app, Duration::from_millis(0));
1150        pump(&mut app, Duration::from_millis(50));
1151        assert_eq!(controller.value(&app), 0.5);
1152
1153        pump(&mut app, Duration::from_millis(150));
1154        assert_eq!(controller.value(&app), 0.0);
1155        assert_eq!(controller.status(&app), AnimationStatus::Dismissed);
1156    }
1157
1158    #[test]
1159    fn the_status_listener_sees_forward_then_completed() {
1160        let cell = AppCell::new();
1161        let mut app = cell.borrow_mut();
1162        let controller = controller_with_duration(&mut app, 100);
1163
1164        let log = Rc::new(RefCell::new(Vec::new()));
1165        controller.view().add_status_listener(
1166            &mut app,
1167            AnimationStatusListener::new({
1168                let log = Rc::clone(&log);
1169                move |status, _app| log.borrow_mut().push(status)
1170            }),
1171        );
1172
1173        controller.forward(&mut app, None);
1174        pump(&mut app, Duration::from_millis(0));
1175        pump(&mut app, Duration::from_millis(150));
1176
1177        assert_eq!(
1178            *log.borrow(),
1179            vec![AnimationStatus::Forward, AnimationStatus::Completed]
1180        );
1181    }
1182
1183    // The value setter stops the animation and notifies even without change.
1184    #[test]
1185    fn set_value_stops_the_animation_and_notifies() {
1186        let cell = AppCell::new();
1187        let mut app = cell.borrow_mut();
1188        let controller = controller_with_duration(&mut app, 100);
1189
1190        let notified = Rc::new(RefCell::new(0));
1191        controller.view().add_listener(
1192            &mut app,
1193            Listener::new({
1194                let notified = Rc::clone(&notified);
1195                move |_app| *notified.borrow_mut() += 1
1196            }),
1197        );
1198
1199        controller.forward(&mut app, None);
1200        assert!(controller.is_animating(&mut app));
1201
1202        controller.set_value(&mut app, 0.5);
1203        assert!(!controller.is_animating(&mut app));
1204        assert_eq!(controller.value(&app), 0.5);
1205        assert_eq!(*notified.borrow(), 1);
1206        assert_eq!(controller.status(&app), AnimationStatus::Forward);
1207    }
1208
1209    // The zero-duration path returns Dart's `TickerFuture.complete()`.
1210    #[test]
1211    fn a_zero_duration_animate_to_completes_synchronously() {
1212        let cell = AppCell::new();
1213        let mut app = cell.borrow_mut();
1214        let controller = controller_with_duration(&mut app, 100);
1215
1216        let future = controller.animate_to(&mut app, 1.0, Some(Duration::ZERO), Curves::linear());
1217        assert_eq!(controller.value(&app), 1.0);
1218        assert_eq!(controller.status(&app), AnimationStatus::Completed);
1219        assert!(!controller.is_animating(&mut app));
1220        assert_future_completed(&mut app, future);
1221    }
1222
1223    // animation_controller_test.dart 'Repeating animation with reverse: true'
1224    // (adapted): the direction setter flips the reported status mid-repeat.
1225    #[test]
1226    fn a_reversing_repeat_flips_the_status_each_period() {
1227        let cell = AppCell::new();
1228        let mut app = cell.borrow_mut();
1229        let controller = controller_with_duration(&mut app, 100);
1230
1231        let log = Rc::new(RefCell::new(Vec::new()));
1232        controller.view().add_status_listener(
1233            &mut app,
1234            AnimationStatusListener::new({
1235                let log = Rc::clone(&log);
1236                move |status, _app| log.borrow_mut().push(status)
1237            }),
1238        );
1239
1240        controller.repeat(&mut app, None, None, true, None, None);
1241        pump(&mut app, Duration::from_millis(0));
1242        pump(&mut app, Duration::from_millis(50));
1243        assert_eq!(controller.value(&app), 0.5);
1244        assert_eq!(controller.status(&app), AnimationStatus::Forward);
1245
1246        // Dart's test pins the boundary: just before the period ends the
1247        // status is still forward; exactly at it, reverse.
1248        pump(&mut app, Duration::from_millis(99));
1249        assert_eq!(controller.status(&app), AnimationStatus::Forward);
1250        pump(&mut app, Duration::from_millis(100));
1251        assert_eq!(controller.status(&app), AnimationStatus::Reverse);
1252
1253        // Second period: playing in reverse. (0.15/0.1) % 1.0 carries float
1254        // residue in Dart too; its test uses moreOrLessEquals.
1255        pump(&mut app, Duration::from_millis(150));
1256        assert!((controller.value(&app) - 0.5).abs() < 1e-9);
1257        assert_eq!(controller.status(&app), AnimationStatus::Reverse);
1258        assert_eq!(
1259            *log.borrow(),
1260            vec![AnimationStatus::Forward, AnimationStatus::Reverse]
1261        );
1262
1263        controller.stop(&mut app, true);
1264    }
1265
1266    // The headline order claim of the direction-setter translation: a status
1267    // listener notified by the mid-repeat flip observes the PRE-tick value,
1268    // because the drain runs before the tick's value assignment — where
1269    // Dart's in-`x()` setter call sits.
1270    #[test]
1271    fn the_direction_flip_notification_sees_the_pre_tick_value() {
1272        let cell = AppCell::new();
1273        let mut app = cell.borrow_mut();
1274        let controller = controller_with_duration(&mut app, 100);
1275
1276        let observed = Rc::new(RefCell::new(Vec::new()));
1277        let view = controller.view();
1278        controller.view().add_status_listener(
1279            &mut app,
1280            AnimationStatusListener::new({
1281                let observed = Rc::clone(&observed);
1282                move |status, app: &mut App| {
1283                    if status == AnimationStatus::Reverse {
1284                        let value = view.value(app);
1285                        observed.borrow_mut().push(value);
1286                    }
1287                }
1288            }),
1289        );
1290
1291        controller.repeat(&mut app, None, None, true, None, None);
1292        pump(&mut app, Duration::from_millis(0));
1293        pump(&mut app, Duration::from_millis(50)); // value 0.5
1294        pump(&mut app, Duration::from_millis(100)); // flip: tick will write 1.0
1295
1296        assert_eq!(
1297            *observed.borrow(),
1298            vec![0.5],
1299            "the flip notification ran before the tick assigned the new value"
1300        );
1301        controller.stop(&mut app, true);
1302    }
1303
1304    // repeat with a count resolves the future once the periods are spent.
1305    #[test]
1306    fn a_counted_repeat_completes() {
1307        let cell = AppCell::new();
1308        let mut app = cell.borrow_mut();
1309        let controller = controller_with_duration(&mut app, 100);
1310
1311        let future = controller.repeat(&mut app, None, None, false, None, Some(1));
1312        pump(&mut app, Duration::from_millis(0));
1313        pump(&mut app, Duration::from_millis(50));
1314        assert!(controller.is_animating(&mut app));
1315
1316        pump(&mut app, Duration::from_millis(100)); // exit time reached
1317        assert!(!controller.is_animating(&mut app));
1318        assert_future_completed(&mut app, future);
1319        assert_eq!(controller.status(&app), AnimationStatus::Completed);
1320        // Dart's boundary value: t wraps to 0 at the exact period end, so
1321        // the final value is min, not max.
1322        assert_eq!(controller.value(&app), 0.0);
1323    }
1324
1325    // fling reaches the bound and reports Completed; the overshoot target is
1326    // clamped away.
1327    #[test]
1328    fn fling_completes_at_the_upper_bound() {
1329        let cell = AppCell::new();
1330        let mut app = cell.borrow_mut();
1331        let controller = controller_with_duration(&mut app, 100);
1332
1333        controller.fling(&mut app, 1.0, None, None);
1334        let mut at = Duration::ZERO;
1335        for _ in 0..600 {
1336            if !controller.is_animating(&mut app) {
1337                break;
1338            }
1339            pump(&mut app, at);
1340            at += Duration::from_millis(16);
1341        }
1342        assert!(!controller.is_animating(&mut app));
1343        assert_eq!(controller.value(&app), 1.0);
1344        assert_eq!(controller.status(&app), AnimationStatus::Completed);
1345    }
1346
1347    // Disposing mid-flight cancels the ticker future without completing it.
1348    #[test]
1349    fn dispose_cancels_the_in_flight_future() {
1350        let cell = AppCell::new();
1351        let mut app = cell.borrow_mut();
1352        let controller = controller_with_duration(&mut app, 100);
1353
1354        let future = controller.forward(&mut app, None);
1355        let either = Rc::new(RefCell::new(false));
1356        future.when_complete_or_cancel(
1357            &mut app,
1358            Listener::new({
1359                let either = Rc::clone(&either);
1360                move |_app| *either.borrow_mut() = true
1361            }),
1362        );
1363
1364        controller.dispose(&mut app);
1365        assert_future_canceled(&mut app, future);
1366        assert!(*either.borrow());
1367    }
1368
1369    #[cfg(debug_assertions)]
1370    #[test]
1371    #[should_panic(expected = "dispose() called more than once")]
1372    fn a_second_dispose_panics_in_debug() {
1373        let cell = AppCell::new();
1374        let mut app = cell.borrow_mut();
1375        let controller = controller_with_duration(&mut app, 100);
1376        controller.dispose(&mut app);
1377        controller.dispose(&mut app);
1378    }
1379
1380    // The velocity getter reads the simulation's dx at the last elapsed time.
1381    #[test]
1382    fn velocity_is_zero_when_not_animating() {
1383        let cell = AppCell::new();
1384        let mut app = cell.borrow_mut();
1385        let controller = controller_with_duration(&mut app, 100);
1386        assert_eq!(controller.velocity(&mut app), 0.0);
1387
1388        controller.forward(&mut app, None);
1389        pump(&mut app, Duration::from_millis(0));
1390        pump(&mut app, Duration::from_millis(50));
1391        // Linear 0..1 over 100ms: 10 units/second.
1392        assert!((controller.velocity(&mut app) - 10.0).abs() < 0.5);
1393    }
1394}