Skip to main content

waft_scheduler/
ticker.rs

1//! Flutter counterpart: `scheduler/ticker.dart`.
2
3use 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
16/// Signature for the callback passed to the [`Ticker`] class's constructor.
17///
18/// The argument is the time elapsed from the frame timestamp when the ticker
19/// was last started to the current frame timestamp.
20pub type TickerCallback = FrameCallback;
21
22/// An interface implemented by classes that can vend [`Ticker`] objects.
23///
24/// Tickers can be used by any object that wants to be notified whenever a
25/// frame triggers, but are most commonly used indirectly via an
26/// `AnimationController`. `AnimationController`s need a [`TickerProvider`] to
27/// obtain their [`Ticker`].
28///
29/// An object in the App implements [`TickerProviderObject`]; its [`Handle`] is then a
30/// provider — Dart's `TickerProviderStateMixin` is `vsync: this` — and a field that Dart types
31/// as `TickerProvider` holds an `Rc<dyn TickerProvider>`.
32///
33/// The ticker is the caller's to keep (an `AnimationController` holds it); a provider that keeps
34/// a set of the tickers it vends holds a second [`Ref`] to each.
35pub trait TickerProvider {
36    /// Creates a ticker with the given callback.
37    ///
38    /// The kind of ticker provided depends on the kind of ticker provider.
39    fn create_ticker(&self, app: &mut App, on_tick: TickerCallback) -> Ref<Ticker>;
40}
41
42/// [`TickerProvider`] for an object in the App: Dart's `implements TickerProvider` on a
43/// `State`, whose `vsync: this` is the object's [`Handle`].
44pub trait TickerProviderObject: Sized + 'static {
45    /// See [`TickerProvider::create_ticker`].
46    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
61/// Calls its callback once per animation frame, when enabled.
62///
63/// When created, a ticker is initially disabled. Call
64/// [`start`](Ticker::start) to enable the ticker.
65///
66/// A [`Ticker`] can be silenced by setting muted to true. While silenced, time
67/// still elapses, and [`start`](Ticker::start) and
68/// [`stop`](Ticker::stop) can still be called, but no callbacks are
69/// called.
70///
71/// By convention, the [`start`](Ticker::start) and
72/// [`stop`](Ticker::stop) methods are used by the ticker's consumer
73/// (for example, an `AnimationController`), and the muted property is
74/// controlled by the [`TickerProvider`] that created the ticker.
75///
76/// A ticker ticks at the frames of its view, or at every frame when it has none. Its view must
77/// follow its widget: the [`TickerProvider`] moves it with [`set_view`](Ticker::set_view).
78pub struct Ticker {
79    future: Option<TickerFuture>,
80
81    /// If true, this ticker will request frames using
82    /// [`SchedulerBinding::schedule_forced_frame`] instead of
83    /// [`SchedulerBinding::schedule_frame`].
84    ///
85    /// This allows granular control to advance frames even when frames are
86    /// typically disabled (e.g. when the app is in the background). This
87    /// should be used sparingly as it can increase battery usage.
88    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    /// Dart's `_WidgetTicker._creator._removeTicker`: what the provider that vended this
96    /// ticker runs when it is disposed, to take it out of the provider's set.
97    remove_from_creator: Option<TickerRemover>,
98}
99
100/// What a ticker's provider runs when the ticker is disposed; see
101/// [`Ticker::set_remove_from_creator`].
102pub type TickerRemover = Rc<dyn Fn(&mut App, Handle<Ticker>)>;
103
104impl Ticker {
105    /// Creates a ticker that will call the provided callback once per frame of `view`, or of
106    /// every frame for `None`, while running.
107    #[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    /// Dart's `_WidgetTicker(onTick, creator)`: a provider that keeps the tickers it vends in a
124    /// set has `dispose` take this one out of it first, as `_WidgetTicker.dispose` does.
125    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    /// Its widget moved to `view`: a pending tick moves with it and asks for that view's frame.
130    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    /// Whether this ticker has been silenced.
142    ///
143    /// While silenced, a ticker's clock can still run, but the callback will
144    /// not be called.
145    pub fn muted(self: Handle<Self>, app: &App) -> bool {
146        app.get(self).muted
147    }
148
149    /// Whether time is elapsing for this [`Ticker`]. Becomes true when
150    /// [`start`](Ticker::start) is called and false when
151    /// [`stop`](Ticker::stop) is called.
152    ///
153    /// A ticker can be active yet not be actually ticking (i.e. not be
154    /// calling the callback). To determine if a ticker is actually ticking,
155    /// use [`is_ticking`](Ticker::is_ticking).
156    pub fn is_active(self: Handle<Self>, app: &App) -> bool {
157        app.get(self).future.is_some()
158    }
159
160    /// Whether this [`Ticker`] has already scheduled a frame callback.
161    fn scheduled(self: Handle<Self>, app: &App) -> bool {
162        app.get(self).animation_id.is_some()
163    }
164
165    /// Whether a tick should be scheduled.
166    ///
167    /// If this is true, then calling [`schedule_tick`](Ticker::schedule_tick)
168    /// should succeed.
169    ///
170    /// Reasons why a tick should not be scheduled include:
171    ///
172    /// * A tick has already been scheduled for the coming frame.
173    /// * The ticker is not active ([`start`](Ticker::start) has not
174    ///   been called).
175    /// * The ticker is not ticking, e.g. because it is muted (see
176    ///   [`is_ticking`](Ticker::is_ticking)).
177    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    /// Dart's `_tick`, the frame callback registered with the binding.
182    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        // The onTick callback may have scheduled another tick already, for
193        // example by calling stop then start again.
194        if self.should_schedule_tick(app) {
195            self.schedule_tick(app, true);
196        }
197    }
198
199    /// Schedules a tick for the next frame.
200    ///
201    /// This should only be called if
202    /// [`should_schedule_tick`](Ticker::should_schedule_tick) is true.
203    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    /// Cancels the frame callback that was requested by
227    /// [`schedule_tick`](Ticker::schedule_tick), if any.
228    ///
229    /// Calling this method when no tick is scheduled is harmless.
230    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    /// When set to true, silences the ticker. If a tick is already scheduled,
238    /// it will unschedule it. This will not unschedule the next frame.
239    ///
240    /// When set to false, unsilences the ticker, potentially scheduling a
241    /// frame to handle the next tick.
242    ///
243    /// By convention, muted is controlled by the object that created the
244    /// [`Ticker`] (typically a [`TickerProvider`]), not the object that
245    /// listens to the ticker's ticks.
246    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    /// Whether this [`Ticker`] has scheduled a call to call its callback on
259    /// the next frame.
260    ///
261    /// A ticker that is muted can be active (see [`Ticker::is_active`]) yet
262    /// not be ticking. In that case, the ticker will not call its callback,
263    /// and `is_ticking` will be false, but time will still be progressing.
264    #[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    /// Starts the clock for this [`Ticker`]. If the ticker is not muted, then
270    /// this also starts calling the ticker's callback once per animation
271    /// frame.
272    ///
273    /// The returned future resolves once the ticker stops ticking. If the
274    /// ticker is disposed, the future does not resolve.
275    ///
276    /// Calling this sets [`Ticker::is_active`] to true.
277    ///
278    /// # Panics
279    ///
280    /// In debug builds, if the ticker is already active — Dart throws a
281    /// `FlutterError` from an assert block here.
282    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    /// Stops calling this [`Ticker`]'s callback.
303    ///
304    /// If called with `canceled` false (Dart's default), causes the future
305    /// returned by [`start`](Ticker::start) to resolve. If called
306    /// with `canceled` true, the future does not resolve, and callbacks
307    /// registered with [`TickerFuture::when_complete_or_cancel`]
308    /// resolve as canceled.
309    ///
310    /// Calling this sets [`Ticker::is_active`] to false.
311    ///
312    /// This method does nothing if called when the ticker is inactive.
313    pub fn stop(self: Handle<Self>, app: &mut App, canceled: bool) {
314        if !self.is_active(app) {
315            return;
316        }
317
318        // We take the future into a local so that isTicking is false when we
319        // actually complete the future (isTicking uses the future to
320        // determine its state).
321        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    /// Makes this [`Ticker`] take the state of another ticker, and disposes
335    /// the other ticker.
336    ///
337    /// This is useful if an object with a [`Ticker`] is given a new
338    /// [`TickerProvider`] but needs to maintain continuity. In particular,
339    /// this maintains the identity of the [`TickerFuture`] returned by the
340    /// [`start`](Ticker::start) function of the original [`Ticker`]
341    /// if the original ticker is active.
342    ///
343    /// This ticker must not be active when this method is called.
344    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(); // so the future is not
357            let start_time = original.start_time; // canceled when we dispose
358            let ticker = app.get_mut(self); // the original ticker below
359            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    /// Release the resources used by this object. The object is no longer
370    /// usable after this method is called.
371    ///
372    /// It is legal to call this method while [`Ticker::is_active`] is true, in
373    /// which case:
374    ///
375    /// * The frame callback that was requested by `schedule_tick`, if any, is
376    ///   canceled.
377    /// * The future that was returned by [`start`](Ticker::start)
378    ///   does not resolve.
379    /// * Callbacks registered with
380    ///   [`TickerFuture::when_complete_or_cancel`] resolve as
381    ///   canceled.
382    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            // We intentionally don't null out startTime. This means that if
395            // start() was ever called, the object is now in a bogus state.
396            // This weakly helps catch cases of use-after-dispose.
397            app.get_mut(self).start_time = Some(Duration::ZERO);
398        }
399    }
400}
401
402/// An object representing an ongoing [`Ticker`] sequence.
403///
404/// The [`Ticker::start`] method returns a [`TickerFuture`]. The [`TickerFuture`] will
405/// complete successfully if the [`Ticker`] is stopped using [`Ticker::stop`] with `canceled`
406/// false. If the [`Ticker`] is disposed without being stopped, or if it is stopped with
407/// `canceled` true, then this future will never complete.
408///
409/// A `Future<Output = ()>`, as Dart's implements `Future<void>`: `await` it in a task, or
410/// register a callback with [`when_complete`](Self::when_complete). Clones share the one
411/// sequence, as Dart's references to the one object do.
412///
413/// To be notified when the sequence is canceled, use [`or_cancel`](Self::or_cancel) or
414/// [`when_complete_or_cancel`](Self::when_complete_or_cancel).
415#[derive(Clone)]
416pub struct TickerFuture {
417    shared: Rc<TickerFutureState>,
418}
419
420/// Written once each: the outcome, and the secondary completer `or_cancel` creates on first
421/// use. No runtime borrow can conflict here.
422struct TickerFutureState {
423    primary: Completer<()>,
424    secondary: OnceCell<Completer<Result<(), TickerCanceled>>>,
425    /// `None` means unresolved, `Some(true)` complete, `Some(false)` canceled.
426    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    /// Creates a [`TickerFuture`] instance that represents an already-complete [`Ticker`]
441    /// sequence.
442    ///
443    /// This is useful for implementing objects that normally defer to a [`Ticker`] but
444    /// sometimes can skip the ticker because the animation is of zero duration, but which
445    /// still need to represent the completed animation in the form of a [`TickerFuture`].
446    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    /// Dart's private `_complete`, called by [`Ticker::stop`].
457    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    /// Dart's private `_cancel`, called by [`Ticker::stop`] with `canceled` and by
467    /// [`Ticker::dispose`].
468    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    /// A future that resolves when this future resolves or with a [`TickerCanceled`] when
477    /// the ticker is canceled.
478    ///
479    /// Until this is first called, canceling the ticker records no error anywhere; from
480    /// then on a cancellation resolves the returned future with `Err`, which the awaiting
481    /// task is expected to handle.
482    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    /// Dart's `then` / `whenComplete`: runs `callback` on the microtask queue after the
494    /// ticker stops without being canceled, never inline — a `.then` on an already resolved
495    /// future still runs asynchronously. On a canceled ticker it never runs.
496    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    /// Calls `callback` either when this future resolves or when the ticker is canceled.
504    ///
505    /// Calling this method registers a handler for the [`or_cancel`](Self::or_cancel) error,
506    /// so canceling the ticker afterwards leaves no unobserved cancellation.
507    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/// Exception thrown by [`Ticker`] objects on the [`TickerFuture::or_cancel`] future when
533/// the ticker is canceled.
534#[derive(Clone, Debug, PartialEq, Eq)]
535pub struct TickerCanceled {
536    /// Reference to the [`Ticker`] object that was canceled.
537    ///
538    /// This may be `None` in the case that the future created for
539    /// [`TickerFuture::or_cancel`] was created after the ticker was canceled.
540    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    /// A refresh of the implicit view at `at`.
569    fn pump(app: &mut App, at: Duration) {
570        crate::test_support::pump(app, &[IMPLICIT_VIEW_ID], at);
571    }
572
573    /// An app on a platform with the implicit view.
574    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    // ticker_test.dart 'ticker can be started and stopped' (adapted: frames
584    // come from handle_begin_frame, as flutter_test's pump does).
585    #[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        // Elapsed is measured from the first tick's time stamp.
602        assert_eq!(
603            *log.borrow(),
604            vec![Duration::ZERO, Duration::from_millis(15)]
605        );
606        assert!(!ticker.is_active(&app));
607    }
608
609    // ticker_test.dart 'Ticker mute control test' (without lifecycle).
610    #[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        // Time elapsed while muted: the clock ran from the 10ms tick.
633        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    // ticker_test.dart 'Ticker can be slowed down with time dilation'
647    #[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    // ticker.dart's absorbTicker contract: the original's active future
737    // survives under the absorbing ticker's identity.
738    #[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        // Its widget moved to the other view, with a tick due.
848        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    /// Dropped while ticking and never disposed (D3: the last drop runs no `dispose`): the ticker
867    /// is freed and its scheduled frame callback is skipped.
868    #[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}