Skip to main content

waft_animation/
animations.rs

1//! Flutter counterpart: `animation/animations.dart`.
2
3use std::rc::Rc;
4
5use waft_foundation::{App, Handle, ListenableObject, Listener, OptionRetained, Ref};
6
7use crate::animation::{
8    Animation, AnimationRef, AnimationStatus, AnimationStatusListener, AnyAnimation,
9};
10use crate::curves::Curve;
11use crate::listener_helpers::{
12    AnimationEagerListenerMixin, AnimationLazyListenerData, AnimationLazyListenerMixin,
13    AnimationLocalListenersData, AnimationLocalListenersMixin, AnimationLocalStatusListenersData,
14    AnimationLocalStatusListenersMixin,
15};
16
17/// Dart's `_AlwaysCompleteAnimation`. Private like the original; reach it
18/// through [`k_always_complete_animation`].
19#[derive(Default)]
20struct AlwaysCompleteAnimation;
21
22impl Animation<f64> for AlwaysCompleteAnimation {
23    fn add_listener(self: Handle<Self>, _app: &mut App, _listener: Listener) {}
24
25    fn remove_listener(self: Handle<Self>, _app: &mut App, _listener: &Listener) {}
26
27    fn add_status_listener(self: Handle<Self>, _app: &mut App, _listener: AnimationStatusListener) {
28    }
29
30    fn remove_status_listener(
31        self: Handle<Self>,
32        _app: &mut App,
33        _listener: &AnimationStatusListener,
34    ) {
35    }
36
37    fn status(self: Handle<Self>, _app: &App) -> AnimationStatus {
38        AnimationStatus::Completed
39    }
40
41    fn value(self: Handle<Self>, _app: &App) -> f64 {
42        1.0
43    }
44}
45
46/// An animation that is always complete.
47///
48/// Using this involves less overhead than building an `AnimationController`
49/// with an initial value of 1.0. This is useful when an API expects an
50/// animation but you don't actually want to animate anything.
51///
52/// Dart's `kAlwaysCompleteAnimation` is a `const` — every mention is one
53/// canonical object — and ours is the App's singleton of the same type, so
54/// every call returns the same identity, as Dart's mentions do. The App keeps
55/// it; the returned reference is one more keeper, for a field that holds it.
56pub fn k_always_complete_animation(app: &mut App) -> AnimationRef<f64> {
57    singleton_animation::<AlwaysCompleteAnimation>(app)
58}
59
60/// The App's singleton `A`, as an animation a field can keep.
61fn singleton_animation<A: Animation<f64> + Default>(app: &mut App) -> AnimationRef<f64> {
62    app.singleton::<A>().keep(app).into_erased()
63}
64
65/// Dart's `_AlwaysDismissedAnimation`. Private like the original; reach it
66/// through [`k_always_dismissed_animation`].
67#[derive(Default)]
68struct AlwaysDismissedAnimation;
69
70impl Animation<f64> for AlwaysDismissedAnimation {
71    fn add_listener(self: Handle<Self>, _app: &mut App, _listener: Listener) {}
72
73    fn remove_listener(self: Handle<Self>, _app: &mut App, _listener: &Listener) {}
74
75    fn add_status_listener(self: Handle<Self>, _app: &mut App, _listener: AnimationStatusListener) {
76    }
77
78    fn remove_status_listener(
79        self: Handle<Self>,
80        _app: &mut App,
81        _listener: &AnimationStatusListener,
82    ) {
83    }
84
85    fn status(self: Handle<Self>, _app: &App) -> AnimationStatus {
86        AnimationStatus::Dismissed
87    }
88
89    fn value(self: Handle<Self>, _app: &App) -> f64 {
90        0.0
91    }
92}
93
94/// An animation that is always dismissed.
95///
96/// Using this involves less overhead than building an `AnimationController`
97/// with an initial value of 0.0. This is useful when an API expects an
98/// animation but you don't actually want to animate anything.
99///
100/// See [`k_always_complete_animation`] for how the identity matches Dart's
101/// `const`.
102pub fn k_always_dismissed_animation(app: &mut App) -> AnimationRef<f64> {
103    singleton_animation::<AlwaysDismissedAnimation>(app)
104}
105
106/// An animation that is always stopped at a given value.
107///
108/// The status is always [`AnimationStatus::Forward`].
109pub struct AlwaysStoppedAnimation<T> {
110    /// The value at which this animation is stopped.
111    ///
112    /// Since the value and status of an [`AlwaysStoppedAnimation`] can never
113    /// change, the listeners can never be called. It is therefore safe to
114    /// reuse one in multiple places.
115    pub value: T,
116}
117
118impl<T> AlwaysStoppedAnimation<T> {
119    /// Creates an [`AlwaysStoppedAnimation`] with the given value.
120    pub const fn new(value: T) -> AlwaysStoppedAnimation<T> {
121        AlwaysStoppedAnimation { value }
122    }
123}
124
125impl<T: Clone + 'static> Animation<T> for AlwaysStoppedAnimation<T> {
126    fn add_listener(self: Handle<Self>, _app: &mut App, _listener: Listener) {}
127
128    fn remove_listener(self: Handle<Self>, _app: &mut App, _listener: &Listener) {}
129
130    fn add_status_listener(self: Handle<Self>, _app: &mut App, _listener: AnimationStatusListener) {
131    }
132
133    fn remove_status_listener(
134        self: Handle<Self>,
135        _app: &mut App,
136        _listener: &AnimationStatusListener,
137    ) {
138    }
139
140    fn status(self: Handle<Self>, _app: &App) -> AnimationStatus {
141        AnimationStatus::Forward
142    }
143
144    fn value(self: Handle<Self>, app: &App) -> T {
145        app.get(self).value.clone()
146    }
147}
148
149/// Implements most of the animation interface by deferring its behavior to a
150/// given [`parent`] animation.
151///
152/// To implement an animation that is driven by a parent, it is only necessary
153/// to implement this trait, supply [`parent`], and implement
154/// [`Animation::value`].
155///
156/// To define a mapping from values in the range 0..1, consider subclassing
157/// `Tween` instead.
158///
159/// [`parent`]: AnimationWithParent::parent
160pub trait AnimationWithParent<T: 'static>: Sized + 'static {
161    /// The animation whose value this animation will proxy.
162    ///
163    /// This animation must remain the same for the lifetime of this object. If
164    /// you wish to proxy a different animation at different times, consider
165    /// using [`ProxyAnimation`].
166    fn parent(self: Handle<Self>, app: &App) -> AnyAnimation<T>;
167
168    /// Calls the listener every time the value of the animation changes.
169    ///
170    /// Listeners can be removed with [`remove_listener`].
171    ///
172    /// [`remove_listener`]: AnimationWithParent::remove_listener
173    fn add_listener(self: Handle<Self>, app: &mut App, listener: Listener) {
174        let parent = self.parent(app);
175        parent.add_listener(app, listener);
176    }
177
178    /// Stop calling the listener every time the value of the animation
179    /// changes.
180    ///
181    /// Listeners can be added with [`add_listener`].
182    ///
183    /// [`add_listener`]: AnimationWithParent::add_listener
184    fn remove_listener(self: Handle<Self>, app: &mut App, listener: &Listener) {
185        let parent = self.parent(app);
186        parent.remove_listener(app, listener);
187    }
188
189    /// Calls listener every time the status of the animation changes.
190    ///
191    /// Listeners can be removed with [`remove_status_listener`].
192    ///
193    /// [`remove_status_listener`]: AnimationWithParent::remove_status_listener
194    fn add_status_listener(self: Handle<Self>, app: &mut App, listener: AnimationStatusListener) {
195        let parent = self.parent(app);
196        parent.add_status_listener(app, listener);
197    }
198
199    /// Stops calling the listener every time the status of the animation
200    /// changes.
201    ///
202    /// Listeners can be added with [`add_status_listener`].
203    ///
204    /// [`add_status_listener`]: AnimationWithParent::add_status_listener
205    fn remove_status_listener(
206        self: Handle<Self>,
207        app: &mut App,
208        listener: &AnimationStatusListener,
209    ) {
210        let parent = self.parent(app);
211        parent.remove_status_listener(app, listener);
212    }
213
214    /// The current status of this animation.
215    fn status(self: Handle<Self>, app: &App) -> AnimationStatus {
216        self.parent(app).status(app)
217    }
218}
219
220/// An animation that is a proxy for another animation.
221///
222/// A proxy animation is useful because the parent animation can be mutated.
223/// For example, one object can create a proxy animation, hand the proxy to
224/// another object, and then later change the animation from which the proxy
225/// receives its value.
226pub struct ProxyAnimation {
227    status: Option<AnimationStatus>,
228    value: Option<f64>,
229    parent: Option<AnimationRef<f64>>,
230
231    // Dart mixes in `AnimationLazyListenerMixin`,
232    // `AnimationLocalListenersMixin` and `AnimationLocalStatusListenersMixin`;
233    // their state lives here and reaches the traits through the accessors.
234    lazy_listener: AnimationLazyListenerData,
235    local_listeners: AnimationLocalListenersData,
236    local_status_listeners: AnimationLocalStatusListenersData,
237}
238
239impl ProxyAnimation {
240    /// Creates a proxy animation.
241    ///
242    /// If the animation argument is `None`, the proxy animation has the status
243    /// [`AnimationStatus::Dismissed`] and a value of 0.0.
244    #[track_caller]
245    pub fn new(app: &mut App, animation: Option<AnimationRef<f64>>) -> Ref<ProxyAnimation> {
246        let mut result = ProxyAnimation {
247            status: None,
248            value: None,
249            parent: animation,
250            lazy_listener: AnimationLazyListenerData::new(),
251            local_listeners: AnimationLocalListenersData::new(),
252            local_status_listeners: AnimationLocalStatusListenersData::new(),
253        };
254        if result.parent.is_none() {
255            result.status = Some(AnimationStatus::Dismissed);
256            result.value = Some(0.0);
257        }
258        app.create(result)
259    }
260
261    /// The animation whose value this animation will proxy.
262    ///
263    /// This value is mutable ([`set_parent`](ProxyAnimation::set_parent)).
264    /// When mutated, the listeners on the proxy animation will be
265    /// transparently updated to be listening to the new parent animation.
266    ///
267    /// The bare handle, which the proxy keeps alive while it is the parent; a
268    /// caller that keeps it takes [`AnyAnimation::upgrade`].
269    pub fn parent(self: Handle<Self>, app: &App) -> Option<AnyAnimation<f64>> {
270        app.get(self).parent.handle()
271    }
272
273    /// Changes the animation whose value this animation proxies.
274    ///
275    /// Dart's `parent` setter, `animations.dart:200`.
276    pub fn set_parent(self: Handle<Self>, app: &mut App, value: Option<AnimationRef<f64>>) {
277        if value == app.get(self).parent {
278            return;
279        }
280        if let Some(parent) = self.parent(app) {
281            let (status, current) = (parent.status(app), parent.value(app));
282            let proxy = app.get_mut(self);
283            proxy.status = Some(status);
284            proxy.value = Some(current);
285            if self.is_listening(app) {
286                self.did_stop_listening(app);
287            }
288        }
289        // The old parent goes when this local does, after the listeners have moved off it.
290        let _old_parent = std::mem::replace(&mut app.get_mut(self).parent, value);
291        if let Some(parent) = self.parent(app) {
292            if self.is_listening(app) {
293                self.did_start_listening(app);
294            }
295            if app.get(self).value != Some(parent.value(app)) {
296                self.notify_listeners(app);
297            }
298            let status = parent.status(app);
299            if app.get(self).status != Some(status) {
300                self.notify_status_listeners(app, status);
301            }
302            let proxy = app.get_mut(self);
303            proxy.status = None;
304            proxy.value = None;
305        }
306    }
307}
308
309impl AnimationLazyListenerMixin for ProxyAnimation {
310    fn lazy_listener_data(self: Handle<Self>, app: &App) -> &AnimationLazyListenerData {
311        &app.get(self).lazy_listener
312    }
313
314    fn lazy_listener_data_mut(self: Handle<Self>, app: &mut App) -> &mut AnimationLazyListenerData {
315        &mut app.get_mut(self).lazy_listener
316    }
317
318    fn did_start_listening(self: Handle<Self>, app: &mut App) {
319        if let Some(parent) = self.parent(app) {
320            // Dart: `_parent!.addListener(notifyListeners)` — a tear-off.
321            // `handle_method` gives the rebuilt listener the same identity, so
322            // `did_stop_listening` removes without a stored handle.
323            parent.add_listener(
324                app,
325                Listener::handle_method(self, ProxyAnimation::notify_listeners),
326            );
327            parent.add_status_listener(
328                app,
329                AnimationStatusListener::handle_method(
330                    self,
331                    ProxyAnimation::notify_status_listeners,
332                ),
333            );
334        }
335    }
336
337    fn did_stop_listening(self: Handle<Self>, app: &mut App) {
338        if let Some(parent) = self.parent(app) {
339            parent.remove_listener(
340                app,
341                &Listener::handle_method(self, ProxyAnimation::notify_listeners),
342            );
343            parent.remove_status_listener(
344                app,
345                &AnimationStatusListener::handle_method(
346                    self,
347                    ProxyAnimation::notify_status_listeners,
348                ),
349            );
350        }
351    }
352}
353
354impl AnimationLocalListenersMixin for ProxyAnimation {
355    fn local_listeners_data(self: Handle<Self>, app: &App) -> &AnimationLocalListenersData {
356        &app.get(self).local_listeners
357    }
358
359    fn local_listeners_data_mut(
360        self: Handle<Self>,
361        app: &mut App,
362    ) -> &mut AnimationLocalListenersData {
363        &mut app.get_mut(self).local_listeners
364    }
365
366    // Dart resolves these two by mixin order — `AnimationLazyListenerMixin` is
367    // the one that declares them in ProxyAnimation's `with` clause. Rust has
368    // no such rule, so the choice is written out.
369    fn did_register_listener(self: Handle<Self>, app: &mut App) {
370        AnimationLazyListenerMixin::did_register_listener(self, app)
371    }
372
373    fn did_unregister_listener(self: Handle<Self>, app: &mut App) {
374        AnimationLazyListenerMixin::did_unregister_listener(self, app)
375    }
376}
377
378impl AnimationLocalStatusListenersMixin for ProxyAnimation {
379    fn local_status_listeners_data(
380        self: Handle<Self>,
381        app: &App,
382    ) -> &AnimationLocalStatusListenersData {
383        &app.get(self).local_status_listeners
384    }
385
386    fn local_status_listeners_data_mut(
387        self: Handle<Self>,
388        app: &mut App,
389    ) -> &mut AnimationLocalStatusListenersData {
390        &mut app.get_mut(self).local_status_listeners
391    }
392
393    fn did_register_listener(self: Handle<Self>, app: &mut App) {
394        AnimationLazyListenerMixin::did_register_listener(self, app)
395    }
396
397    fn did_unregister_listener(self: Handle<Self>, app: &mut App) {
398        AnimationLazyListenerMixin::did_unregister_listener(self, app)
399    }
400}
401
402impl ListenableObject for ProxyAnimation {
403    fn add_listener(self: Handle<Self>, app: &mut App, listener: Listener) {
404        AnimationLocalListenersMixin::add_listener(self, app, listener);
405    }
406
407    fn remove_listener(self: Handle<Self>, app: &mut App, listener: &Listener) {
408        AnimationLocalListenersMixin::remove_listener(self, app, listener);
409    }
410}
411
412// Dart: `class ProxyAnimation extends Animation<double> with
413// AnimationLazyListenerMixin, AnimationLocalListenersMixin,
414// AnimationLocalStatusListenersMixin`. The forwarding below is the `with`
415// clause: the mixins supply the listener protocol.
416impl Animation<f64> for ProxyAnimation {
417    fn add_listener(self: Handle<Self>, app: &mut App, listener: Listener) {
418        AnimationLocalListenersMixin::add_listener(self, app, listener)
419    }
420
421    fn remove_listener(self: Handle<Self>, app: &mut App, listener: &Listener) {
422        AnimationLocalListenersMixin::remove_listener(self, app, listener)
423    }
424
425    fn add_status_listener(self: Handle<Self>, app: &mut App, listener: AnimationStatusListener) {
426        AnimationLocalStatusListenersMixin::add_status_listener(self, app, listener)
427    }
428
429    fn remove_status_listener(
430        self: Handle<Self>,
431        app: &mut App,
432        listener: &AnimationStatusListener,
433    ) {
434        AnimationLocalStatusListenersMixin::remove_status_listener(self, app, listener)
435    }
436
437    fn status(self: Handle<Self>, app: &App) -> AnimationStatus {
438        match self.parent(app) {
439            Some(parent) => parent.status(app),
440            None => app
441                .get(self)
442                .status
443                .expect("a ProxyAnimation without a parent keeps its last status"),
444        }
445    }
446
447    fn value(self: Handle<Self>, app: &App) -> f64 {
448        match self.parent(app) {
449            Some(parent) => parent.value(app),
450            None => app
451                .get(self)
452                .value
453                .expect("a ProxyAnimation without a parent keeps its last value"),
454        }
455    }
456}
457
458/// An animation that is the reverse of another animation.
459///
460/// If the parent animation is running forward from 0.0 to 1.0, this animation
461/// is running in reverse from 1.0 to 0.0.
462///
463/// Using a [`ReverseAnimation`] is different from using a `Tween` with a
464/// `begin` of 1.0 and an `end` of 0.0 because the tween does not change the
465/// status or direction of the animation.
466pub struct ReverseAnimation {
467    // Dart: `final Animation<double> parent` — private with a getter so it
468    // cannot be rebound away from the animation the subscriptions target.
469    parent: AnimationRef<f64>,
470
471    // `AnimationLazyListenerMixin` and `AnimationLocalStatusListenersMixin`
472    // state.
473    lazy_listener: AnimationLazyListenerData,
474    local_status_listeners: AnimationLocalStatusListenersData,
475}
476
477impl ReverseAnimation {
478    /// Creates a reverse animation, which keeps `parent`.
479    #[track_caller]
480    pub fn new(app: &mut App, parent: AnimationRef<f64>) -> Ref<ReverseAnimation> {
481        app.create(ReverseAnimation {
482            parent,
483            lazy_listener: AnimationLazyListenerData::new(),
484            local_status_listeners: AnimationLocalStatusListenersData::new(),
485        })
486    }
487
488    /// The animation whose value and direction this animation is reversing.
489    pub fn parent(&self) -> AnyAnimation<f64> {
490        self.parent.handle()
491    }
492
493    fn status_change_handler(self: Handle<Self>, app: &mut App, status: AnimationStatus) {
494        self.notify_status_listeners(app, Self::reverse_status(status));
495    }
496
497    fn reverse_status(status: AnimationStatus) -> AnimationStatus {
498        match status {
499            AnimationStatus::Forward => AnimationStatus::Reverse,
500            AnimationStatus::Reverse => AnimationStatus::Forward,
501            AnimationStatus::Completed => AnimationStatus::Dismissed,
502            AnimationStatus::Dismissed => AnimationStatus::Completed,
503        }
504    }
505}
506
507impl AnimationLazyListenerMixin for ReverseAnimation {
508    fn lazy_listener_data(self: Handle<Self>, app: &App) -> &AnimationLazyListenerData {
509        &app.get(self).lazy_listener
510    }
511
512    fn lazy_listener_data_mut(self: Handle<Self>, app: &mut App) -> &mut AnimationLazyListenerData {
513        &mut app.get_mut(self).lazy_listener
514    }
515
516    fn did_start_listening(self: Handle<Self>, app: &mut App) {
517        let parent = app.get(self).parent();
518        parent.add_status_listener(
519            app,
520            AnimationStatusListener::handle_method(self, ReverseAnimation::status_change_handler),
521        );
522    }
523
524    fn did_stop_listening(self: Handle<Self>, app: &mut App) {
525        let parent = app.get(self).parent();
526        parent.remove_status_listener(
527            app,
528            &AnimationStatusListener::handle_method(self, ReverseAnimation::status_change_handler),
529        );
530    }
531}
532
533impl AnimationLocalStatusListenersMixin for ReverseAnimation {
534    fn local_status_listeners_data(
535        self: Handle<Self>,
536        app: &App,
537    ) -> &AnimationLocalStatusListenersData {
538        &app.get(self).local_status_listeners
539    }
540
541    fn local_status_listeners_data_mut(
542        self: Handle<Self>,
543        app: &mut App,
544    ) -> &mut AnimationLocalStatusListenersData {
545        &mut app.get_mut(self).local_status_listeners
546    }
547
548    fn did_register_listener(self: Handle<Self>, app: &mut App) {
549        AnimationLazyListenerMixin::did_register_listener(self, app)
550    }
551
552    fn did_unregister_listener(self: Handle<Self>, app: &mut App) {
553        AnimationLazyListenerMixin::did_unregister_listener(self, app)
554    }
555}
556
557// Dart: `class ReverseAnimation extends Animation<double> with
558// AnimationLazyListenerMixin, AnimationLocalStatusListenersMixin`. The value
559// listeners are the class's own overrides: they forward to the parent, but
560// count through the lazy mixin so the status subscription follows them.
561impl Animation<f64> for ReverseAnimation {
562    fn add_listener(self: Handle<Self>, app: &mut App, listener: Listener) {
563        AnimationLazyListenerMixin::did_register_listener(self, app);
564        let parent = app.get(self).parent();
565        parent.add_listener(app, listener);
566    }
567
568    fn remove_listener(self: Handle<Self>, app: &mut App, listener: &Listener) {
569        let parent = app.get(self).parent();
570        parent.remove_listener(app, listener);
571        AnimationLazyListenerMixin::did_unregister_listener(self, app);
572    }
573
574    fn add_status_listener(self: Handle<Self>, app: &mut App, listener: AnimationStatusListener) {
575        AnimationLocalStatusListenersMixin::add_status_listener(self, app, listener)
576    }
577
578    fn remove_status_listener(
579        self: Handle<Self>,
580        app: &mut App,
581        listener: &AnimationStatusListener,
582    ) {
583        AnimationLocalStatusListenersMixin::remove_status_listener(self, app, listener)
584    }
585
586    fn status(self: Handle<Self>, app: &App) -> AnimationStatus {
587        Self::reverse_status(app.get(self).parent().status(app))
588    }
589
590    fn value(self: Handle<Self>, app: &App) -> f64 {
591        1.0 - app.get(self).parent().value(app)
592    }
593}
594
595/// An animation that applies a curve to another animation.
596///
597/// [`CurvedAnimation`] is useful when you want to apply a non-linear [`Curve`]
598/// to an animation object, especially if you want different curves when the
599/// animation is going forward vs when it is going backward.
600///
601/// Depending on the given curve, the output of the [`CurvedAnimation`] could
602/// have a wider range than its input. For example, elastic curves such as
603/// `Curves::elastic_in()` will significantly overshoot or undershoot the
604/// default range of 0.0 to 1.0.
605///
606/// A [`CurvedAnimation`] should be disposed when no longer needed to clean up
607/// any listeners that it may have added.
608pub struct CurvedAnimation {
609    // Dart: `final Animation<double> parent` — private with the
610    // `AnimationWithParent::parent` getter, so it cannot be rebound away from
611    // the animation the constructor subscribed to.
612    parent: AnimationRef<f64>,
613
614    /// The curve to use in the forward direction.
615    pub curve: Rc<dyn Curve>,
616
617    /// The curve to use in the reverse direction.
618    ///
619    /// If the parent animation changes direction without first reaching the
620    /// [`AnimationStatus::Completed`] or [`AnimationStatus::Dismissed`]
621    /// status, the [`CurvedAnimation`] stays on the same curve (albeit in the
622    /// opposite direction) to avoid visual discontinuities.
623    ///
624    /// If this field is `None`, uses [`curve`](CurvedAnimation::curve) in both
625    /// directions.
626    pub reverse_curve: Option<Rc<dyn Curve>>,
627
628    /// The direction used to select the current curve.
629    ///
630    /// The curve direction is only reset when we hit the beginning or the end
631    /// of the timeline to avoid discontinuities in the value of any variables
632    /// this animation is used to animate.
633    curve_direction: Option<AnimationStatus>,
634
635    /// True if this CurvedAnimation has been disposed.
636    pub is_disposed: bool,
637}
638
639impl CurvedAnimation {
640    /// Creates a curved animation.
641    ///
642    /// Dart's constructor registers `_updateCurveDirection` on `parent` — a
643    /// tear-off of the object under construction — so creation goes through
644    /// the [`App`]: the entity exists first, then the constructor body runs in
645    /// Dart's statement order.
646    #[track_caller]
647    pub fn new(
648        app: &mut App,
649        parent: AnimationRef<f64>,
650        curve: Rc<dyn Curve>,
651        reverse_curve: Option<Rc<dyn Curve>>,
652    ) -> Ref<CurvedAnimation> {
653        let this = app.create(CurvedAnimation {
654            parent: parent.clone(),
655            curve,
656            reverse_curve,
657            curve_direction: None,
658            is_disposed: false,
659        });
660        app.expect_dispose(&this);
661        let status = parent.status(app);
662        this.update_curve_direction(app, status);
663        parent.add_status_listener(
664            app,
665            AnimationStatusListener::handle_method(
666                this.handle(),
667                CurvedAnimation::update_curve_direction,
668            ),
669        );
670        this
671    }
672
673    fn update_curve_direction(self: Handle<Self>, app: &mut App, status: AnimationStatus) {
674        let animation = app.get_mut(self);
675        animation.curve_direction = if status.is_animating() {
676            animation.curve_direction.or(Some(status))
677        } else {
678            None
679        };
680    }
681
682    fn use_forward_curve(self: Handle<Self>, app: &App) -> bool {
683        let animation = app.get(self);
684        animation.reverse_curve.is_none()
685            || animation
686                .curve_direction
687                .unwrap_or_else(|| animation.parent.status(app))
688                != AnimationStatus::Reverse
689    }
690
691    /// Cleans up any listeners added by this CurvedAnimation.
692    pub fn dispose(self: Handle<Self>, app: &mut App) {
693        app.get_mut(self).is_disposed = true;
694        app.mark_disposed(self);
695        let parent = app.get(self).parent.handle();
696        parent.remove_status_listener(
697            app,
698            &AnimationStatusListener::handle_method(self, CurvedAnimation::update_curve_direction),
699        );
700    }
701}
702
703impl AnimationWithParent<f64> for CurvedAnimation {
704    fn parent(self: Handle<Self>, app: &App) -> AnyAnimation<f64> {
705        app.get(self).parent.handle()
706    }
707}
708
709// Dart: `class CurvedAnimation extends Animation<double> with
710// AnimationWithParentMixin<double>`.
711impl Animation<f64> for CurvedAnimation {
712    fn add_listener(self: Handle<Self>, app: &mut App, listener: Listener) {
713        AnimationWithParent::add_listener(self, app, listener)
714    }
715
716    fn remove_listener(self: Handle<Self>, app: &mut App, listener: &Listener) {
717        AnimationWithParent::remove_listener(self, app, listener)
718    }
719
720    fn add_status_listener(self: Handle<Self>, app: &mut App, listener: AnimationStatusListener) {
721        AnimationWithParent::add_status_listener(self, app, listener)
722    }
723
724    fn remove_status_listener(
725        self: Handle<Self>,
726        app: &mut App,
727        listener: &AnimationStatusListener,
728    ) {
729        AnimationWithParent::remove_status_listener(self, app, listener)
730    }
731
732    fn status(self: Handle<Self>, app: &App) -> AnimationStatus {
733        AnimationWithParent::status(self, app)
734    }
735
736    fn value(self: Handle<Self>, app: &App) -> f64 {
737        let animation = app.get(self);
738        let active_curve = if self.use_forward_curve(app) {
739            Some(Rc::clone(&animation.curve))
740        } else {
741            animation.reverse_curve.clone()
742        };
743
744        let t = animation.parent.value(app);
745        let Some(active_curve) = active_curve else {
746            return t;
747        };
748        if t == 0.0 || t == 1.0 {
749            #[cfg(debug_assertions)]
750            {
751                let transformed_value = active_curve.transform(t);
752                let rounded_transformed_value = transformed_value.round();
753                assert!(
754                    rounded_transformed_value == t,
755                    "Invalid curve endpoint at {t}. Curves must map 0.0 to near zero and 1.0 to \
756                     near one but {active_curve:?} mapped {t} to {transformed_value}, which is \
757                     near {rounded_transformed_value}."
758                );
759            }
760            return t;
761        }
762        active_curve.transform(t)
763    }
764}
765
766/// Dart's private `_TrainHoppingMode`.
767#[derive(Clone, Copy, PartialEq, Eq, Debug)]
768enum TrainHoppingMode {
769    Minimize,
770    Maximize,
771}
772
773/// This animation starts by proxying one animation, but when the value of that
774/// animation crosses the value of the second (either because the second is
775/// going in the opposite direction, or because the one overtakes the other),
776/// the animation hops over to proxying the second animation.
777///
778/// When the [`TrainHoppingAnimation`] starts proxying the second animation
779/// instead of the first, the [`on_switched_train`] callback is called.
780///
781/// If the two animations start at the same value, then the
782/// [`TrainHoppingAnimation`] immediately hops to the second animation, and the
783/// [`on_switched_train`] callback is not called. If only one animation is
784/// provided (i.e. if the second is `None`), then the [`TrainHoppingAnimation`]
785/// just proxies the first animation.
786///
787/// Since this object must track the two animations even when it has no
788/// listeners of its own, instead of shutting down when all its listeners are
789/// removed, it exposes a [`dispose`] method. Call this method to shut this
790/// object down.
791///
792/// [`on_switched_train`]: TrainHoppingAnimation::on_switched_train
793/// [`dispose`]: TrainHoppingAnimation::dispose
794pub struct TrainHoppingAnimation {
795    current_train: Option<AnimationRef<f64>>,
796    next_train: Option<AnimationRef<f64>>,
797    mode: Option<TrainHoppingMode>,
798
799    /// Called when this animation switches to be driven by the second
800    /// animation.
801    ///
802    /// This is not called if the two animations provided to the constructor
803    /// have the same value at the time of the call to the constructor. In that
804    /// case, the second animation is used from the start, and the first is
805    /// ignored.
806    pub on_switched_train: Option<Listener>,
807
808    last_status: Option<AnimationStatus>,
809    last_value: Option<f64>,
810
811    // `AnimationLocalListenersMixin` and `AnimationLocalStatusListenersMixin`
812    // state. `AnimationEagerListenerMixin` declares none.
813    local_listeners: AnimationLocalListenersData,
814    local_status_listeners: AnimationLocalStatusListenersData,
815}
816
817impl TrainHoppingAnimation {
818    /// Creates a train-hopping animation.
819    ///
820    /// If the next train is `None`, then this object will just proxy the first
821    /// animation and never hop. Dart's constructor registers tear-offs of the
822    /// object under construction, so creation goes through the [`App`].
823    #[track_caller]
824    pub fn new(
825        app: &mut App,
826        current_train: AnimationRef<f64>,
827        next_train: Option<AnimationRef<f64>>,
828        on_switched_train: Option<Listener>,
829    ) -> Ref<TrainHoppingAnimation> {
830        let mut current_train = current_train;
831        let mut next_train = next_train;
832        let mut mode = None;
833        if let Some(next) = next_train.clone() {
834            if current_train.value(app) == next.value(app) {
835                current_train = next;
836                next_train = None;
837            } else if current_train.value(app) > next.value(app) {
838                mode = Some(TrainHoppingMode::Maximize);
839            } else {
840                debug_assert!(current_train.value(app) < next.value(app));
841                mode = Some(TrainHoppingMode::Minimize);
842            }
843        }
844        let this = app.create(TrainHoppingAnimation {
845            current_train: Some(current_train.clone()),
846            next_train: next_train.clone(),
847            mode,
848            on_switched_train,
849            last_status: None,
850            last_value: None,
851            local_listeners: AnimationLocalListenersData::new(),
852            local_status_listeners: AnimationLocalStatusListenersData::new(),
853        });
854        current_train.add_status_listener(
855            app,
856            AnimationStatusListener::handle_method(this.handle(), Self::status_change_handler),
857        );
858        current_train.add_listener(
859            app,
860            Listener::handle_method(this.handle(), Self::value_change_handler),
861        );
862        if let Some(next) = next_train {
863            next.add_listener(
864                app,
865                Listener::handle_method(this.handle(), Self::value_change_handler),
866            );
867        }
868        debug_assert!(app.get(&this).mode.is_some() || app.get(&this).next_train.is_none());
869        this
870    }
871
872    /// The animation that is currently driving this animation.
873    ///
874    /// The identity of this object will change from the first animation to the
875    /// second animation when [`on_switched_train`] is called.
876    ///
877    /// [`on_switched_train`]: TrainHoppingAnimation::on_switched_train
878    pub fn current_train(&self) -> Option<AnyAnimation<f64>> {
879        self.current_train.handle()
880    }
881
882    fn status_change_handler(self: Handle<Self>, app: &mut App, status: AnimationStatus) {
883        debug_assert!(app.get(self).current_train.is_some());
884        if Some(status) != app.get(self).last_status {
885            self.notify_status_listeners(app, status);
886            app.get_mut(self).last_status = Some(status);
887        }
888        debug_assert!(app.get(self).last_status.is_some());
889    }
890
891    fn value_change_handler(self: Handle<Self>, app: &mut App) {
892        debug_assert!(app.get(self).current_train.is_some());
893        let mut hop = false;
894        if app.get(self).next_train.is_some() {
895            debug_assert!(app.get(self).mode.is_some());
896            let animation = app.get(self);
897            let current = animation.current_train.handle().unwrap();
898            let next = animation.next_train.handle().unwrap();
899            hop = match animation.mode.unwrap() {
900                TrainHoppingMode::Minimize => next.value(app) <= current.value(app),
901                TrainHoppingMode::Maximize => next.value(app) >= current.value(app),
902            };
903            if hop {
904                current.remove_status_listener(
905                    app,
906                    &AnimationStatusListener::handle_method(self, Self::status_change_handler),
907                );
908                current.remove_listener(
909                    app,
910                    &Listener::handle_method(self, Self::value_change_handler),
911                );
912                let animation = app.get_mut(self);
913                // The old train goes when this local does, after its listeners are removed.
914                let _old_train =
915                    std::mem::replace(&mut animation.current_train, animation.next_train.take());
916                let new_current = app.get(self).current_train().unwrap();
917                new_current.add_status_listener(
918                    app,
919                    AnimationStatusListener::handle_method(self, Self::status_change_handler),
920                );
921                let status = new_current.status(app);
922                self.status_change_handler(app, status);
923            }
924        }
925        let new_value = self.value(app);
926        if Some(new_value) != app.get(self).last_value {
927            self.notify_listeners(app);
928            app.get_mut(self).last_value = Some(new_value);
929        }
930        debug_assert!(app.get(self).last_value.is_some());
931        if hop && let Some(on_switched_train) = app.get(self).on_switched_train.clone() {
932            on_switched_train.call(app);
933        }
934    }
935
936    /// Frees all the resources used by this performance.
937    /// After this is called, this object is no longer usable.
938    pub fn dispose(self: Handle<Self>, app: &mut App) {
939        debug_assert!(app.get(self).current_train.is_some());
940        let current = app
941            .get(self)
942            .current_train()
943            .expect("a disposed TrainHoppingAnimation has no current train");
944        current.remove_status_listener(
945            app,
946            &AnimationStatusListener::handle_method(self, Self::status_change_handler),
947        );
948        current.remove_listener(
949            app,
950            &Listener::handle_method(self, Self::value_change_handler),
951        );
952        let _current_train = app.get_mut(self).current_train.take();
953        if let Some(next) = app.get(self).next_train.handle() {
954            next.remove_listener(
955                app,
956                &Listener::handle_method(self, Self::value_change_handler),
957            );
958        }
959        let _next_train = app.get_mut(self).next_train.take();
960        self.clear_listeners(app);
961        self.clear_status_listeners(app);
962        AnimationEagerListenerMixin::dispose(self, app);
963    }
964}
965
966impl AnimationEagerListenerMixin for TrainHoppingAnimation {}
967
968impl AnimationLocalListenersMixin for TrainHoppingAnimation {
969    fn local_listeners_data(self: Handle<Self>, app: &App) -> &AnimationLocalListenersData {
970        &app.get(self).local_listeners
971    }
972
973    fn local_listeners_data_mut(
974        self: Handle<Self>,
975        app: &mut App,
976    ) -> &mut AnimationLocalListenersData {
977        &mut app.get_mut(self).local_listeners
978    }
979
980    // Dart resolves these by mixin order — `AnimationEagerListenerMixin` is
981    // the one that declares them in this class's `with` clause.
982    fn did_register_listener(self: Handle<Self>, app: &mut App) {
983        AnimationEagerListenerMixin::did_register_listener(self, app)
984    }
985
986    fn did_unregister_listener(self: Handle<Self>, app: &mut App) {
987        AnimationEagerListenerMixin::did_unregister_listener(self, app)
988    }
989}
990
991impl AnimationLocalStatusListenersMixin for TrainHoppingAnimation {
992    fn local_status_listeners_data(
993        self: Handle<Self>,
994        app: &App,
995    ) -> &AnimationLocalStatusListenersData {
996        &app.get(self).local_status_listeners
997    }
998
999    fn local_status_listeners_data_mut(
1000        self: Handle<Self>,
1001        app: &mut App,
1002    ) -> &mut AnimationLocalStatusListenersData {
1003        &mut app.get_mut(self).local_status_listeners
1004    }
1005
1006    fn did_register_listener(self: Handle<Self>, app: &mut App) {
1007        AnimationEagerListenerMixin::did_register_listener(self, app)
1008    }
1009
1010    fn did_unregister_listener(self: Handle<Self>, app: &mut App) {
1011        AnimationEagerListenerMixin::did_unregister_listener(self, app)
1012    }
1013}
1014
1015// Dart: `class TrainHoppingAnimation extends Animation<double> with
1016// AnimationEagerListenerMixin, AnimationLocalListenersMixin,
1017// AnimationLocalStatusListenersMixin`.
1018impl Animation<f64> for TrainHoppingAnimation {
1019    fn add_listener(self: Handle<Self>, app: &mut App, listener: Listener) {
1020        AnimationLocalListenersMixin::add_listener(self, app, listener)
1021    }
1022
1023    fn remove_listener(self: Handle<Self>, app: &mut App, listener: &Listener) {
1024        AnimationLocalListenersMixin::remove_listener(self, app, listener)
1025    }
1026
1027    fn add_status_listener(self: Handle<Self>, app: &mut App, listener: AnimationStatusListener) {
1028        AnimationLocalStatusListenersMixin::add_status_listener(self, app, listener)
1029    }
1030
1031    fn remove_status_listener(
1032        self: Handle<Self>,
1033        app: &mut App,
1034        listener: &AnimationStatusListener,
1035    ) {
1036        AnimationLocalStatusListenersMixin::remove_status_listener(self, app, listener)
1037    }
1038
1039    fn status(self: Handle<Self>, app: &App) -> AnimationStatus {
1040        app.get(self)
1041            .current_train()
1042            .expect("a disposed TrainHoppingAnimation has no current train")
1043            .status(app)
1044    }
1045
1046    fn value(self: Handle<Self>, app: &App) -> f64 {
1047        app.get(self)
1048            .current_train()
1049            .expect("a disposed TrainHoppingAnimation has no current train")
1050            .value(app)
1051    }
1052}
1053
1054/// An interface for combining multiple Animations. Implementors need only
1055/// implement [`Animation::value`] to control how the child animations are
1056/// combined. Can be chained to combine more than 2 animations.
1057///
1058/// For example, to create an animation that is the sum of two others,
1059/// implement this trait and define `value` as `first.value + next.value`.
1060///
1061/// By default, the status of a compound animation is the status of the
1062/// [`next`] animation if [`next`] is moving, and the status of the [`first`]
1063/// animation otherwise.
1064///
1065/// Dart's `CompoundAnimation<T>` is an abstract class whose handlers call the
1066/// subclass's `value` override. The upward call is what makes it a trait here;
1067/// it reaches the override through [`as_animation`], the erased handle, whose
1068/// vtable is built from the subclass's [`Animation`] impl. The fields Dart
1069/// declares on the abstract class belong to the implementing type and reach
1070/// the trait through the app-mediated accessors.
1071///
1072/// [`as_animation`]: Animation::as_animation
1073/// [`first`]: CompoundAnimation::first
1074/// [`next`]: CompoundAnimation::next
1075pub trait CompoundAnimation<T: Clone + PartialEq + 'static>:
1076    Animation<T>
1077    + AnimationLazyListenerMixin
1078    + AnimationLocalListenersMixin
1079    + AnimationLocalStatusListenersMixin
1080{
1081    /// The first sub-animation. Its status takes precedence if neither are
1082    /// animating.
1083    fn first(self: Handle<Self>, app: &App) -> AnyAnimation<T>;
1084
1085    /// The second sub-animation.
1086    fn next(self: Handle<Self>, app: &App) -> AnyAnimation<T>;
1087
1088    /// Dart's `_lastStatus`, owned by the implementing type.
1089    fn last_status(self: Handle<Self>, app: &App) -> Option<AnimationStatus>;
1090
1091    /// Dart's `_lastStatus`, mutably.
1092    fn last_status_mut(self: Handle<Self>, app: &mut App) -> &mut Option<AnimationStatus>;
1093
1094    /// Dart's `_lastValue`, owned by the implementing type.
1095    fn last_value(self: Handle<Self>, app: &App) -> &Option<T>;
1096
1097    /// Dart's `_lastValue`, mutably.
1098    fn last_value_mut(self: Handle<Self>, app: &mut App) -> &mut Option<T>;
1099
1100    /// Gets the status of this animation based on the [`first`] and [`next`]
1101    /// status.
1102    ///
1103    /// The default is that if the [`next`] animation is moving, use its
1104    /// status. Otherwise, default to [`first`].
1105    ///
1106    /// [`first`]: CompoundAnimation::first
1107    /// [`next`]: CompoundAnimation::next
1108    fn status(self: Handle<Self>, app: &App) -> AnimationStatus {
1109        let next_status = self.next(app).status(app);
1110        if next_status.is_animating() {
1111            next_status
1112        } else {
1113            self.first(app).status(app)
1114        }
1115    }
1116
1117    /// Dart's `_maybeNotifyStatusListeners`.
1118    fn maybe_notify_status_listeners(self: Handle<Self>, app: &mut App, _status: AnimationStatus) {
1119        let status = self.as_animation().status(app);
1120        if Some(status) != self.last_status(app) {
1121            *self.last_status_mut(app) = Some(status);
1122            self.notify_status_listeners(app, status);
1123        }
1124    }
1125
1126    /// Dart's `_maybeNotifyListeners`.
1127    fn maybe_notify_listeners(self: Handle<Self>, app: &mut App) {
1128        let value = self.as_animation().value(app);
1129        if self.last_value(app).as_ref() != Some(&value) {
1130            *self.last_value_mut(app) = Some(value);
1131            self.notify_listeners(app);
1132        }
1133    }
1134}
1135
1136/// Dart's `CompoundAnimation.didStartListening`: subscribes to both
1137/// sub-animations.
1138///
1139/// A free function rather than a provided method on [`CompoundAnimation`]
1140/// because the method it implements belongs to the
1141/// [`AnimationLazyListenerMixin`] supertrait: a provided method of the same
1142/// name here would make every `did_start_listening` call ambiguous. Each
1143/// implementor's [`AnimationLazyListenerMixin::did_start_listening`] delegates
1144/// here, exactly as it would to a trait default; public because Dart's
1145/// `CompoundAnimation` is subclassed outside the animation library.
1146pub fn compound_did_start_listening<S, T>(this: Handle<S>, app: &mut App)
1147where
1148    S: CompoundAnimation<T>,
1149    T: Clone + PartialEq + 'static,
1150{
1151    let (first, next) = (this.first(app), this.next(app));
1152    first.add_listener(
1153        app,
1154        Listener::handle_method(this, <S as CompoundAnimation<T>>::maybe_notify_listeners),
1155    );
1156    first.add_status_listener(
1157        app,
1158        AnimationStatusListener::handle_method(
1159            this,
1160            <S as CompoundAnimation<T>>::maybe_notify_status_listeners,
1161        ),
1162    );
1163    next.add_listener(
1164        app,
1165        Listener::handle_method(this, <S as CompoundAnimation<T>>::maybe_notify_listeners),
1166    );
1167    next.add_status_listener(
1168        app,
1169        AnimationStatusListener::handle_method(
1170            this,
1171            <S as CompoundAnimation<T>>::maybe_notify_status_listeners,
1172        ),
1173    );
1174}
1175
1176/// Dart's `CompoundAnimation.didStopListening`: unsubscribes from both
1177/// sub-animations. Free for the reason on
1178/// [`compound_did_start_listening`]; the tear-offs it rebuilds are the same
1179/// fn items registered there, so they match.
1180pub fn compound_did_stop_listening<S, T>(this: Handle<S>, app: &mut App)
1181where
1182    S: CompoundAnimation<T>,
1183    T: Clone + PartialEq + 'static,
1184{
1185    let (first, next) = (this.first(app), this.next(app));
1186    first.remove_listener(
1187        app,
1188        &Listener::handle_method(this, <S as CompoundAnimation<T>>::maybe_notify_listeners),
1189    );
1190    first.remove_status_listener(
1191        app,
1192        &AnimationStatusListener::handle_method(
1193            this,
1194            <S as CompoundAnimation<T>>::maybe_notify_status_listeners,
1195        ),
1196    );
1197    next.remove_listener(
1198        app,
1199        &Listener::handle_method(this, <S as CompoundAnimation<T>>::maybe_notify_listeners),
1200    );
1201    next.remove_status_listener(
1202        app,
1203        &AnimationStatusListener::handle_method(
1204            this,
1205            <S as CompoundAnimation<T>>::maybe_notify_status_listeners,
1206        ),
1207    );
1208}
1209
1210/// An animation of [`f64`]s that tracks the mean of two other animations.
1211///
1212/// The status of this animation is the status of the `right` animation if it
1213/// is moving, and the `left` animation otherwise.
1214///
1215/// The value of this animation is the [`f64`] that represents the mean value
1216/// of the values of the `left` and `right` animations.
1217pub struct AnimationMean {
1218    first: AnimationRef<f64>,
1219    next: AnimationRef<f64>,
1220    last_status: Option<AnimationStatus>,
1221    last_value: Option<f64>,
1222    lazy_listener: AnimationLazyListenerData,
1223    local_listeners: AnimationLocalListenersData,
1224    local_status_listeners: AnimationLocalStatusListenersData,
1225}
1226
1227impl AnimationMean {
1228    /// Creates an animation that tracks the mean of two other animations, which it keeps.
1229    #[track_caller]
1230    pub fn new(
1231        app: &mut App,
1232        left: AnimationRef<f64>,
1233        right: AnimationRef<f64>,
1234    ) -> Ref<AnimationMean> {
1235        app.create(AnimationMean {
1236            first: left,
1237            next: right,
1238            last_status: None,
1239            last_value: None,
1240            lazy_listener: AnimationLazyListenerData::new(),
1241            local_listeners: AnimationLocalListenersData::new(),
1242            local_status_listeners: AnimationLocalStatusListenersData::new(),
1243        })
1244    }
1245}
1246
1247impl AnimationLazyListenerMixin for AnimationMean {
1248    fn lazy_listener_data(self: Handle<Self>, app: &App) -> &AnimationLazyListenerData {
1249        &app.get(self).lazy_listener
1250    }
1251
1252    fn lazy_listener_data_mut(self: Handle<Self>, app: &mut App) -> &mut AnimationLazyListenerData {
1253        &mut app.get_mut(self).lazy_listener
1254    }
1255
1256    fn did_start_listening(self: Handle<Self>, app: &mut App) {
1257        compound_did_start_listening::<AnimationMean, f64>(self, app)
1258    }
1259
1260    fn did_stop_listening(self: Handle<Self>, app: &mut App) {
1261        compound_did_stop_listening::<AnimationMean, f64>(self, app)
1262    }
1263}
1264
1265impl AnimationLocalListenersMixin for AnimationMean {
1266    fn local_listeners_data(self: Handle<Self>, app: &App) -> &AnimationLocalListenersData {
1267        &app.get(self).local_listeners
1268    }
1269
1270    fn local_listeners_data_mut(
1271        self: Handle<Self>,
1272        app: &mut App,
1273    ) -> &mut AnimationLocalListenersData {
1274        &mut app.get_mut(self).local_listeners
1275    }
1276
1277    fn did_register_listener(self: Handle<Self>, app: &mut App) {
1278        AnimationLazyListenerMixin::did_register_listener(self, app)
1279    }
1280
1281    fn did_unregister_listener(self: Handle<Self>, app: &mut App) {
1282        AnimationLazyListenerMixin::did_unregister_listener(self, app)
1283    }
1284}
1285
1286impl AnimationLocalStatusListenersMixin for AnimationMean {
1287    fn local_status_listeners_data(
1288        self: Handle<Self>,
1289        app: &App,
1290    ) -> &AnimationLocalStatusListenersData {
1291        &app.get(self).local_status_listeners
1292    }
1293
1294    fn local_status_listeners_data_mut(
1295        self: Handle<Self>,
1296        app: &mut App,
1297    ) -> &mut AnimationLocalStatusListenersData {
1298        &mut app.get_mut(self).local_status_listeners
1299    }
1300
1301    fn did_register_listener(self: Handle<Self>, app: &mut App) {
1302        AnimationLazyListenerMixin::did_register_listener(self, app)
1303    }
1304
1305    fn did_unregister_listener(self: Handle<Self>, app: &mut App) {
1306        AnimationLazyListenerMixin::did_unregister_listener(self, app)
1307    }
1308}
1309
1310impl CompoundAnimation<f64> for AnimationMean {
1311    fn first(self: Handle<Self>, app: &App) -> AnyAnimation<f64> {
1312        app.get(self).first.handle()
1313    }
1314
1315    fn next(self: Handle<Self>, app: &App) -> AnyAnimation<f64> {
1316        app.get(self).next.handle()
1317    }
1318
1319    fn last_status(self: Handle<Self>, app: &App) -> Option<AnimationStatus> {
1320        app.get(self).last_status
1321    }
1322
1323    fn last_status_mut(self: Handle<Self>, app: &mut App) -> &mut Option<AnimationStatus> {
1324        &mut app.get_mut(self).last_status
1325    }
1326
1327    fn last_value(self: Handle<Self>, app: &App) -> &Option<f64> {
1328        &app.get(self).last_value
1329    }
1330
1331    fn last_value_mut(self: Handle<Self>, app: &mut App) -> &mut Option<f64> {
1332        &mut app.get_mut(self).last_value
1333    }
1334}
1335
1336// Dart: `class AnimationMean extends CompoundAnimation<double>`.
1337impl Animation<f64> for AnimationMean {
1338    fn add_listener(self: Handle<Self>, app: &mut App, listener: Listener) {
1339        AnimationLocalListenersMixin::add_listener(self, app, listener)
1340    }
1341
1342    fn remove_listener(self: Handle<Self>, app: &mut App, listener: &Listener) {
1343        AnimationLocalListenersMixin::remove_listener(self, app, listener)
1344    }
1345
1346    fn add_status_listener(self: Handle<Self>, app: &mut App, listener: AnimationStatusListener) {
1347        AnimationLocalStatusListenersMixin::add_status_listener(self, app, listener)
1348    }
1349
1350    fn remove_status_listener(
1351        self: Handle<Self>,
1352        app: &mut App,
1353        listener: &AnimationStatusListener,
1354    ) {
1355        AnimationLocalStatusListenersMixin::remove_status_listener(self, app, listener)
1356    }
1357
1358    fn status(self: Handle<Self>, app: &App) -> AnimationStatus {
1359        CompoundAnimation::status(self, app)
1360    }
1361
1362    fn value(self: Handle<Self>, app: &App) -> f64 {
1363        let animation = app.get(self);
1364        (animation.first.value(app) + animation.next.value(app)) / 2.0
1365    }
1366}
1367
1368/// `dart:math`'s `max` for doubles, written from its documented contract — the
1369/// Dart SDK source is not in the Flutter checkout. NaN propagates, and `0.0`
1370/// is the larger of the two zeros.
1371fn dart_max(a: f64, b: f64) -> f64 {
1372    if a > b {
1373        return a;
1374    }
1375    if b > a {
1376        return b;
1377    }
1378    if a.is_nan() {
1379        return a;
1380    }
1381    if b.is_nan() {
1382        return b;
1383    }
1384    if a.is_sign_positive() { a } else { b }
1385}
1386
1387/// `dart:math`'s `min` for doubles, from its documented contract. NaN
1388/// propagates, and `-0.0` is the smaller of the two zeros.
1389fn dart_min(a: f64, b: f64) -> f64 {
1390    if a < b {
1391        return a;
1392    }
1393    if b < a {
1394        return b;
1395    }
1396    if a.is_nan() {
1397        return a;
1398    }
1399    if b.is_nan() {
1400        return b;
1401    }
1402    if a.is_sign_negative() { a } else { b }
1403}
1404
1405/// An animation that tracks the maximum of two other animations.
1406///
1407/// The value of this animation is the maximum of the values of
1408/// [`first`](CompoundAnimation::first) and [`next`](CompoundAnimation::next).
1409///
1410/// Dart's `AnimationMax<T extends num>` is generic over `int` and `double`;
1411/// Rust has no `num` supertype, so this is `f64`-only until a non-double use
1412/// appears.
1413pub struct AnimationMax {
1414    first: AnimationRef<f64>,
1415    next: AnimationRef<f64>,
1416    last_status: Option<AnimationStatus>,
1417    last_value: Option<f64>,
1418    lazy_listener: AnimationLazyListenerData,
1419    local_listeners: AnimationLocalListenersData,
1420    local_status_listeners: AnimationLocalStatusListenersData,
1421}
1422
1423impl AnimationMax {
1424    /// Creates an [`AnimationMax`].
1425    ///
1426    /// Either argument can be an [`AnimationMax`] itself to combine multiple
1427    /// animations.
1428    #[track_caller]
1429    pub fn new(
1430        app: &mut App,
1431        first: AnimationRef<f64>,
1432        next: AnimationRef<f64>,
1433    ) -> Ref<AnimationMax> {
1434        app.create(AnimationMax {
1435            first,
1436            next,
1437            last_status: None,
1438            last_value: None,
1439            lazy_listener: AnimationLazyListenerData::new(),
1440            local_listeners: AnimationLocalListenersData::new(),
1441            local_status_listeners: AnimationLocalStatusListenersData::new(),
1442        })
1443    }
1444}
1445
1446impl AnimationLazyListenerMixin for AnimationMax {
1447    fn lazy_listener_data(self: Handle<Self>, app: &App) -> &AnimationLazyListenerData {
1448        &app.get(self).lazy_listener
1449    }
1450
1451    fn lazy_listener_data_mut(self: Handle<Self>, app: &mut App) -> &mut AnimationLazyListenerData {
1452        &mut app.get_mut(self).lazy_listener
1453    }
1454
1455    fn did_start_listening(self: Handle<Self>, app: &mut App) {
1456        compound_did_start_listening::<AnimationMax, f64>(self, app)
1457    }
1458
1459    fn did_stop_listening(self: Handle<Self>, app: &mut App) {
1460        compound_did_stop_listening::<AnimationMax, f64>(self, app)
1461    }
1462}
1463
1464impl AnimationLocalListenersMixin for AnimationMax {
1465    fn local_listeners_data(self: Handle<Self>, app: &App) -> &AnimationLocalListenersData {
1466        &app.get(self).local_listeners
1467    }
1468
1469    fn local_listeners_data_mut(
1470        self: Handle<Self>,
1471        app: &mut App,
1472    ) -> &mut AnimationLocalListenersData {
1473        &mut app.get_mut(self).local_listeners
1474    }
1475
1476    fn did_register_listener(self: Handle<Self>, app: &mut App) {
1477        AnimationLazyListenerMixin::did_register_listener(self, app)
1478    }
1479
1480    fn did_unregister_listener(self: Handle<Self>, app: &mut App) {
1481        AnimationLazyListenerMixin::did_unregister_listener(self, app)
1482    }
1483}
1484
1485impl AnimationLocalStatusListenersMixin for AnimationMax {
1486    fn local_status_listeners_data(
1487        self: Handle<Self>,
1488        app: &App,
1489    ) -> &AnimationLocalStatusListenersData {
1490        &app.get(self).local_status_listeners
1491    }
1492
1493    fn local_status_listeners_data_mut(
1494        self: Handle<Self>,
1495        app: &mut App,
1496    ) -> &mut AnimationLocalStatusListenersData {
1497        &mut app.get_mut(self).local_status_listeners
1498    }
1499
1500    fn did_register_listener(self: Handle<Self>, app: &mut App) {
1501        AnimationLazyListenerMixin::did_register_listener(self, app)
1502    }
1503
1504    fn did_unregister_listener(self: Handle<Self>, app: &mut App) {
1505        AnimationLazyListenerMixin::did_unregister_listener(self, app)
1506    }
1507}
1508
1509impl CompoundAnimation<f64> for AnimationMax {
1510    fn first(self: Handle<Self>, app: &App) -> AnyAnimation<f64> {
1511        app.get(self).first.handle()
1512    }
1513
1514    fn next(self: Handle<Self>, app: &App) -> AnyAnimation<f64> {
1515        app.get(self).next.handle()
1516    }
1517
1518    fn last_status(self: Handle<Self>, app: &App) -> Option<AnimationStatus> {
1519        app.get(self).last_status
1520    }
1521
1522    fn last_status_mut(self: Handle<Self>, app: &mut App) -> &mut Option<AnimationStatus> {
1523        &mut app.get_mut(self).last_status
1524    }
1525
1526    fn last_value(self: Handle<Self>, app: &App) -> &Option<f64> {
1527        &app.get(self).last_value
1528    }
1529
1530    fn last_value_mut(self: Handle<Self>, app: &mut App) -> &mut Option<f64> {
1531        &mut app.get_mut(self).last_value
1532    }
1533}
1534
1535// Dart: `class AnimationMax<T extends num> extends CompoundAnimation<T>`.
1536impl Animation<f64> for AnimationMax {
1537    fn add_listener(self: Handle<Self>, app: &mut App, listener: Listener) {
1538        AnimationLocalListenersMixin::add_listener(self, app, listener)
1539    }
1540
1541    fn remove_listener(self: Handle<Self>, app: &mut App, listener: &Listener) {
1542        AnimationLocalListenersMixin::remove_listener(self, app, listener)
1543    }
1544
1545    fn add_status_listener(self: Handle<Self>, app: &mut App, listener: AnimationStatusListener) {
1546        AnimationLocalStatusListenersMixin::add_status_listener(self, app, listener)
1547    }
1548
1549    fn remove_status_listener(
1550        self: Handle<Self>,
1551        app: &mut App,
1552        listener: &AnimationStatusListener,
1553    ) {
1554        AnimationLocalStatusListenersMixin::remove_status_listener(self, app, listener)
1555    }
1556
1557    fn status(self: Handle<Self>, app: &App) -> AnimationStatus {
1558        CompoundAnimation::status(self, app)
1559    }
1560
1561    fn value(self: Handle<Self>, app: &App) -> f64 {
1562        let animation = app.get(self);
1563        dart_max(animation.first.value(app), animation.next.value(app))
1564    }
1565}
1566
1567/// An animation that tracks the minimum of two other animations.
1568///
1569/// The value of this animation is the minimum of the values of
1570/// [`first`](CompoundAnimation::first) and [`next`](CompoundAnimation::next).
1571///
1572/// Dart's `AnimationMin<T extends num>` is generic over `int` and `double`;
1573/// Rust has no `num` supertype, so this is `f64`-only until a non-double use
1574/// appears.
1575pub struct AnimationMin {
1576    first: AnimationRef<f64>,
1577    next: AnimationRef<f64>,
1578    last_status: Option<AnimationStatus>,
1579    last_value: Option<f64>,
1580    lazy_listener: AnimationLazyListenerData,
1581    local_listeners: AnimationLocalListenersData,
1582    local_status_listeners: AnimationLocalStatusListenersData,
1583}
1584
1585impl AnimationMin {
1586    /// Creates an [`AnimationMin`].
1587    ///
1588    /// Either argument can be an [`AnimationMin`] itself to combine multiple
1589    /// animations.
1590    #[track_caller]
1591    pub fn new(
1592        app: &mut App,
1593        first: AnimationRef<f64>,
1594        next: AnimationRef<f64>,
1595    ) -> Ref<AnimationMin> {
1596        app.create(AnimationMin {
1597            first,
1598            next,
1599            last_status: None,
1600            last_value: None,
1601            lazy_listener: AnimationLazyListenerData::new(),
1602            local_listeners: AnimationLocalListenersData::new(),
1603            local_status_listeners: AnimationLocalStatusListenersData::new(),
1604        })
1605    }
1606}
1607
1608impl AnimationLazyListenerMixin for AnimationMin {
1609    fn lazy_listener_data(self: Handle<Self>, app: &App) -> &AnimationLazyListenerData {
1610        &app.get(self).lazy_listener
1611    }
1612
1613    fn lazy_listener_data_mut(self: Handle<Self>, app: &mut App) -> &mut AnimationLazyListenerData {
1614        &mut app.get_mut(self).lazy_listener
1615    }
1616
1617    fn did_start_listening(self: Handle<Self>, app: &mut App) {
1618        compound_did_start_listening::<AnimationMin, f64>(self, app)
1619    }
1620
1621    fn did_stop_listening(self: Handle<Self>, app: &mut App) {
1622        compound_did_stop_listening::<AnimationMin, f64>(self, app)
1623    }
1624}
1625
1626impl AnimationLocalListenersMixin for AnimationMin {
1627    fn local_listeners_data(self: Handle<Self>, app: &App) -> &AnimationLocalListenersData {
1628        &app.get(self).local_listeners
1629    }
1630
1631    fn local_listeners_data_mut(
1632        self: Handle<Self>,
1633        app: &mut App,
1634    ) -> &mut AnimationLocalListenersData {
1635        &mut app.get_mut(self).local_listeners
1636    }
1637
1638    fn did_register_listener(self: Handle<Self>, app: &mut App) {
1639        AnimationLazyListenerMixin::did_register_listener(self, app)
1640    }
1641
1642    fn did_unregister_listener(self: Handle<Self>, app: &mut App) {
1643        AnimationLazyListenerMixin::did_unregister_listener(self, app)
1644    }
1645}
1646
1647impl AnimationLocalStatusListenersMixin for AnimationMin {
1648    fn local_status_listeners_data(
1649        self: Handle<Self>,
1650        app: &App,
1651    ) -> &AnimationLocalStatusListenersData {
1652        &app.get(self).local_status_listeners
1653    }
1654
1655    fn local_status_listeners_data_mut(
1656        self: Handle<Self>,
1657        app: &mut App,
1658    ) -> &mut AnimationLocalStatusListenersData {
1659        &mut app.get_mut(self).local_status_listeners
1660    }
1661
1662    fn did_register_listener(self: Handle<Self>, app: &mut App) {
1663        AnimationLazyListenerMixin::did_register_listener(self, app)
1664    }
1665
1666    fn did_unregister_listener(self: Handle<Self>, app: &mut App) {
1667        AnimationLazyListenerMixin::did_unregister_listener(self, app)
1668    }
1669}
1670
1671impl CompoundAnimation<f64> for AnimationMin {
1672    fn first(self: Handle<Self>, app: &App) -> AnyAnimation<f64> {
1673        app.get(self).first.handle()
1674    }
1675
1676    fn next(self: Handle<Self>, app: &App) -> AnyAnimation<f64> {
1677        app.get(self).next.handle()
1678    }
1679
1680    fn last_status(self: Handle<Self>, app: &App) -> Option<AnimationStatus> {
1681        app.get(self).last_status
1682    }
1683
1684    fn last_status_mut(self: Handle<Self>, app: &mut App) -> &mut Option<AnimationStatus> {
1685        &mut app.get_mut(self).last_status
1686    }
1687
1688    fn last_value(self: Handle<Self>, app: &App) -> &Option<f64> {
1689        &app.get(self).last_value
1690    }
1691
1692    fn last_value_mut(self: Handle<Self>, app: &mut App) -> &mut Option<f64> {
1693        &mut app.get_mut(self).last_value
1694    }
1695}
1696
1697// Dart: `class AnimationMin<T extends num> extends CompoundAnimation<T>`.
1698impl Animation<f64> for AnimationMin {
1699    fn add_listener(self: Handle<Self>, app: &mut App, listener: Listener) {
1700        AnimationLocalListenersMixin::add_listener(self, app, listener)
1701    }
1702
1703    fn remove_listener(self: Handle<Self>, app: &mut App, listener: &Listener) {
1704        AnimationLocalListenersMixin::remove_listener(self, app, listener)
1705    }
1706
1707    fn add_status_listener(self: Handle<Self>, app: &mut App, listener: AnimationStatusListener) {
1708        AnimationLocalStatusListenersMixin::add_status_listener(self, app, listener)
1709    }
1710
1711    fn remove_status_listener(
1712        self: Handle<Self>,
1713        app: &mut App,
1714        listener: &AnimationStatusListener,
1715    ) {
1716        AnimationLocalStatusListenersMixin::remove_status_listener(self, app, listener)
1717    }
1718
1719    fn status(self: Handle<Self>, app: &App) -> AnimationStatus {
1720        CompoundAnimation::status(self, app)
1721    }
1722
1723    fn value(self: Handle<Self>, app: &App) -> f64 {
1724        let animation = app.get(self);
1725        dart_min(animation.first.value(app), animation.next.value(app))
1726    }
1727}
1728
1729#[cfg(test)]
1730mod tests {
1731    use std::cell::{Cell, RefCell};
1732    use std::rc::Rc;
1733    use waft_foundation::AppCell;
1734
1735    use super::*;
1736    use crate::curves::Curves;
1737
1738    /// Dart's final parent references outlive dispose until the driven animation is dropped.
1739    #[test]
1740    fn driven_animation_keeps_disposed_curve_and_its_parent() {
1741        use crate::tween::Animatable;
1742
1743        let cell = AppCell::new();
1744        let mut app = cell.borrow_mut();
1745        let parent_ref = app.create(AlwaysStoppedAnimation::new(0.5));
1746        let parent = parent_ref.handle();
1747        let curve_ref =
1748            CurvedAnimation::new(&mut app, parent_ref.into_erased(), Curves::linear(), None);
1749        let curve = curve_ref.handle();
1750        let driven = crate::tween::CallbackAnimatable::from_callback(|value| value * 10.0)
1751            .animate(&mut app, curve_ref.into_erased());
1752        let listener = Listener::new(|_| {});
1753        driven.add_listener(&mut app, listener.clone());
1754        curve.dispose(&mut app);
1755        drop(app);
1756        cell.checkpoint();
1757        let mut app = cell.borrow_mut();
1758        assert_eq!(driven.value(&app), 5.0);
1759        driven.remove_listener(&mut app, &listener);
1760        assert!(app.contains(curve));
1761        assert!(app.contains(parent));
1762        drop(driven);
1763        drop(app);
1764        cell.checkpoint();
1765        let app = cell.borrow();
1766        assert!(!app.contains(curve));
1767        assert!(!app.contains(parent));
1768    }
1769
1770    #[test]
1771    fn the_constant_animations_report_flutters_values() {
1772        let cell = AppCell::new();
1773        let mut app = cell.borrow_mut();
1774
1775        let complete = k_always_complete_animation(&mut app);
1776        assert_eq!(complete.value(&app), 1.0);
1777        assert_eq!(complete.status(&app), AnimationStatus::Completed);
1778        assert!(complete.is_completed(&app));
1779
1780        let dismissed = k_always_dismissed_animation(&mut app);
1781        assert_eq!(dismissed.value(&app), 0.0);
1782        assert_eq!(dismissed.status(&app), AnimationStatus::Dismissed);
1783        assert!(dismissed.is_dismissed(&app));
1784
1785        // Dart's overrides are empty bodies: registration is ignored, so
1786        // removal of something never added is also fine.
1787        complete.add_listener(&mut app, Listener::new(|_app| {}));
1788        complete.remove_listener(&mut app, &Listener::new(|_app| {}));
1789    }
1790
1791    #[test]
1792    fn every_mention_of_a_constant_animation_is_one_identity() {
1793        let cell = AppCell::new();
1794        let mut app = cell.borrow_mut();
1795        let first = k_always_complete_animation(&mut app);
1796
1797        // Dart's `const` canonicalization, reproduced per App by the
1798        // singleton: comparisons like ProxyAnimation's early return answer
1799        // "unchanged", as Flutter's do.
1800        assert_eq!(first, k_always_complete_animation(&mut app));
1801        assert_ne!(first, k_always_dismissed_animation(&mut app));
1802    }
1803
1804    #[test]
1805    fn an_always_stopped_animation_is_forward_at_its_value() {
1806        let cell = AppCell::new();
1807        let mut app = cell.borrow_mut();
1808        let half: AnimationRef<f64> = app.create(AlwaysStoppedAnimation::new(0.5)).into_erased();
1809
1810        assert_eq!(half.value(&app), 0.5);
1811        assert_eq!(half.status(&app), AnimationStatus::Forward);
1812    }
1813
1814    // animations_test.dart:51 — 'ProxyAnimation.toString control test', the
1815    // value/status half. `toString` is not ported.
1816    #[test]
1817    fn a_parentless_proxy_is_dismissed_at_zero() {
1818        let cell = AppCell::new();
1819        let mut app = cell.borrow_mut();
1820        let animation: AnimationRef<f64> = ProxyAnimation::new(&mut app, None).into_erased();
1821
1822        assert_eq!(animation.value(&app), 0.0);
1823        assert_eq!(animation.status(&app), AnimationStatus::Dismissed);
1824    }
1825
1826    // animations_test.dart:60 — 'ProxyAnimation set parent generates value
1827    // changed'. The Dart test drives the second notification through an
1828    // AnimationController, which is not ported; here a chained inner proxy
1829    // takes that role, which also exercises the tear-off subscription.
1830    #[test]
1831    fn set_parent_generates_value_changed() {
1832        let cell = AppCell::new();
1833        let mut app = cell.borrow_mut();
1834        let half: AnimationRef<f64> = app.create(AlwaysStoppedAnimation::new(0.5)).into_erased();
1835        let did_receive_callback = Rc::new(Cell::new(false));
1836
1837        let animation = ProxyAnimation::new(&mut app, None);
1838        animation.as_animation().add_listener(
1839            &mut app,
1840            Listener::new({
1841                let did_receive_callback = Rc::clone(&did_receive_callback);
1842                move |_app| did_receive_callback.set(true)
1843            }),
1844        );
1845
1846        assert!(!did_receive_callback.get());
1847        animation.set_parent(&mut app, Some(half));
1848        assert!(did_receive_callback.get());
1849        did_receive_callback.set(false);
1850    }
1851
1852    #[test]
1853    fn a_proxy_follows_its_parent_through_the_subscription() {
1854        let cell = AppCell::new();
1855        let mut app = cell.borrow_mut();
1856        let inner = ProxyAnimation::new(&mut app, None);
1857        let outer = ProxyAnimation::new(&mut app, Some(inner.erase()));
1858
1859        let notified = Rc::new(Cell::new(0));
1860        outer.as_animation().add_listener(
1861            &mut app,
1862            Listener::new({
1863                let notified = Rc::clone(&notified);
1864                move |_app| notified.set(notified.get() + 1)
1865            }),
1866        );
1867
1868        // The inner proxy's own notification reaches the outer proxy's
1869        // listener through the tear-off the outer registered on it.
1870        let target: AnimationRef<f64> = app.create(AlwaysStoppedAnimation::new(0.6)).into_erased();
1871        inner.set_parent(&mut app, Some(target));
1872
1873        assert_eq!(notified.get(), 1);
1874        assert_eq!(outer.as_animation().value(&app), 0.6);
1875    }
1876
1877    #[test]
1878    fn removing_the_last_listener_unsubscribes_from_the_parent() {
1879        let cell = AppCell::new();
1880        let mut app = cell.borrow_mut();
1881        let inner = ProxyAnimation::new(&mut app, None);
1882        let outer = ProxyAnimation::new(&mut app, Some(inner.erase()));
1883
1884        let listener = Listener::new(|_app| {});
1885        outer
1886            .as_animation()
1887            .add_listener(&mut app, listener.clone());
1888        assert!(
1889            !inner.local_listeners_data(&app).is_empty(),
1890            "the outer proxy's tear-off is registered on the inner"
1891        );
1892        assert!(!inner.local_status_listeners_data(&app).is_empty());
1893
1894        outer.as_animation().remove_listener(&mut app, &listener);
1895        assert!(
1896            inner.local_listeners_data(&app).is_empty(),
1897            "the rebuilt tear-off matched, so the registration is gone"
1898        );
1899        assert!(inner.local_status_listeners_data(&app).is_empty());
1900    }
1901
1902    #[test]
1903    fn set_parent_notifies_the_status_change() {
1904        let cell = AppCell::new();
1905        let mut app = cell.borrow_mut();
1906        let statuses = Rc::new(RefCell::new(Vec::new()));
1907
1908        let animation = ProxyAnimation::new(&mut app, None); // Dismissed
1909        animation.as_animation().add_status_listener(
1910            &mut app,
1911            AnimationStatusListener::new({
1912                let statuses = Rc::clone(&statuses);
1913                move |status, _app| statuses.borrow_mut().push(status)
1914            }),
1915        );
1916
1917        let complete = k_always_complete_animation(&mut app);
1918        animation.set_parent(&mut app, Some(complete));
1919
1920        assert_eq!(*statuses.borrow(), vec![AnimationStatus::Completed]);
1921    }
1922
1923    #[test]
1924    fn a_listener_can_reach_its_own_animation_while_it_notifies() {
1925        let cell = AppCell::new();
1926        let mut app = cell.borrow_mut();
1927        let animation = ProxyAnimation::new(&mut app, None);
1928        let animation_handle = animation.as_animation();
1929
1930        let observed = Rc::new(Cell::new(f64::NAN));
1931        animation.as_animation().add_listener(
1932            &mut app,
1933            Listener::new({
1934                let observed = Rc::clone(&observed);
1935                move |app: &mut App| {
1936                    // Mid-notification, from inside set_parent: the parent is
1937                    // already assigned, so the value reads through it — as in
1938                    // Dart, where the setter notifies after `_parent = value`.
1939                    observed.set(animation_handle.value(app));
1940                }
1941            }),
1942        );
1943
1944        let half: AnimationRef<f64> = app.create(AlwaysStoppedAnimation::new(0.5)).into_erased();
1945        animation.set_parent(&mut app, Some(half));
1946        assert_eq!(observed.get(), 0.5);
1947    }
1948
1949    #[test]
1950    fn setting_the_same_parent_is_a_no_op() {
1951        let cell = AppCell::new();
1952        let mut app = cell.borrow_mut();
1953        let half: AnimationRef<f64> = app.create(AlwaysStoppedAnimation::new(0.5)).into_erased();
1954        let animation = ProxyAnimation::new(&mut app, Some(half.clone()));
1955
1956        let notified = Rc::new(Cell::new(0));
1957        animation.as_animation().add_listener(
1958            &mut app,
1959            Listener::new({
1960                let notified = Rc::clone(&notified);
1961                move |_app| notified.set(notified.get() + 1)
1962            }),
1963        );
1964
1965        animation.set_parent(&mut app, Some(half));
1966        assert_eq!(notified.get(), 0, "Dart returns before the swap");
1967    }
1968
1969    #[test]
1970    fn a_reverse_animation_flips_value_and_status() {
1971        let cell = AppCell::new();
1972        let mut app = cell.borrow_mut();
1973        let stopped: AnimationRef<f64> =
1974            app.create(AlwaysStoppedAnimation::new(0.25)).into_erased();
1975        let reverse: AnimationRef<f64> = ReverseAnimation::new(&mut app, stopped).into_erased();
1976
1977        assert_eq!(reverse.value(&app), 0.75);
1978        assert_eq!(reverse.status(&app), AnimationStatus::Reverse);
1979    }
1980
1981    // animations_test.dart:77 — 'ReverseAnimation calls listeners': the value
1982    // listener is forwarded to the parent, and removal stops the calls. A
1983    // ProxyAnimation drives in place of the unported controller.
1984    #[test]
1985    fn reverse_animation_calls_listeners() {
1986        let cell = AppCell::new();
1987        let mut app = cell.borrow_mut();
1988        let driver = ProxyAnimation::new(&mut app, None);
1989        let animation = ReverseAnimation::new(&mut app, driver.erase());
1990
1991        let did_receive_callback = Rc::new(Cell::new(false));
1992        let listener = Listener::new({
1993            let did_receive_callback = Rc::clone(&did_receive_callback);
1994            move |_app| did_receive_callback.set(true)
1995        });
1996        animation
1997            .as_animation()
1998            .add_listener(&mut app, listener.clone());
1999
2000        assert!(!did_receive_callback.get());
2001        let target: AnimationRef<f64> = app.create(AlwaysStoppedAnimation::new(0.6)).into_erased();
2002        driver.set_parent(&mut app, Some(target));
2003        assert!(did_receive_callback.get());
2004        did_receive_callback.set(false);
2005
2006        animation
2007            .as_animation()
2008            .remove_listener(&mut app, &listener);
2009        assert!(!did_receive_callback.get());
2010        let target: AnimationRef<f64> = app.create(AlwaysStoppedAnimation::new(0.7)).into_erased();
2011        driver.set_parent(&mut app, Some(target));
2012        assert!(!did_receive_callback.get());
2013    }
2014
2015    // The `_statusChangeHandler` half: status notifications arrive reversed.
2016    #[test]
2017    fn a_reverse_animation_reverses_status_notifications() {
2018        let cell = AppCell::new();
2019        let mut app = cell.borrow_mut();
2020        let driver = ProxyAnimation::new(&mut app, None); // Dismissed
2021        let reverse = ReverseAnimation::new(&mut app, driver.erase());
2022
2023        let statuses = Rc::new(RefCell::new(Vec::new()));
2024        let listener = AnimationStatusListener::new({
2025            let statuses = Rc::clone(&statuses);
2026            move |status, _app| statuses.borrow_mut().push(status)
2027        });
2028        reverse
2029            .as_animation()
2030            .add_status_listener(&mut app, listener.clone());
2031        assert!(
2032            !driver.local_status_listeners_data(&app).is_empty(),
2033            "lazily subscribed to the driver"
2034        );
2035
2036        let complete = k_always_complete_animation(&mut app);
2037        driver.set_parent(&mut app, Some(complete));
2038
2039        assert_eq!(*statuses.borrow(), vec![AnimationStatus::Dismissed]);
2040        assert_eq!(
2041            reverse.as_animation().status(&app),
2042            AnimationStatus::Dismissed
2043        );
2044
2045        reverse
2046            .as_animation()
2047            .remove_status_listener(&mut app, &listener);
2048        assert!(
2049            driver.local_status_listeners_data(&app).is_empty(),
2050            "the rebuilt tear-off matched, so the subscription is gone"
2051        );
2052    }
2053
2054    #[test]
2055    fn a_curved_animation_applies_the_curve() {
2056        let cell = AppCell::new();
2057        let mut app = cell.borrow_mut();
2058        let half: AnimationRef<f64> = app.create(AlwaysStoppedAnimation::new(0.5)).into_erased();
2059        let curved = CurvedAnimation::new(&mut app, half, Curves::ease(), None);
2060
2061        assert_eq!(
2062            curved.as_animation().value(&app),
2063            Curves::ease().transform(0.5)
2064        );
2065        assert_eq!(curved.as_animation().status(&app), AnimationStatus::Forward);
2066    }
2067
2068    #[test]
2069    fn a_curved_animation_uses_the_reverse_curve_when_the_direction_is_reverse() {
2070        let cell = AppCell::new();
2071        let mut app = cell.borrow_mut();
2072        // A parent with status Reverse: a ReverseAnimation over an
2073        // always-Forward stopped animation at 0.25, so its value is 0.75.
2074        let stopped: AnimationRef<f64> =
2075            app.create(AlwaysStoppedAnimation::new(0.25)).into_erased();
2076        let parent: AnimationRef<f64> = ReverseAnimation::new(&mut app, stopped).into_erased();
2077        let curved =
2078            CurvedAnimation::new(&mut app, parent, Curves::ease(), Some(Curves::ease_out()));
2079
2080        // The constructor saw status Reverse while animating, so the curve
2081        // direction is pinned to Reverse and the reverse curve is active.
2082        assert_eq!(
2083            curved.as_animation().value(&app),
2084            Curves::ease_out().transform(0.75)
2085        );
2086    }
2087
2088    // animations_test.dart:251 — 'CurvedAnimation with bogus curve'. Dart
2089    // throws a FlutterError from inside an assert; ours is the debug-only
2090    // panic, so the test exists only in debug builds.
2091    #[cfg(debug_assertions)]
2092    #[test]
2093    #[should_panic(expected = "Invalid curve endpoint")]
2094    fn a_curve_that_moves_an_endpoint_panics_in_debug() {
2095        #[derive(Debug)]
2096        struct BogusCurve;
2097
2098        impl Curve for BogusCurve {
2099            fn transform(&self, _t: f64) -> f64 {
2100                100.0
2101            }
2102        }
2103
2104        let cell = AppCell::new();
2105        let mut app = cell.borrow_mut();
2106        let zero: AnimationRef<f64> = app.create(AlwaysStoppedAnimation::new(0.0)).into_erased();
2107        let curved = CurvedAnimation::new(&mut app, zero, Rc::new(BogusCurve), None);
2108        let _ = curved.as_animation().value(&app);
2109    }
2110
2111    // animations_test.dart:326 — 'CurvedAnimation stops listening to parent
2112    // when disposed', the subscription half.
2113    #[test]
2114    fn a_disposed_curved_animation_unsubscribes_from_its_parent() {
2115        let cell = AppCell::new();
2116        let mut app = cell.borrow_mut();
2117        let driver = ProxyAnimation::new(&mut app, None);
2118        let curved = CurvedAnimation::new(&mut app, driver.erase(), Curves::ease(), None);
2119        assert!(!driver.local_status_listeners_data(&app).is_empty());
2120
2121        curved.dispose(&mut app);
2122        assert!(driver.local_status_listeners_data(&app).is_empty());
2123        assert!(app.get(&curved).is_disposed);
2124    }
2125
2126    // animations_test.dart:97 — 'TrainHoppingAnimation', with ProxyAnimations
2127    // as the trains in place of the unported controllers.
2128    #[test]
2129    fn a_train_hopping_animation_hops_when_the_next_train_crosses() {
2130        let cell = AppCell::new();
2131        let mut app = cell.borrow_mut();
2132        let half: AnimationRef<f64> = app.create(AlwaysStoppedAnimation::new(0.5)).into_erased();
2133        let low: AnimationRef<f64> = app.create(AlwaysStoppedAnimation::new(0.3)).into_erased();
2134        let train_a = ProxyAnimation::new(&mut app, Some(half));
2135        let train_b = ProxyAnimation::new(&mut app, Some(low));
2136
2137        let switched = Rc::new(Cell::new(false));
2138        let train = TrainHoppingAnimation::new(
2139            &mut app,
2140            train_a.erase(),
2141            Some(train_b.erase()),
2142            Some(Listener::new({
2143                let switched = Rc::clone(&switched);
2144                move |_app| switched.set(true)
2145            })),
2146        );
2147
2148        assert_eq!(train.as_animation().value(&app), 0.5);
2149        assert!(!switched.get());
2150
2151        // Drive the next train past the current one: 0.3 → 0.75.
2152        let high: AnimationRef<f64> = app.create(AlwaysStoppedAnimation::new(0.75)).into_erased();
2153        train_b.set_parent(&mut app, Some(high));
2154
2155        assert!(switched.get(), "the hop fired the callback");
2156        assert_eq!(
2157            app.get(&train).current_train(),
2158            Some(train_b.as_animation())
2159        );
2160        assert_eq!(train.as_animation().value(&app), 0.75);
2161    }
2162
2163    #[test]
2164    fn trains_starting_at_the_same_value_hop_immediately_without_the_callback() {
2165        let cell = AppCell::new();
2166        let mut app = cell.borrow_mut();
2167        let a: AnimationRef<f64> = app.create(AlwaysStoppedAnimation::new(0.5)).into_erased();
2168        let b: AnimationRef<f64> = app.create(AlwaysStoppedAnimation::new(0.5)).into_erased();
2169
2170        let switched = Rc::new(Cell::new(false));
2171        let b_handle = b.handle();
2172        let train = TrainHoppingAnimation::new(
2173            &mut app,
2174            a,
2175            Some(b),
2176            Some(Listener::new({
2177                let switched = Rc::clone(&switched);
2178                move |_app| switched.set(true)
2179            })),
2180        );
2181
2182        assert_eq!(app.get(&train).current_train(), Some(b_handle));
2183        assert!(!switched.get(), "Dart never calls onSwitchedTrain here");
2184    }
2185
2186    #[test]
2187    fn a_disposed_train_hopping_animation_releases_both_trains() {
2188        let cell = AppCell::new();
2189        let mut app = cell.borrow_mut();
2190        let half: AnimationRef<f64> = app.create(AlwaysStoppedAnimation::new(0.5)).into_erased();
2191        let low: AnimationRef<f64> = app.create(AlwaysStoppedAnimation::new(0.3)).into_erased();
2192        let train_a = ProxyAnimation::new(&mut app, Some(half));
2193        let train_b = ProxyAnimation::new(&mut app, Some(low));
2194
2195        let train =
2196            TrainHoppingAnimation::new(&mut app, train_a.erase(), Some(train_b.erase()), None);
2197        assert!(!train_a.local_listeners_data(&app).is_empty());
2198        assert!(!train_a.local_status_listeners_data(&app).is_empty());
2199        assert!(!train_b.local_listeners_data(&app).is_empty());
2200
2201        train.dispose(&mut app);
2202        assert!(train_a.local_listeners_data(&app).is_empty());
2203        assert!(train_a.local_status_listeners_data(&app).is_empty());
2204        assert!(train_b.local_listeners_data(&app).is_empty());
2205        assert!(app.get(&train).current_train().is_none());
2206    }
2207
2208    // animations_test.dart:161 — 'AnimationMean control test': Dart's values,
2209    // with ProxyAnimations as the mutable controllers, including the
2210    // removeListener half.
2211    #[test]
2212    fn animation_mean_control_test() {
2213        let cell = AppCell::new();
2214        let mut app = cell.borrow_mut();
2215        let half: AnimationRef<f64> = app.create(AlwaysStoppedAnimation::new(0.5)).into_erased();
2216        let left = ProxyAnimation::new(&mut app, Some(half));
2217        let right = ProxyAnimation::new(&mut app, None); // 0.0
2218
2219        let mean = AnimationMean::new(&mut app, left.erase(), right.erase());
2220        let mean_handle: AnimationRef<f64> = mean.erase();
2221        assert_eq!(mean_handle.value(&app), 0.25);
2222
2223        let log = Rc::new(RefCell::new(Vec::new()));
2224        let mean_animation = mean.as_animation();
2225        let log_value = Listener::new({
2226            let log = Rc::clone(&log);
2227            move |app: &mut App| {
2228                let value = mean_animation.value(app);
2229                log.borrow_mut().push(value);
2230            }
2231        });
2232        mean_handle.add_listener(&mut app, log_value.clone());
2233
2234        let one: AnimationRef<f64> = app.create(AlwaysStoppedAnimation::new(1.0)).into_erased();
2235        right.set_parent(&mut app, Some(one));
2236
2237        assert_eq!(mean_handle.value(&app), 0.75);
2238        assert_eq!(*log.borrow(), vec![0.75]);
2239        log.borrow_mut().clear();
2240
2241        mean_handle.remove_listener(&mut app, &log_value);
2242
2243        let zero: AnimationRef<f64> = app.create(AlwaysStoppedAnimation::new(0.0)).into_erased();
2244        left.set_parent(&mut app, Some(zero));
2245
2246        assert_eq!(mean_handle.value(&app), 0.50);
2247        assert!(log.borrow().is_empty());
2248    }
2249
2250    // animations_test.dart:136 — 'TrainHoppingAnimation notifies status
2251    // listeners'. Dart drives two opposed tweens off one controller; here the
2252    // controller's place is taken by a ProxyAnimation whose parent swaps
2253    // change its value and status together.
2254    #[test]
2255    fn train_hopping_notifies_status_listeners() {
2256        use crate::tween::{Animatable, Tween};
2257
2258        let cell = AppCell::new();
2259        let mut app = cell.borrow_mut();
2260        let driver = ProxyAnimation::new(&mut app, None); // Dismissed, 0.0
2261        let falling = Tween::new(&mut app, Some(1.0), Some(-1.0));
2262        let rising = Tween::new(&mut app, Some(-1.0), Some(1.0));
2263        let current = falling.animate(&mut app, driver.erase());
2264        let next = rising.animate(&mut app, driver.erase());
2265
2266        let animation = TrainHoppingAnimation::new(&mut app, current, Some(next), None);
2267
2268        let status_log = Rc::new(RefCell::new(Vec::new()));
2269        animation.as_animation().add_status_listener(
2270            &mut app,
2271            AnimationStatusListener::new({
2272                let status_log = Rc::clone(&status_log);
2273                move |status, _app| status_log.borrow_mut().push(status)
2274            }),
2275        );
2276        assert!(status_log.borrow().is_empty());
2277
2278        // Dart: `controller.forward()` — status Forward; the trains cross at
2279        // t = 0.5, which hops to the rising train.
2280        let half: AnimationRef<f64> = app.create(AlwaysStoppedAnimation::new(0.5)).into_erased();
2281        driver.set_parent(&mut app, Some(half));
2282        assert_eq!(*status_log.borrow(), vec![AnimationStatus::Forward]);
2283        status_log.borrow_mut().clear();
2284
2285        // Dart: `controller.reverse()` from 0.0 — status Dismissed.
2286        let dismissed = k_always_dismissed_animation(&mut app);
2287        driver.set_parent(&mut app, Some(dismissed));
2288        assert_eq!(*status_log.borrow(), vec![AnimationStatus::Dismissed]);
2289    }
2290
2291    // animations_test.dart:326 — 'CurvedAnimation stops listening to parent
2292    // when disposed', including the frozen curve direction afterwards.
2293    //
2294    #[test]
2295    fn curved_animation_stops_listening_to_parent_when_disposed() {
2296        use crate::curves::Interval;
2297
2298        let forward_curve = Rc::new(Interval::new(0.0, 0.5, Curves::linear()));
2299        let reverse_curve = Rc::new(Interval::new(0.5, 1.0, Curves::linear()));
2300        assert_eq!(forward_curve.transform(0.5), 1.0);
2301        assert_eq!(reverse_curve.transform(0.5), 0.0);
2302
2303        let cell = AppCell::new();
2304        let mut app = cell.borrow_mut();
2305        // Forward at 0.5, and Reverse at 0.5 (a ReverseAnimation over 0.5
2306        // keeps the value while flipping the direction).
2307        let forward_half: AnimationRef<f64> =
2308            app.create(AlwaysStoppedAnimation::new(0.5)).into_erased();
2309        let reverse_half: AnimationRef<f64> = {
2310            let stopped = app.create(AlwaysStoppedAnimation::new(0.5)).into_erased();
2311            ReverseAnimation::new(&mut app, stopped).into_erased()
2312        };
2313
2314        let parent = ProxyAnimation::new(&mut app, Some(forward_half.clone()));
2315        let curved =
2316            CurvedAnimation::new(&mut app, parent.erase(), forward_curve, Some(reverse_curve));
2317        let curved_handle: AnimationRef<f64> = curved.erase();
2318
2319        // Forward at 0.5: the forward interval maps it to 1.0.
2320        assert_eq!(curved_handle.value(&app), 1.0);
2321
2322        // Reach Completed so the curve direction resets, as the Dart test
2323        // does with `controller.value = 1.0`, then go Reverse.
2324        let complete = k_always_complete_animation(&mut app);
2325        parent.set_parent(&mut app, Some(complete));
2326        parent.set_parent(&mut app, Some(reverse_half));
2327        assert_eq!(curved_handle.value(&app), 0.0);
2328
2329        assert!(!app.get(&curved).is_disposed);
2330        curved.dispose(&mut app);
2331        assert!(app.get(&curved).is_disposed);
2332
2333        // Dismissed, then Forward at 0.5 again: were it still listening the
2334        // direction would reset and the forward curve would give 1.0; frozen
2335        // at Reverse, the reverse curve gives 0.0.
2336        let dismissed = k_always_dismissed_animation(&mut app);
2337        parent.set_parent(&mut app, Some(dismissed));
2338        parent.set_parent(&mut app, Some(forward_half));
2339        assert_eq!(curved_handle.value(&app), 0.0);
2340    }
2341
2342    #[test]
2343    fn animation_max_and_min_pick_their_extremes() {
2344        let cell = AppCell::new();
2345        let mut app = cell.borrow_mut();
2346        let low: AnimationRef<f64> = app.create(AlwaysStoppedAnimation::new(0.25)).into_erased();
2347        let high: AnimationRef<f64> = app.create(AlwaysStoppedAnimation::new(0.75)).into_erased();
2348
2349        let max: AnimationRef<f64> =
2350            AnimationMax::new(&mut app, low.clone(), high.clone()).into_erased();
2351        let min: AnimationRef<f64> = AnimationMin::new(&mut app, low, high).into_erased();
2352
2353        assert_eq!(max.value(&app), 0.75);
2354        assert_eq!(min.value(&app), 0.25);
2355    }
2356
2357    #[test]
2358    fn dart_max_and_min_follow_the_documented_contract() {
2359        // NaN propagates from either side — unlike `f64::max`, which drops it.
2360        assert!(dart_max(f64::NAN, 1.0).is_nan());
2361        assert!(dart_max(1.0, f64::NAN).is_nan());
2362        assert!(dart_min(f64::NAN, 1.0).is_nan());
2363        assert!(dart_min(1.0, f64::NAN).is_nan());
2364
2365        // 0.0 is the larger zero, -0.0 the smaller.
2366        assert!(dart_max(0.0, -0.0).is_sign_positive());
2367        assert!(dart_max(-0.0, 0.0).is_sign_positive());
2368        assert!(dart_min(0.0, -0.0).is_sign_negative());
2369        assert!(dart_min(-0.0, 0.0).is_sign_negative());
2370
2371        assert_eq!(dart_max(0.25, 0.75), 0.75);
2372        assert_eq!(dart_min(0.25, 0.75), 0.25);
2373    }
2374}