1use std::cell::{Cell, OnceCell};
4use std::fmt;
5use std::future::Future;
6use std::pin::Pin;
7use std::rc::Rc;
8use std::task::{Context, Poll};
9use std::time::Duration;
10
11use waft_embedder::ViewId;
12use waft_foundation::{App, Completer, CompleterFuture, Handle, Listener, Ref};
13
14use crate::binding::{FrameCallback, FrameTarget, SchedulerBinding, SchedulerPhase};
15
16pub type TickerCallback = FrameCallback;
21
22pub trait TickerProvider {
36 fn create_ticker(&self, app: &mut App, on_tick: TickerCallback) -> Ref<Ticker>;
40}
41
42pub trait TickerProviderObject: Sized + 'static {
45 fn create_ticker(self: Handle<Self>, app: &mut App, on_tick: TickerCallback) -> Ref<Ticker>;
47}
48
49impl<T: TickerProviderObject> TickerProvider for Handle<T> {
50 fn create_ticker(&self, app: &mut App, on_tick: TickerCallback) -> Ref<Ticker> {
51 TickerProviderObject::create_ticker(*self, app, on_tick)
52 }
53}
54
55impl<T: TickerProvider + ?Sized> TickerProvider for Rc<T> {
56 fn create_ticker(&self, app: &mut App, on_tick: TickerCallback) -> Ref<Ticker> {
57 T::create_ticker(self, app, on_tick)
58 }
59}
60
61pub struct Ticker {
79 future: Option<TickerFuture>,
80
81 pub force_frames: bool,
89
90 muted: bool,
91 start_time: Option<Duration>,
92 on_tick: TickerCallback,
93 animation_id: Option<i64>,
94 view: Option<ViewId>,
95 remove_from_creator: Option<TickerRemover>,
98}
99
100pub type TickerRemover = Rc<dyn Fn(&mut App, Handle<Ticker>)>;
103
104impl Ticker {
105 #[track_caller]
108 pub fn new(app: &mut App, on_tick: TickerCallback, view: Option<ViewId>) -> Ref<Ticker> {
109 let ticker = app.create(Ticker {
110 future: None,
111 force_frames: false,
112 muted: false,
113 start_time: None,
114 on_tick,
115 animation_id: None,
116 view,
117 remove_from_creator: None,
118 });
119 app.expect_dispose(&ticker);
120 ticker
121 }
122
123 pub fn set_remove_from_creator(self: Handle<Self>, app: &mut App, remover: TickerRemover) {
126 app.get_mut(self).remove_from_creator = Some(remover);
127 }
128
129 pub fn set_view(self: Handle<Self>, app: &mut App, view: Option<ViewId>) {
131 if app.get(self).view == view {
132 return;
133 }
134 app.get_mut(self).view = view;
135 if let Some(animation_id) = app.get_mut(self).animation_id.take() {
136 SchedulerBinding::cancel_frame_callback_with_id(app, animation_id);
137 self.schedule_tick(app, false);
138 }
139 }
140
141 pub fn muted(self: Handle<Self>, app: &App) -> bool {
146 app.get(self).muted
147 }
148
149 pub fn is_active(self: Handle<Self>, app: &App) -> bool {
157 app.get(self).future.is_some()
158 }
159
160 fn scheduled(self: Handle<Self>, app: &App) -> bool {
162 app.get(self).animation_id.is_some()
163 }
164
165 fn should_schedule_tick(self: Handle<Self>, app: &mut App) -> bool {
178 !app.get(self).muted && self.is_active(app) && !self.scheduled(app)
179 }
180
181 fn tick(self: Handle<Self>, app: &mut App, time_stamp: Duration) {
183 debug_assert!(self.is_ticking(app));
184 debug_assert!(self.scheduled(app));
185 app.get_mut(self).animation_id = None;
186
187 let ticker = app.get_mut(self);
188 let start_time = *ticker.start_time.get_or_insert(time_stamp);
189 let on_tick = ticker.on_tick.clone();
190 on_tick.call(app, time_stamp - start_time);
191
192 if self.should_schedule_tick(app) {
195 self.schedule_tick(app, true);
196 }
197 }
198
199 fn schedule_tick(self: Handle<Self>, app: &mut App, rescheduling: bool) {
204 debug_assert!(!self.scheduled(app));
205 debug_assert!(self.should_schedule_tick(app));
206 let view = app.get(self).view;
207 let target = match view {
208 Some(view) => FrameTarget::View(view),
209 None => FrameTarget::EveryView,
210 };
211 if app.get(self).force_frames {
212 SchedulerBinding::schedule_forced_frame(app, target);
213 } else {
214 SchedulerBinding::schedule_frame(app, target);
215 }
216 let animation_id = SchedulerBinding::schedule_frame_callback(
217 app,
218 FrameCallback::handle_method(self, Ticker::tick),
219 view,
220 rescheduling,
221 false,
222 );
223 app.get_mut(self).animation_id = Some(animation_id);
224 }
225
226 fn unschedule_tick(self: Handle<Self>, app: &mut App) {
231 if let Some(animation_id) = app.get_mut(self).animation_id.take() {
232 SchedulerBinding::cancel_frame_callback_with_id(app, animation_id);
233 }
234 debug_assert!(!self.should_schedule_tick(app));
235 }
236
237 pub fn set_muted(self: Handle<Self>, app: &mut App, value: bool) {
247 if value == app.get(self).muted {
248 return;
249 }
250 app.get_mut(self).muted = value;
251 if value {
252 self.unschedule_tick(app);
253 } else if self.should_schedule_tick(app) {
254 self.schedule_tick(app, false);
255 }
256 }
257
258 #[allow(clippy::wrong_self_convention)]
265 pub fn is_ticking(self: Handle<Self>, app: &mut App) -> bool {
266 app.get(self).future.is_some() && !app.get(self).muted
267 }
268
269 pub fn start(self: Handle<Self>, app: &mut App) -> TickerFuture {
283 debug_assert!(
284 !self.is_active(app),
285 "A ticker was started twice. A ticker that is already active cannot be started again without first stopping it."
286 );
287 debug_assert!(app.get(self).start_time.is_none());
288
289 let future = TickerFuture::new();
290 app.get_mut(self).future = Some(future.clone());
291 if self.should_schedule_tick(app) {
292 self.schedule_tick(app, false);
293 }
294 let phase = SchedulerBinding::scheduler_phase(app);
295 if phase > SchedulerPhase::Idle && phase < SchedulerPhase::PostFrameCallbacks {
296 let time_stamp = SchedulerBinding::current_frame_time_stamp(app);
297 app.get_mut(self).start_time = Some(time_stamp);
298 }
299 future
300 }
301
302 pub fn stop(self: Handle<Self>, app: &mut App, canceled: bool) {
314 if !self.is_active(app) {
315 return;
316 }
317
318 let ticker = app.get_mut(self);
322 let local_future = ticker.future.take().unwrap();
323 ticker.start_time = None;
324 debug_assert!(!self.is_active(app));
325
326 self.unschedule_tick(app);
327 if canceled {
328 local_future.mark_canceled(app, self.upgrade(app));
329 } else {
330 local_future.mark_complete(app);
331 }
332 }
333
334 pub fn absorb_ticker(self: Handle<Self>, app: &mut App, original_ticker: Handle<Ticker>) {
345 debug_assert!(!self.is_active(app));
346 debug_assert!(app.get(self).future.is_none());
347 debug_assert!(app.get(self).start_time.is_none());
348 debug_assert!(app.get(self).animation_id.is_none());
349 debug_assert!(
350 app.get(original_ticker).future.is_some()
351 || app.get(original_ticker).start_time.is_none(),
352 "Cannot absorb Ticker after it has been disposed."
353 );
354 if app.get(original_ticker).future.is_some() {
355 let original = app.get_mut(original_ticker);
356 let future = original.future.take(); let start_time = original.start_time; let ticker = app.get_mut(self); ticker.future = future;
360 ticker.start_time = start_time;
361 if self.should_schedule_tick(app) {
362 self.schedule_tick(app, false);
363 }
364 original_ticker.unschedule_tick(app);
365 }
366 original_ticker.dispose(app);
367 }
368
369 pub fn dispose(self: Handle<Self>, app: &mut App) {
383 app.mark_disposed(self);
384 if let Some(remove_from_creator) = app.get_mut(self).remove_from_creator.take() {
385 remove_from_creator(app, self);
386 }
387 if let Some(local_future) = app.get_mut(self).future.take() {
388 debug_assert!(!self.is_active(app));
389 self.unschedule_tick(app);
390 local_future.mark_canceled(app, self.upgrade(app));
391 }
392 #[cfg(debug_assertions)]
393 {
394 app.get_mut(self).start_time = Some(Duration::ZERO);
398 }
399 }
400}
401
402#[derive(Clone)]
416pub struct TickerFuture {
417 shared: Rc<TickerFutureState>,
418}
419
420struct TickerFutureState {
423 primary: Completer<()>,
424 secondary: OnceCell<Completer<Result<(), TickerCanceled>>>,
425 completed: Cell<Option<bool>>,
427}
428
429impl TickerFuture {
430 fn new() -> TickerFuture {
431 TickerFuture {
432 shared: Rc::new(TickerFutureState {
433 primary: Completer::new(),
434 secondary: OnceCell::new(),
435 completed: Cell::new(None),
436 }),
437 }
438 }
439
440 pub fn complete() -> TickerFuture {
447 TickerFuture {
448 shared: Rc::new(TickerFutureState {
449 primary: Completer::completed(()),
450 secondary: OnceCell::new(),
451 completed: Cell::new(Some(true)),
452 }),
453 }
454 }
455
456 fn mark_complete(&self, app: &mut App) {
458 debug_assert!(self.shared.completed.get().is_none());
459 self.shared.completed.set(Some(true));
460 self.shared.primary.complete(app, ());
461 if let Some(secondary) = self.shared.secondary.get() {
462 secondary.complete(app, Ok(()));
463 }
464 }
465
466 fn mark_canceled(&self, app: &mut App, ticker: Option<Ref<Ticker>>) {
469 debug_assert!(self.shared.completed.get().is_none());
470 self.shared.completed.set(Some(false));
471 if let Some(secondary) = self.shared.secondary.get() {
472 secondary.complete(app, Err(TickerCanceled { ticker }));
473 }
474 }
475
476 pub fn or_cancel(&self) -> CompleterFuture<Result<(), TickerCanceled>> {
483 self.shared
484 .secondary
485 .get_or_init(|| match self.shared.completed.get() {
486 None => Completer::new(),
487 Some(true) => Completer::completed(Ok(())),
488 Some(false) => Completer::completed(Err(TickerCanceled { ticker: None })),
489 })
490 .future()
491 }
492
493 pub fn when_complete(&self, app: &mut App, callback: Listener) {
497 self.shared
498 .primary
499 .future()
500 .then(app, move |app, ()| callback.call(app));
501 }
502
503 pub fn when_complete_or_cancel(&self, app: &mut App, callback: Listener) {
508 self.or_cancel().then(app, move |app, _| callback.call(app));
509 }
510}
511
512impl Future for TickerFuture {
513 type Output = ();
514
515 fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<()> {
516 let mut primary = self.shared.primary.future();
517 Pin::new(&mut primary).poll(cx)
518 }
519}
520
521impl fmt::Debug for TickerFuture {
522 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
523 let state = match self.shared.completed.get() {
524 None => "active",
525 Some(true) => "complete",
526 Some(false) => "canceled",
527 };
528 write!(f, "TickerFuture({state})")
529 }
530}
531
532#[derive(Clone, Debug, PartialEq, Eq)]
535pub struct TickerCanceled {
536 pub ticker: Option<Ref<Ticker>>,
541}
542
543impl fmt::Display for TickerCanceled {
544 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
545 match &self.ticker {
546 Some(ticker) => write!(f, "This ticker was canceled: {ticker:?}"),
547 None => write!(
548 f,
549 "The ticker was canceled before the \"orCancel\" property was first used."
550 ),
551 }
552 }
553}
554
555impl std::error::Error for TickerCanceled {}
556
557#[cfg(test)]
558mod tests {
559 use std::cell::{Cell, RefCell};
560 use std::rc::Rc;
561
562 use waft_foundation::AppCell;
563 use waft_test::IMPLICIT_VIEW_ID;
564
565 use super::*;
566 use crate::test_support::app_with_views;
567
568 fn pump(app: &mut App, at: Duration) {
570 crate::test_support::pump(app, &[IMPLICIT_VIEW_ID], at);
571 }
572
573 fn app_with_implicit_view() -> Rc<AppCell> {
575 app_with_views(&[IMPLICIT_VIEW_ID]).0
576 }
577
578 fn elapsed_recorder(log: &Rc<RefCell<Vec<Duration>>>) -> TickerCallback {
579 let log = Rc::clone(log);
580 FrameCallback::new(move |_app, elapsed| log.borrow_mut().push(elapsed))
581 }
582
583 #[test]
586 fn a_ticker_ticks_with_elapsed_time_until_stopped() {
587 let cell = app_with_implicit_view();
588 let mut app = cell.borrow_mut();
589 let log = Rc::new(RefCell::new(Vec::new()));
590 let ticker = Ticker::new(&mut app, elapsed_recorder(&log), Some(IMPLICIT_VIEW_ID));
591
592 ticker.start(&mut app);
593 assert!(ticker.is_active(&app));
594 assert!(SchedulerBinding::has_scheduled_frame(&mut app));
595
596 pump(&mut app, Duration::from_millis(10));
597 pump(&mut app, Duration::from_millis(25));
598 ticker.stop(&mut app, false);
599 pump(&mut app, Duration::from_millis(40));
600
601 assert_eq!(
603 *log.borrow(),
604 vec![Duration::ZERO, Duration::from_millis(15)]
605 );
606 assert!(!ticker.is_active(&app));
607 }
608
609 #[test]
611 fn a_muted_ticker_keeps_time_but_does_not_call_back() {
612 let cell = app_with_implicit_view();
613 let mut app = cell.borrow_mut();
614 let log = Rc::new(RefCell::new(Vec::new()));
615 let ticker = Ticker::new(&mut app, elapsed_recorder(&log), Some(IMPLICIT_VIEW_ID));
616
617 ticker.start(&mut app);
618 assert!(ticker.is_ticking(&mut app));
619 pump(&mut app, Duration::from_millis(10));
620
621 ticker.set_muted(&mut app, true);
622 assert!(!ticker.is_ticking(&mut app));
623 assert!(ticker.is_active(&app));
624 SchedulerBinding::schedule_frame(&mut app, FrameTarget::View(IMPLICIT_VIEW_ID));
625 pump(&mut app, Duration::from_millis(20));
626 assert_eq!(log.borrow().len(), 1, "no tick while muted");
627
628 ticker.set_muted(&mut app, false);
629 assert!(ticker.is_ticking(&mut app));
630 pump(&mut app, Duration::from_millis(30));
631
632 assert_eq!(
634 *log.borrow(),
635 vec![Duration::ZERO, Duration::from_millis(20)]
636 );
637
638 ticker.stop(&mut app, false);
639 ticker.set_muted(&mut app, false);
640 pump(&mut app, Duration::from_millis(40));
641 assert_eq!(log.borrow().len(), 2, "stopped ticker does not tick");
642 assert!(!ticker.is_ticking(&mut app));
643 assert!(!ticker.is_active(&app));
644 }
645
646 #[test]
648 fn a_ticker_is_slowed_by_time_dilation() {
649 let cell = app_with_implicit_view();
650 let mut app = cell.borrow_mut();
651 SchedulerBinding::set_time_dilation(&mut app, 2.0);
652 let last = Rc::new(Cell::new(None::<Duration>));
653 let ticker = Ticker::new(
654 &mut app,
655 FrameCallback::new({
656 let last = Rc::clone(&last);
657 move |_app, duration| last.set(Some(duration))
658 }),
659 Some(IMPLICIT_VIEW_ID),
660 );
661 ticker.start(&mut app);
662 pump(&mut app, Duration::from_millis(10));
663 pump(&mut app, Duration::from_millis(20));
664 assert_eq!(last.get(), Some(Duration::from_millis(5)));
665 ticker.dispose(&mut app);
666 SchedulerBinding::set_time_dilation(&mut app, 1.0);
667 }
668
669 #[test]
670 fn the_ticker_future_completes_through_the_microtask_queue() {
671 let cell = app_with_implicit_view();
672 let mut app = cell.borrow_mut();
673 let ticker = Ticker::new(
674 &mut app,
675 FrameCallback::new(|_app, _t| {}),
676 Some(IMPLICIT_VIEW_ID),
677 );
678 let future = ticker.start(&mut app);
679
680 let completed = Rc::new(Cell::new(false));
681 future.when_complete(
682 &mut app,
683 Listener::new({
684 let completed = Rc::clone(&completed);
685 move |_app| completed.set(true)
686 }),
687 );
688
689 ticker.stop(&mut app, false);
690 assert!(
691 !completed.get(),
692 "Dart resolves Future listeners on the microtask queue, not during stop()"
693 );
694 app.drain_microtasks();
695 assert!(completed.get());
696 }
697
698 #[test]
699 fn disposing_an_active_ticker_cancels_without_completing() {
700 let cell = app_with_implicit_view();
701 let mut app = cell.borrow_mut();
702 let ticker = Ticker::new(
703 &mut app,
704 FrameCallback::new(|_app, _t| {}),
705 Some(IMPLICIT_VIEW_ID),
706 );
707 let future = ticker.start(&mut app);
708
709 let completed = Rc::new(Cell::new(false));
710 let either = Rc::new(Cell::new(false));
711 future.when_complete(
712 &mut app,
713 Listener::new({
714 let completed = Rc::clone(&completed);
715 move |_app| completed.set(true)
716 }),
717 );
718 future.when_complete_or_cancel(
719 &mut app,
720 Listener::new({
721 let either = Rc::clone(&either);
722 move |_app| either.set(true)
723 }),
724 );
725
726 ticker.dispose(&mut app);
727 app.drain_microtasks();
728
729 assert!(!completed.get(), "the primary future never resolves");
730 assert!(
731 either.get(),
732 "whenCompleteOrCancel observes the cancellation"
733 );
734 }
735
736 #[test]
739 fn absorbing_a_ticker_keeps_the_original_future_alive() {
740 let cell = app_with_implicit_view();
741 let mut app = cell.borrow_mut();
742 let log = Rc::new(RefCell::new(Vec::new()));
743 let original = Ticker::new(&mut app, elapsed_recorder(&log), Some(IMPLICIT_VIEW_ID));
744 let future = original.start(&mut app);
745
746 let absorber = Ticker::new(
747 &mut app,
748 FrameCallback::new(|_app, _t| {}),
749 Some(IMPLICIT_VIEW_ID),
750 );
751 absorber.absorb_ticker(&mut app, original.handle());
752
753 assert!(absorber.is_active(&app));
754
755 let completed = Rc::new(Cell::new(false));
756 future.when_complete(
757 &mut app,
758 Listener::new({
759 let completed = Rc::clone(&completed);
760 move |_app| completed.set(true)
761 }),
762 );
763 absorber.stop(&mut app, false);
764 app.drain_microtasks();
765 assert!(completed.get(), "not canceled by the original's dispose");
766 }
767
768 #[test]
769 fn a_zero_duration_sequence_is_already_complete() {
770 let cell = app_with_implicit_view();
771 let mut app = cell.borrow_mut();
772 let future = TickerFuture::complete();
773
774 let ran = Rc::new(Cell::new(false));
775 future.when_complete(
776 &mut app,
777 Listener::new({
778 let ran = Rc::clone(&ran);
779 move |_app| ran.set(true)
780 }),
781 );
782 assert!(!ran.get(), "still asynchronous on a resolved future");
783 app.drain_microtasks();
784 assert!(ran.get());
785 }
786
787 struct TestVSync;
788
789 impl TickerProvider for TestVSync {
790 fn create_ticker(&self, app: &mut App, on_tick: TickerCallback) -> Ref<Ticker> {
791 Ticker::new(app, on_tick, Some(IMPLICIT_VIEW_ID))
792 }
793 }
794
795 #[test]
796 fn a_ticker_provider_vends_a_ticker_that_ticks() {
797 let cell = app_with_implicit_view();
798 let mut app = cell.borrow_mut();
799 let log = Rc::new(RefCell::new(Vec::new()));
800 let ticker = TestVSync.create_ticker(&mut app, elapsed_recorder(&log));
801 ticker.start(&mut app);
802 pump(&mut app, Duration::from_millis(10));
803 assert_eq!(*log.borrow(), vec![Duration::ZERO]);
804 ticker.stop(&mut app, false);
805 }
806
807 struct Host {
808 ticker: Option<Ref<Ticker>>,
809 }
810
811 impl TickerProvider for Handle<Host> {
812 fn create_ticker(&self, app: &mut App, on_tick: TickerCallback) -> Ref<Ticker> {
813 let ticker = Ticker::new(app, on_tick, Some(IMPLICIT_VIEW_ID));
814 app.get_mut(*self).ticker = Some(ticker.clone());
815 ticker
816 }
817 }
818
819 #[test]
820 fn a_provider_in_the_app_can_vend_a_ticker() {
821 let cell = app_with_implicit_view();
822 let mut app = cell.borrow_mut();
823 let host = app.create(Host { ticker: None });
824 let log = Rc::new(RefCell::new(Vec::new()));
825 let ticker = host.create_ticker(&mut app, elapsed_recorder(&log));
826 assert!(app.get(&host).ticker.is_some());
827 ticker.start(&mut app);
828 pump(&mut app, Duration::from_millis(10));
829 assert_eq!(*log.borrow(), vec![Duration::ZERO]);
830 ticker.stop(&mut app, false);
831 }
832
833 #[test]
834 fn a_ticker_moved_to_another_view_ticks_at_its_frames() {
835 let other = ViewId(1);
836 let (cell, platform) = app_with_views(&[IMPLICIT_VIEW_ID, other]);
837 let mut app = cell.borrow_mut();
838 let log = Rc::new(RefCell::new(Vec::new()));
839 let ticker = Ticker::new(&mut app, elapsed_recorder(&log), Some(IMPLICIT_VIEW_ID));
840 ticker.start(&mut app);
841
842 crate::test_support::pump(&mut app, &[other], Duration::from_millis(5));
843 assert!(log.borrow().is_empty(), "another view's frame");
844 pump(&mut app, Duration::from_millis(10));
845 assert_eq!(log.borrow().len(), 1);
846
847 platform.take_frame_requests();
849 ticker.set_view(&mut app, Some(other));
850 assert_eq!(
851 platform.take_frame_requests(),
852 [other],
853 "the tick asks for its new view"
854 );
855 pump(&mut app, Duration::from_millis(20));
856 assert_eq!(log.borrow().len(), 1, "its old view's frame");
857 crate::test_support::pump(&mut app, &[other], Duration::from_millis(21));
858 assert_eq!(
859 *log.borrow(),
860 [Duration::ZERO, Duration::from_millis(11)],
861 "its new view's frame"
862 );
863 ticker.stop(&mut app, false);
864 }
865
866 #[test]
869 fn a_ticker_dropped_while_ticking_is_freed_and_its_frame_callback_skipped() {
870 let cell = app_with_implicit_view();
871 let log = Rc::new(RefCell::new(Vec::new()));
872 let ticker = {
873 let mut app = cell.borrow_mut();
874 let ticker = Ticker::new(&mut app, elapsed_recorder(&log), Some(IMPLICIT_VIEW_ID));
875 ticker.start(&mut app);
876 ticker.handle()
877 };
878 cell.checkpoint();
879 assert!(!cell.borrow().contains(ticker));
880 pump(&mut cell.borrow_mut(), Duration::from_millis(10));
881 assert!(log.borrow().is_empty());
882 }
883
884 #[test]
885 fn a_ticker_in_no_view_ticks_at_every_frame() {
886 let other = ViewId(1);
887 let (cell, _platform) = app_with_views(&[IMPLICIT_VIEW_ID, other]);
888 let mut app = cell.borrow_mut();
889 let log = Rc::new(RefCell::new(Vec::new()));
890 let ticker = Ticker::new(&mut app, elapsed_recorder(&log), None);
891 ticker.start(&mut app);
892
893 pump(&mut app, Duration::from_millis(10));
894 crate::test_support::pump(&mut app, &[other], Duration::from_millis(18));
895 assert_eq!(*log.borrow(), [Duration::ZERO, Duration::from_millis(8)]);
896 ticker.stop(&mut app, false);
897 }
898}