1use std::any::{TypeId, type_name};
4use std::fmt::{self, Debug};
5use std::hash::{Hash, Hasher};
6use std::rc::{Rc, Weak};
7
8use waft_foundation::{
9 App, Handle, HandleId, ListenableHandle, Listener, Ref, Retained, describe_identity,
10};
11
12use crate::tween::Animatable;
13
14#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
16pub enum AnimationStatus {
17 Dismissed,
19
20 Forward,
22
23 Reverse,
25
26 Completed,
28}
29
30impl AnimationStatus {
31 pub fn is_dismissed(self) -> bool {
33 self == AnimationStatus::Dismissed
34 }
35
36 pub fn is_completed(self) -> bool {
38 self == AnimationStatus::Completed
39 }
40
41 pub fn is_animating(self) -> bool {
43 match self {
44 AnimationStatus::Forward | AnimationStatus::Reverse => true,
45 AnimationStatus::Completed | AnimationStatus::Dismissed => false,
46 }
47 }
48
49 pub fn is_forward_or_completed(self) -> bool {
51 match self {
52 AnimationStatus::Forward | AnimationStatus::Completed => true,
53 AnimationStatus::Reverse | AnimationStatus::Dismissed => false,
54 }
55 }
56}
57
58#[derive(Clone)]
66pub struct AnimationStatusListener {
67 callback: Rc<StatusCallback>,
68 identity: StatusListenerIdentity,
69}
70
71type StatusCallback = dyn Fn(AnimationStatus, &mut App);
72
73#[derive(Clone, Copy)]
76enum StatusListenerIdentity {
77 Closure,
78 HandleMethod(HandleId, TypeId),
79}
80
81impl AnimationStatusListener {
82 pub fn new(callback: impl Fn(AnimationStatus, &mut App) + 'static) -> AnimationStatusListener {
84 AnimationStatusListener {
85 callback: Rc::new(callback),
86 identity: StatusListenerIdentity::Closure,
87 }
88 }
89
90 pub fn handle_method<T: 'static, F>(this: Handle<T>, f: F) -> AnimationStatusListener
103 where
104 F: Fn(Handle<T>, &mut App, AnimationStatus) + 'static,
105 {
106 const {
107 assert!(
108 std::mem::size_of::<F>() == 0,
109 "pass the function by name: a fn pointer or capturing closure \
110 has no canonical identity to match on removal"
111 )
112 };
113 AnimationStatusListener {
114 callback: Rc::new(move |status, app: &mut App| {
115 if app.tear_off_receiver_is_live(this) {
116 f(this, app, status);
117 }
118 }),
119 identity: StatusListenerIdentity::HandleMethod(this.id(), TypeId::of::<F>()),
120 }
121 }
122
123 pub fn call(&self, status: AnimationStatus, app: &mut App) {
125 (self.callback)(status, app);
126 }
127
128 pub fn downgrade(&self) -> WeakAnimationStatusListener {
133 WeakAnimationStatusListener {
134 callback: Rc::downgrade(&self.callback),
135 identity: self.identity,
136 }
137 }
138}
139
140#[derive(Clone)]
143pub struct WeakAnimationStatusListener {
144 callback: Weak<StatusCallback>,
145 identity: StatusListenerIdentity,
146}
147
148impl WeakAnimationStatusListener {
149 pub fn upgrade(&self) -> Option<AnimationStatusListener> {
151 Some(AnimationStatusListener {
152 callback: self.callback.upgrade()?,
153 identity: self.identity,
154 })
155 }
156}
157
158impl PartialEq for AnimationStatusListener {
159 fn eq(&self, other: &AnimationStatusListener) -> bool {
160 match (self.identity, other.identity) {
161 (StatusListenerIdentity::Closure, StatusListenerIdentity::Closure) => {
162 Rc::ptr_eq(&self.callback, &other.callback)
163 }
164 (
165 StatusListenerIdentity::HandleMethod(entity, function),
166 StatusListenerIdentity::HandleMethod(other_entity, other_function),
167 ) => entity == other_entity && function == other_function,
168 _ => false,
169 }
170 }
171}
172
173impl Eq for AnimationStatusListener {}
174
175impl Hash for AnimationStatusListener {
176 fn hash<H: Hasher>(&self, state: &mut H) {
177 match self.identity {
178 StatusListenerIdentity::Closure => {
179 (Rc::as_ptr(&self.callback) as *const ()).hash(state);
180 }
181 StatusListenerIdentity::HandleMethod(entity, function) => {
182 entity.hash(state);
183 function.hash(state);
184 }
185 }
186 }
187}
188
189impl Debug for AnimationStatusListener {
190 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
191 f.write_str("AnimationStatusListener")
192 }
193}
194
195pub trait Animation<T: 'static>: Sized + 'static {
208 fn add_listener(self: Handle<Self>, app: &mut App, listener: Listener);
214
215 fn remove_listener(self: Handle<Self>, app: &mut App, listener: &Listener);
222
223 fn add_status_listener(self: Handle<Self>, app: &mut App, listener: AnimationStatusListener);
229
230 fn remove_status_listener(
237 self: Handle<Self>,
238 app: &mut App,
239 listener: &AnimationStatusListener,
240 );
241
242 fn status(self: Handle<Self>, app: &App) -> AnimationStatus;
244
245 fn value(self: Handle<Self>, app: &App) -> T;
251
252 fn is_dismissed(self: Handle<Self>, app: &App) -> bool {
254 Self::status(self, app).is_dismissed()
255 }
256
257 fn is_completed(self: Handle<Self>, app: &App) -> bool {
259 Self::status(self, app).is_completed()
260 }
261
262 fn is_animating(self: Handle<Self>, app: &App) -> bool {
264 Self::status(self, app).is_animating()
265 }
266
267 fn is_forward_or_completed(self: Handle<Self>, app: &App) -> bool {
269 Self::status(self, app).is_forward_or_completed()
270 }
271
272 fn to_string_details(self: Handle<Self>, app: &App) -> String {
274 animation_status_symbol(Self::status(self, app)).to_string()
275 }
276
277 fn to_string(self: Handle<Self>, app: &App) -> String {
279 format!(
280 "{}({})",
281 describe_identity(
282 waft_foundation::bare_type_name(std::any::type_name::<Self>()),
283 self.id().identity_hash(),
284 ),
285 self.to_string_details(app)
286 )
287 }
288
289 fn as_animation(self: Handle<Self>) -> AnyAnimation<T> {
296 AnyAnimation {
297 id: self.id(),
298 vtable: const { &AnimationVTable::of::<Self>() },
299 }
300 }
301}
302
303pub(crate) fn animation_status_symbol(status: AnimationStatus) -> &'static str {
305 match status {
306 AnimationStatus::Forward => "\u{25B6}",
307 AnimationStatus::Reverse => "\u{25C0}",
308 AnimationStatus::Completed => "\u{23ED}",
309 AnimationStatus::Dismissed => "\u{23EE}",
310 }
311}
312
313pub struct AnyAnimation<T: 'static> {
327 id: HandleId,
328 vtable: &'static AnimationVTable<T>,
329}
330
331struct AnimationVTable<T> {
338 add_listener: fn(&mut App, HandleId, Listener),
339 remove_listener: fn(&mut App, HandleId, &Listener),
340 add_status_listener: fn(&mut App, HandleId, AnimationStatusListener),
341 remove_status_listener: fn(&mut App, HandleId, &AnimationStatusListener),
342 status: fn(&App, HandleId) -> AnimationStatus,
343 value: fn(&App, HandleId) -> T,
344 is_dismissed: fn(&App, HandleId) -> bool,
349 is_completed: fn(&App, HandleId) -> bool,
350 is_animating: fn(&App, HandleId) -> bool,
351 is_forward_or_completed: fn(&App, HandleId) -> bool,
352 to_string: fn(&App, HandleId) -> String,
353}
354
355fn resolve<A: 'static>(id: HandleId) -> Handle<A> {
358 Handle::from_id(id)
359}
360
361impl<T: 'static> AnimationVTable<T> {
362 const fn of<A: Animation<T>>() -> AnimationVTable<T> {
364 AnimationVTable {
365 add_listener: |app, id, listener| A::add_listener(resolve(id), app, listener),
366 remove_listener: |app, id, listener| A::remove_listener(resolve(id), app, listener),
367 add_status_listener: |app, id, listener| {
368 A::add_status_listener(resolve(id), app, listener)
369 },
370 remove_status_listener: |app, id, listener| {
371 A::remove_status_listener(resolve(id), app, listener)
372 },
373 status: |app, id| A::status(resolve(id), app),
374 value: |app, id| A::value(resolve(id), app),
375 is_dismissed: |app, id| A::is_dismissed(resolve(id), app),
376 is_completed: |app, id| A::is_completed(resolve(id), app),
377 is_animating: |app, id| A::is_animating(resolve(id), app),
378 is_forward_or_completed: |app, id| A::is_forward_or_completed(resolve(id), app),
379 to_string: |app, id| A::to_string(resolve(id), app),
380 }
381 }
382}
383
384impl<T: 'static> AnyAnimation<T> {
385 pub fn id(self) -> HandleId {
387 self.id
388 }
389
390 pub fn downcast<A: 'static>(self, app: &App) -> Option<Handle<A>> {
392 app.handle::<A>(self.id)
393 }
394
395 pub fn add_listener(self, app: &mut App, listener: Listener) {
399 (self.vtable.add_listener)(app, self.id, listener)
400 }
401
402 pub fn remove_listener(self, app: &mut App, listener: &Listener) {
407 (self.vtable.remove_listener)(app, self.id, listener)
408 }
409
410 pub fn add_status_listener(self, app: &mut App, listener: AnimationStatusListener) {
415 (self.vtable.add_status_listener)(app, self.id, listener)
416 }
417
418 pub fn remove_status_listener(self, app: &mut App, listener: &AnimationStatusListener) {
424 (self.vtable.remove_status_listener)(app, self.id, listener)
425 }
426
427 pub fn status(self, app: &App) -> AnimationStatus {
429 (self.vtable.status)(app, self.id)
430 }
431
432 pub fn value(self, app: &App) -> T {
434 (self.vtable.value)(app, self.id)
435 }
436
437 pub fn is_dismissed(self, app: &App) -> bool {
439 (self.vtable.is_dismissed)(app, self.id)
440 }
441
442 pub fn is_completed(self, app: &App) -> bool {
444 (self.vtable.is_completed)(app, self.id)
445 }
446
447 pub fn is_animating(self, app: &App) -> bool {
449 (self.vtable.is_animating)(app, self.id)
450 }
451
452 pub fn is_forward_or_completed(self, app: &App) -> bool {
454 (self.vtable.is_forward_or_completed)(app, self.id)
455 }
456
457 pub fn to_string(self, app: &App) -> String {
459 (self.vtable.to_string)(app, self.id)
460 }
461}
462
463pub type AnimationRef<T> = Retained<AnyAnimation<T>>;
467
468waft_foundation::erased_handle!(AnyAnimation<T>: Animation => Animation::as_animation);
469
470pub trait Drive {
478 fn drive<U: 'static>(
480 &self,
481 app: &mut App,
482 child: impl Animatable<U> + Clone + 'static,
483 ) -> AnimationRef<U>;
484}
485
486impl<A: Animation<f64>> Drive for Ref<A> {
487 fn drive<U: 'static>(
488 &self,
489 app: &mut App,
490 child: impl Animatable<U> + Clone + 'static,
491 ) -> AnimationRef<U> {
492 child.animate(app, self.erase())
493 }
494}
495
496impl Drive for AnimationRef<f64> {
497 fn drive<U: 'static>(
498 &self,
499 app: &mut App,
500 child: impl Animatable<U> + Clone + 'static,
501 ) -> AnimationRef<U> {
502 child.animate(app, self.clone())
503 }
504}
505
506impl<T: 'static> ListenableHandle for AnyAnimation<T> {
507 fn add_listener_to(self, app: &mut App, listener: Listener) {
508 AnyAnimation::add_listener(self, app, listener);
509 }
510
511 fn remove_listener_from(self, app: &mut App, listener: &Listener) {
512 AnyAnimation::remove_listener(self, app, listener);
513 }
514}
515
516impl<T> Clone for AnyAnimation<T> {
519 fn clone(&self) -> AnyAnimation<T> {
520 *self
521 }
522}
523
524impl<T> Copy for AnyAnimation<T> {}
525
526impl<T> Debug for AnyAnimation<T> {
527 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
528 write!(f, "AnyAnimation<{}>({:?})", type_name::<T>(), self.id)
529 }
530}
531
532#[cfg(test)]
533mod tests {
534 use std::cell::Cell;
535 use waft_foundation::AppCell;
536
537 use super::*;
538
539 #[test]
540 fn a_weak_status_listener_upgrades_to_an_equal_listener_only_while_one_is_held() {
541 let listener = AnimationStatusListener::new(|_, _| {});
542 let weak = listener.downgrade();
543 assert!(weak.upgrade().is_some_and(|upgraded| upgraded == listener));
544 drop(listener);
545 assert!(weak.upgrade().is_none());
546 }
547
548 #[test]
549 fn the_derived_status_getters_match_flutter() {
550 use AnimationStatus::*;
551
552 assert_eq!(
553 [
554 Dismissed.is_dismissed(),
555 Forward.is_dismissed(),
556 Reverse.is_dismissed(),
557 Completed.is_dismissed()
558 ],
559 [true, false, false, false]
560 );
561 assert_eq!(
562 [
563 Dismissed.is_completed(),
564 Forward.is_completed(),
565 Reverse.is_completed(),
566 Completed.is_completed()
567 ],
568 [false, false, false, true]
569 );
570 assert_eq!(
571 [
572 Dismissed.is_animating(),
573 Forward.is_animating(),
574 Reverse.is_animating(),
575 Completed.is_animating()
576 ],
577 [false, true, true, false]
578 );
579 assert_eq!(
580 [
581 Dismissed.is_forward_or_completed(),
582 Forward.is_forward_or_completed(),
583 Reverse.is_forward_or_completed(),
584 Completed.is_forward_or_completed()
585 ],
586 [false, true, false, true]
587 );
588 }
589
590 #[test]
591 fn only_a_handle_to_the_same_status_closure_compares_equal() {
592 let listener = AnimationStatusListener::new(|_status, _app| {});
593
594 assert_eq!(listener, listener.clone());
595 assert_ne!(listener, AnimationStatusListener::new(|_status, _app| {}));
596 }
597
598 #[test]
599 fn a_rebuilt_handle_method_status_listener_matches_like_a_dart_tear_off() {
600 struct Host;
601 fn hook(_this: Handle<Host>, _app: &mut App, _status: AnimationStatus) {}
602
603 let cell = AppCell::new();
604 let mut app = cell.borrow_mut();
605 let a = app.create(Host);
606 let b = app.create(Host);
607
608 assert_eq!(
609 AnimationStatusListener::handle_method(a.handle(), hook),
610 AnimationStatusListener::handle_method(a.handle(), hook)
611 );
612 assert_ne!(
613 AnimationStatusListener::handle_method(a.handle(), hook),
614 AnimationStatusListener::handle_method(b.handle(), hook)
615 );
616 assert_ne!(
617 AnimationStatusListener::handle_method(a.handle(), hook),
618 AnimationStatusListener::new(|_status, _app| {})
619 );
620 }
621
622 struct OverridingNode;
626
627 impl Animation<f64> for OverridingNode {
628 fn add_listener(self: Handle<Self>, _app: &mut App, _listener: Listener) {}
629 fn remove_listener(self: Handle<Self>, _app: &mut App, _listener: &Listener) {}
630 fn add_status_listener(
631 self: Handle<Self>,
632 _app: &mut App,
633 _listener: AnimationStatusListener,
634 ) {
635 }
636 fn remove_status_listener(
637 self: Handle<Self>,
638 _app: &mut App,
639 _listener: &AnimationStatusListener,
640 ) {
641 }
642 fn status(self: Handle<Self>, _app: &App) -> AnimationStatus {
643 AnimationStatus::Forward
644 }
645 fn value(self: Handle<Self>, _app: &App) -> f64 {
646 0.25
647 }
648 fn is_animating(self: Handle<Self>, _app: &App) -> bool {
649 false
651 }
652 }
653
654 #[test]
655 fn the_erased_handle_dispatches_overridden_getters() {
656 let cell = AppCell::new();
657 let mut app = cell.borrow_mut();
658 let node = app.create(OverridingNode);
659 let animation: AnimationRef<f64> = node.erase();
660
661 assert_eq!(animation.status(&app), AnimationStatus::Forward);
662 assert_eq!(animation.value(&app), 0.25);
663 assert!(
664 !animation.is_animating(&app),
665 "the override, not the status"
666 );
667 assert!(animation.is_forward_or_completed(&app), "the default");
668 }
669
670 #[test]
671 fn erased_handles_are_equal_exactly_when_their_entities_are() {
672 let cell = AppCell::new();
673 let mut app = cell.borrow_mut();
674 let first = app.create(OverridingNode);
675 let second = app.create(OverridingNode);
676
677 assert_eq!(first.erase::<AnyAnimation<f64>>(), first.erase());
678 assert_eq!(
679 first.erase::<AnyAnimation<f64>>().handle(),
680 first.as_animation()
681 );
682 assert_ne!(first.erase::<AnyAnimation<f64>>(), second.erase());
683 }
684
685 struct Counter(u32);
687
688 impl Animation<f64> for Counter {
689 fn add_listener(self: Handle<Self>, _app: &mut App, _listener: Listener) {}
690 fn remove_listener(self: Handle<Self>, _app: &mut App, _listener: &Listener) {}
691 fn add_status_listener(
692 self: Handle<Self>,
693 _app: &mut App,
694 _listener: AnimationStatusListener,
695 ) {
696 }
697 fn remove_status_listener(
698 self: Handle<Self>,
699 _app: &mut App,
700 _listener: &AnimationStatusListener,
701 ) {
702 }
703 fn status(self: Handle<Self>, _app: &App) -> AnimationStatus {
704 AnimationStatus::Forward
705 }
706 fn value(self: Handle<Self>, app: &App) -> f64 {
707 f64::from(app.get(self).0)
708 }
709 }
710
711 #[test]
712 fn an_erased_handle_does_not_consume_the_typed_one() {
713 let cell = AppCell::new();
714 let mut app = cell.borrow_mut();
715 let counter = app.create(Counter(1));
716 let erased: AnimationRef<f64> = counter.erase();
717
718 app.get_mut(&counter).0 = 2;
721 assert_eq!(erased.value(&app), 2.0);
722 }
723
724 #[test]
727 #[should_panic(expected = "stale handle")]
728 fn an_erased_handle_to_a_freed_animation_panics_on_slot_access() {
729 let cell = AppCell::new();
730 let animation = cell.borrow_mut().create(Counter(1)).as_animation();
731 cell.checkpoint();
732 animation.value(&cell.borrow());
733 }
734
735 #[test]
737 fn an_animation_ref_keeps_the_object_its_typed_ref_made() {
738 let cell = AppCell::new();
739 let counter = cell.borrow_mut().create(Counter(1));
740 let handle = counter.handle();
741 let erased: AnimationRef<f64> = counter.into_erased();
742 cell.checkpoint();
743 assert!(cell.borrow().contains(handle), "the erased ref keeps it");
744 assert_eq!(
745 handle.as_animation().upgrade(&cell.borrow()),
746 Some(erased.clone())
747 );
748 drop(erased);
749 cell.checkpoint();
750 assert!(!cell.borrow().contains(handle));
751 }
752
753 #[test]
754 fn a_status_listener_receives_the_status_and_the_app() {
755 thread_local! {
756 static RECEIVED: Cell<Option<AnimationStatus>> = const { Cell::new(None) };
757 }
758 let listener = AnimationStatusListener::new(|status, _app| {
759 RECEIVED.with(|received| received.set(Some(status)));
760 });
761 listener.call(AnimationStatus::Reverse, &mut AppCell::new().borrow_mut());
762 assert_eq!(RECEIVED.with(Cell::get), Some(AnimationStatus::Reverse));
763 }
764}