Skip to main content

waft_widgets/widgets/
scroll_activity.rs

1//! Flutter counterpart: `widgets/scroll_activity.dart`.
2
3use std::rc::Rc;
4use std::time::Duration;
5
6use waft_animation::{AnimationBehavior, AnimationController, Curve};
7use waft_embedder::PointerDeviceKind;
8use waft_foundation::{
9    App, Completer, CompleterFuture, Handle, HandleId, ListenableObject, Listener, OptionRetained,
10    PRECISION_ERROR_TOLERANCE, Retained,
11};
12use waft_gestures::{DragEndDetails, DragObject, DragStartDetails, DragUpdateDetails};
13use waft_painting::{AxisDirection, axis_direction_is_reversed};
14use waft_physics::Simulation;
15use waft_scheduler::TickerProvider;
16
17use crate::framework::{BuildContext, Notification};
18use crate::widgets::scroll_metrics::ScrollMetrics;
19use crate::widgets::scroll_notification::{
20    OverscrollNotification, ScrollEndNotification, ScrollStartNotification,
21    ScrollUpdateNotification,
22};
23use waft_foundation::Ref;
24
25/// A backend for a [`ScrollActivity`].
26///
27/// Used by implementors of [`ScrollActivity`] to manipulate the scroll view that
28/// they are acting upon.
29///
30/// See also:
31///
32///  * [`ScrollActivity`], which uses this trait as its delegate.
33///  * `ScrollPositionWithSingleContext`, the main implementation of this interface.
34pub trait ScrollActivityDelegate: Sized + 'static {
35    /// The direction in which the scroll view scrolls.
36    fn axis_direction(self: Handle<Self>, app: &App) -> AxisDirection;
37
38    /// Update the scroll position to the given pixel value.
39    ///
40    /// Returns the overscroll, if any. See `ScrollPosition::set_pixels` for more
41    /// information.
42    fn set_pixels(self: Handle<Self>, app: &mut App, pixels: f64) -> f64;
43
44    /// Updates the scroll position by the given amount.
45    ///
46    /// Appropriate for when the user is directly manipulating the scroll
47    /// position, for example by dragging the scroll view. Typically applies
48    /// [`crate::ScrollPhysics::apply_physics_to_user_offset`] and other transformations that
49    /// are appropriate for user-driving scrolling.
50    fn apply_user_offset(self: Handle<Self>, app: &mut App, delta: f64);
51
52    /// Terminate the current activity and start an idle activity.
53    fn go_idle(self: Handle<Self>, app: &mut App);
54
55    /// Terminate the current activity and start a ballistic activity with the
56    /// given velocity.
57    fn go_ballistic(self: Handle<Self>, app: &mut App, velocity: f64);
58
59    /// This delegate as the erased [`AnyScrollActivityDelegate`] — what to pass where a Dart
60    /// API takes a `ScrollActivityDelegate`.
61    fn as_scroll_activity_delegate(self: Handle<Self>) -> AnyScrollActivityDelegate {
62        AnyScrollActivityDelegate {
63            id: self.id(),
64            vtable: const { &ScrollActivityDelegateVTable::of::<Self>() },
65        }
66    }
67}
68
69/// The vtable of an erased [`AnyScrollActivityDelegate`].
70struct ScrollActivityDelegateVTable {
71    axis_direction: fn(&App, HandleId) -> AxisDirection,
72    set_pixels: fn(&mut App, HandleId, f64) -> f64,
73    apply_user_offset: fn(&mut App, HandleId, f64),
74    go_idle: fn(&mut App, HandleId),
75    go_ballistic: fn(&mut App, HandleId, f64),
76}
77
78/// The typed handle for an erased id. Free: nothing is looked up; `get` checks the slot.
79fn resolve<T: 'static>(id: HandleId) -> Handle<T> {
80    Handle::from_id(id)
81}
82
83impl ScrollActivityDelegateVTable {
84    /// The table for one concrete delegate type.
85    const fn of<D: ScrollActivityDelegate>() -> ScrollActivityDelegateVTable {
86        ScrollActivityDelegateVTable {
87            axis_direction: |app, id| D::axis_direction(resolve(id), app),
88            set_pixels: |app, id, pixels| D::set_pixels(resolve(id), app, pixels),
89            apply_user_offset: |app, id, delta| D::apply_user_offset(resolve(id), app, delta),
90            go_idle: |app, id| D::go_idle(resolve(id), app),
91            go_ballistic: |app, id, velocity| D::go_ballistic(resolve(id), app, velocity),
92        }
93    }
94}
95
96/// Erased [`ScrollActivityDelegate`]: one identity and a static vtable.
97///
98/// Equality is Dart's `==` on an object reference.
99#[derive(Clone, Copy)]
100pub struct AnyScrollActivityDelegate {
101    id: HandleId,
102    vtable: &'static ScrollActivityDelegateVTable,
103}
104
105impl AnyScrollActivityDelegate {
106    /// See [`ScrollActivityDelegate::axis_direction`].
107    pub fn axis_direction(self, app: &App) -> AxisDirection {
108        (self.vtable.axis_direction)(app, self.id)
109    }
110
111    /// See [`ScrollActivityDelegate::set_pixels`].
112    pub fn set_pixels(self, app: &mut App, pixels: f64) -> f64 {
113        (self.vtable.set_pixels)(app, self.id, pixels)
114    }
115
116    /// See [`ScrollActivityDelegate::apply_user_offset`].
117    pub fn apply_user_offset(self, app: &mut App, delta: f64) {
118        (self.vtable.apply_user_offset)(app, self.id, delta);
119    }
120
121    /// See [`ScrollActivityDelegate::go_idle`].
122    pub fn go_idle(self, app: &mut App) {
123        (self.vtable.go_idle)(app, self.id);
124    }
125
126    /// See [`ScrollActivityDelegate::go_ballistic`].
127    pub fn go_ballistic(self, app: &mut App, velocity: f64) {
128        (self.vtable.go_ballistic)(app, self.id, velocity);
129    }
130}
131
132impl PartialEq for AnyScrollActivityDelegate {
133    fn eq(&self, other: &AnyScrollActivityDelegate) -> bool {
134        self.id == other.id
135    }
136}
137
138impl Eq for AnyScrollActivityDelegate {}
139
140/// The fields of Dart's `ScrollActivity` base class, held under the field `scroll_activity`.
141pub struct ScrollActivityData {
142    delegate: AnyScrollActivityDelegate,
143    is_disposed: bool,
144}
145
146impl ScrollActivityData {
147    /// The bag of an activity that will actuate `delegate`.
148    pub fn new(delegate: AnyScrollActivityDelegate) -> ScrollActivityData {
149        ScrollActivityData {
150            delegate,
151            is_disposed: false,
152        }
153    }
154}
155
156/// The accessors [`ScrollActivity`] asks for, for a struct whose bag is the field
157/// `scroll_activity`.
158#[macro_export]
159macro_rules! scroll_activity_accessors {
160    () => {
161        fn scroll_activity_data(
162            self: ::waft_foundation::Handle<Self>,
163            app: &::waft_foundation::App,
164        ) -> &$crate::ScrollActivityData {
165            &app.get(self).scroll_activity
166        }
167
168        fn scroll_activity_data_mut(
169            self: ::waft_foundation::Handle<Self>,
170            app: &mut ::waft_foundation::App,
171        ) -> &mut $crate::ScrollActivityData {
172            &mut app.get_mut(self).scroll_activity
173        }
174    };
175}
176
177/// Base trait for scrolling activities like dragging and flinging.
178///
179/// The shared bodies live on [`ScrollActivityBase`], which an override calls where Dart
180/// writes `super.…`.
181///
182/// See also:
183///
184///  * `ScrollPosition`, which uses [`ScrollActivity`] objects to manage the
185///    `ScrollPosition` of a `Scrollable`.
186pub trait ScrollActivity: Sized + 'static {
187    /// Dart's `ScrollActivity` fields, held under the field `scroll_activity`
188    /// ([`scroll_activity_accessors!`](crate::scroll_activity_accessors)).
189    fn scroll_activity_data(self: Handle<Self>, app: &App) -> &ScrollActivityData;
190
191    /// See [`scroll_activity_data`](Self::scroll_activity_data).
192    fn scroll_activity_data_mut(self: Handle<Self>, app: &mut App) -> &mut ScrollActivityData;
193
194    /// The delegate that this activity will use to actuate the scroll view.
195    fn delegate(self: Handle<Self>, app: &App) -> AnyScrollActivityDelegate {
196        self.scroll_activity_data(app).delegate
197    }
198
199    /// Whether [`dispose`](Self::dispose) has run; Dart's `_isDisposed`.
200    fn is_disposed(self: Handle<Self>, app: &App) -> bool {
201        self.scroll_activity_data(app).is_disposed
202    }
203
204    /// Updates the activity's link to the [`ScrollActivityDelegate`].
205    ///
206    /// This should only be called when an activity is being moved from a defunct
207    /// (or about-to-be defunct) [`ScrollActivityDelegate`] object to a new one.
208    fn update_delegate(self: Handle<Self>, app: &mut App, value: AnyScrollActivityDelegate) {
209        debug_assert!(self.delegate(app) != value);
210        self.scroll_activity_data_mut(app).delegate = value;
211    }
212
213    /// Called by the [`ScrollActivityDelegate`] when it has changed type (for
214    /// example, when changing from an Android-style scroll position to an
215    /// iOS-style scroll position). If this activity can differ between the two
216    /// modes, then it should tell the position to restart that activity
217    /// appropriately.
218    ///
219    /// For example, [`BallisticScrollActivity`]'s implementation calls
220    /// [`ScrollActivityDelegate::go_ballistic`].
221    fn reset_activity(self: Handle<Self>, app: &mut App) {
222        let _ = (self, app);
223    }
224
225    /// Dispatch a [`ScrollStartNotification`] with the given metrics.
226    fn dispatch_scroll_start_notification(
227        self: Handle<Self>,
228        app: &mut App,
229        metrics: Rc<dyn ScrollMetrics>,
230        context: Option<BuildContext>,
231    ) {
232        ScrollActivityBase::dispatch_scroll_start_notification(app, metrics, context);
233    }
234
235    /// Dispatch a [`ScrollUpdateNotification`] with the given metrics and scroll delta.
236    fn dispatch_scroll_update_notification(
237        self: Handle<Self>,
238        app: &mut App,
239        metrics: Rc<dyn ScrollMetrics>,
240        context: BuildContext,
241        scroll_delta: f64,
242    ) {
243        ScrollActivityBase::dispatch_scroll_update_notification(
244            app,
245            metrics,
246            context,
247            scroll_delta,
248        );
249    }
250
251    /// Dispatch an [`OverscrollNotification`] with the given metrics and overscroll.
252    fn dispatch_overscroll_notification(
253        self: Handle<Self>,
254        app: &mut App,
255        metrics: Rc<dyn ScrollMetrics>,
256        context: BuildContext,
257        overscroll: f64,
258    ) {
259        ScrollActivityBase::dispatch_overscroll_notification(app, metrics, context, overscroll);
260    }
261
262    /// Dispatch a [`ScrollEndNotification`] with the given metrics and overscroll.
263    fn dispatch_scroll_end_notification(
264        self: Handle<Self>,
265        app: &mut App,
266        metrics: Rc<dyn ScrollMetrics>,
267        context: BuildContext,
268    ) {
269        ScrollActivityBase::dispatch_scroll_end_notification(app, metrics, context);
270    }
271
272    /// Called when the scroll view that is performing this activity changes its metrics.
273    fn apply_new_dimensions(self: Handle<Self>, app: &mut App) {
274        let _ = (self, app);
275    }
276
277    /// Whether the scroll view should ignore pointer events while performing this
278    /// activity.
279    ///
280    /// See also:
281    ///
282    ///  * [`is_scrolling`](Self::is_scrolling), which describes whether the activity is
283    ///    considered to represent user interaction or not.
284    fn should_ignore_pointer(self: Handle<Self>, app: &App) -> bool;
285
286    /// Whether performing this activity constitutes scrolling.
287    ///
288    /// Used, for example, to determine whether the user scroll
289    /// direction (see `ScrollPosition::user_scroll_direction`) is
290    /// [`waft_rendering::ScrollDirection::Idle`].
291    ///
292    /// See also:
293    ///
294    ///  * [`should_ignore_pointer`](Self::should_ignore_pointer), which controls whether
295    ///    pointer events are allowed while the activity is live.
296    ///  * [`crate::UserScrollNotification`], which exposes this status.
297    fn is_scrolling(self: Handle<Self>, app: &App) -> bool;
298
299    /// If applicable, the velocity at which the scroll offset is currently
300    /// independently changing (i.e. without external stimuli such as a dragging
301    /// gestures) in logical pixels per second for this activity.
302    fn velocity(self: Handle<Self>, app: &mut App) -> f64;
303
304    /// Called when the scroll view stops performing this activity.
305    fn dispose(self: Handle<Self>, app: &mut App) {
306        ScrollActivityBase::dispose(self, app);
307    }
308
309    /// Dart's `toString`, which reads the arena and so cannot be [`std::fmt::Debug`].
310    fn describe(self: Handle<Self>, app: &App) -> String {
311        let _ = app;
312        describe_identity::<Self>(self.id())
313    }
314
315    /// Dart's `activity is ScrollHoldController`; `None` — the default — for every activity
316    /// but [`HoldScrollActivity`].
317    fn as_hold_controller(self: Handle<Self>) -> Option<Rc<dyn ScrollHoldController>> {
318        let _ = self;
319        None
320    }
321
322    /// This activity as the erased [`AnyScrollActivity`] — what to pass where a Dart API takes
323    /// a `ScrollActivity`.
324    fn as_activity(self: Handle<Self>) -> AnyScrollActivity {
325        AnyScrollActivity {
326            id: self.id(),
327            vtable: const { &ScrollActivityVTable::of::<Self>() },
328        }
329    }
330}
331
332/// Dart's `describeIdentity`: the runtime type and a short identity hash.
333fn describe_identity<T: ?Sized>(id: HandleId) -> String {
334    let name = std::any::type_name::<T>();
335    let short = name.rsplit("::").next().unwrap_or(name);
336    format!("{short}#{id:?}")
337}
338
339/// The shared bodies of Dart's `ScrollActivity`: call one where Dart writes `super.…`.
340pub struct ScrollActivityBase;
341
342impl ScrollActivityBase {
343    /// See [`ScrollActivity::dispatch_scroll_start_notification`].
344    pub fn dispatch_scroll_start_notification(
345        app: &mut App,
346        metrics: Rc<dyn ScrollMetrics>,
347        context: Option<BuildContext>,
348    ) {
349        ScrollStartNotification::new(metrics, context).dispatch(app, context);
350    }
351
352    /// See [`ScrollActivity::dispatch_scroll_update_notification`].
353    pub fn dispatch_scroll_update_notification(
354        app: &mut App,
355        metrics: Rc<dyn ScrollMetrics>,
356        context: BuildContext,
357        scroll_delta: f64,
358    ) {
359        ScrollUpdateNotification::new(metrics, context)
360            .scroll_delta(scroll_delta)
361            .dispatch(app, Some(context));
362    }
363
364    /// See [`ScrollActivity::dispatch_overscroll_notification`].
365    pub fn dispatch_overscroll_notification(
366        app: &mut App,
367        metrics: Rc<dyn ScrollMetrics>,
368        context: BuildContext,
369        overscroll: f64,
370    ) {
371        OverscrollNotification::new(metrics, context, overscroll).dispatch(app, Some(context));
372    }
373
374    /// See [`ScrollActivity::dispatch_scroll_end_notification`].
375    pub fn dispatch_scroll_end_notification(
376        app: &mut App,
377        metrics: Rc<dyn ScrollMetrics>,
378        context: BuildContext,
379    ) {
380        ScrollEndNotification::new(metrics, context).dispatch(app, Some(context));
381    }
382
383    /// See [`ScrollActivity::dispose`].
384    pub fn dispose<A: ScrollActivity>(this: Handle<A>, app: &mut App) {
385        this.scroll_activity_data_mut(app).is_disposed = true;
386    }
387}
388
389/// The dispatch signature of [`ScrollActivity::dispatch_scroll_update_notification`].
390type DispatchDeltaFn = fn(&mut App, HandleId, Rc<dyn ScrollMetrics>, BuildContext, f64);
391
392/// The vtable of an erased [`AnyScrollActivity`]: one `&'static` table per concrete
393/// [`ScrollActivity`] type.
394struct ScrollActivityVTable {
395    delegate: fn(&App, HandleId) -> AnyScrollActivityDelegate,
396    is_disposed: fn(&App, HandleId) -> bool,
397    update_delegate: fn(&mut App, HandleId, AnyScrollActivityDelegate),
398    reset_activity: fn(&mut App, HandleId),
399    dispatch_scroll_start_notification:
400        fn(&mut App, HandleId, Rc<dyn ScrollMetrics>, Option<BuildContext>),
401    dispatch_scroll_update_notification: DispatchDeltaFn,
402    dispatch_overscroll_notification: DispatchDeltaFn,
403    dispatch_scroll_end_notification: fn(&mut App, HandleId, Rc<dyn ScrollMetrics>, BuildContext),
404    apply_new_dimensions: fn(&mut App, HandleId),
405    should_ignore_pointer: fn(&App, HandleId) -> bool,
406    is_scrolling: fn(&App, HandleId) -> bool,
407    velocity: fn(&mut App, HandleId) -> f64,
408    dispose: fn(&mut App, HandleId),
409    describe: fn(&App, HandleId) -> String,
410    as_hold_controller: fn(HandleId) -> Option<Rc<dyn ScrollHoldController>>,
411}
412
413impl ScrollActivityVTable {
414    /// The table for one concrete activity type.
415    const fn of<A: ScrollActivity>() -> ScrollActivityVTable {
416        ScrollActivityVTable {
417            delegate: |app, id| A::delegate(resolve(id), app),
418            is_disposed: |app, id| A::is_disposed(resolve(id), app),
419            update_delegate: |app, id, value| A::update_delegate(resolve(id), app, value),
420            reset_activity: |app, id| A::reset_activity(resolve(id), app),
421            dispatch_scroll_start_notification: |app, id, metrics, context| {
422                A::dispatch_scroll_start_notification(resolve(id), app, metrics, context);
423            },
424            dispatch_scroll_update_notification: |app, id, metrics, context, delta| {
425                A::dispatch_scroll_update_notification(resolve(id), app, metrics, context, delta);
426            },
427            dispatch_overscroll_notification: |app, id, metrics, context, overscroll| {
428                A::dispatch_overscroll_notification(resolve(id), app, metrics, context, overscroll);
429            },
430            dispatch_scroll_end_notification: |app, id, metrics, context| {
431                A::dispatch_scroll_end_notification(resolve(id), app, metrics, context);
432            },
433            apply_new_dimensions: |app, id| A::apply_new_dimensions(resolve(id), app),
434            should_ignore_pointer: |app, id| A::should_ignore_pointer(resolve(id), app),
435            is_scrolling: |app, id| A::is_scrolling(resolve(id), app),
436            velocity: |app, id| A::velocity(resolve(id), app),
437            dispose: |app, id| A::dispose(resolve(id), app),
438            describe: |app, id| A::describe(resolve(id), app),
439            as_hold_controller: |id| A::as_hold_controller(resolve(id)),
440        }
441    }
442}
443
444/// Erased [`ScrollActivity`]: what a field or parameter Dart types as `ScrollActivity`
445/// becomes.
446///
447/// Equality is Dart's `==` on an object reference.
448#[derive(Clone, Copy)]
449pub struct AnyScrollActivity {
450    id: HandleId,
451    vtable: &'static ScrollActivityVTable,
452}
453
454/// A field Dart types as the erased object, kept: AnyScrollActivity with its count.
455pub type ScrollActivityRef = Retained<AnyScrollActivity>;
456
457waft_foundation::erased_handle!(AnyScrollActivity: ScrollActivity => ScrollActivity::as_activity);
458
459impl AnyScrollActivity {
460    /// See [`ScrollActivity::delegate`].
461    pub fn delegate(self, app: &App) -> AnyScrollActivityDelegate {
462        (self.vtable.delegate)(app, self.id)
463    }
464
465    /// See [`ScrollActivity::is_disposed`].
466    pub fn is_disposed(self, app: &App) -> bool {
467        (self.vtable.is_disposed)(app, self.id)
468    }
469
470    /// See [`ScrollActivity::update_delegate`].
471    pub fn update_delegate(self, app: &mut App, value: AnyScrollActivityDelegate) {
472        (self.vtable.update_delegate)(app, self.id, value);
473    }
474
475    /// See [`ScrollActivity::reset_activity`].
476    pub fn reset_activity(self, app: &mut App) {
477        (self.vtable.reset_activity)(app, self.id);
478    }
479
480    /// See [`ScrollActivity::dispatch_scroll_start_notification`].
481    pub fn dispatch_scroll_start_notification(
482        self,
483        app: &mut App,
484        metrics: Rc<dyn ScrollMetrics>,
485        context: Option<BuildContext>,
486    ) {
487        (self.vtable.dispatch_scroll_start_notification)(app, self.id, metrics, context);
488    }
489
490    /// See [`ScrollActivity::dispatch_scroll_update_notification`].
491    pub fn dispatch_scroll_update_notification(
492        self,
493        app: &mut App,
494        metrics: Rc<dyn ScrollMetrics>,
495        context: BuildContext,
496        scroll_delta: f64,
497    ) {
498        (self.vtable.dispatch_scroll_update_notification)(
499            app,
500            self.id,
501            metrics,
502            context,
503            scroll_delta,
504        );
505    }
506
507    /// See [`ScrollActivity::dispatch_overscroll_notification`].
508    pub fn dispatch_overscroll_notification(
509        self,
510        app: &mut App,
511        metrics: Rc<dyn ScrollMetrics>,
512        context: BuildContext,
513        overscroll: f64,
514    ) {
515        (self.vtable.dispatch_overscroll_notification)(app, self.id, metrics, context, overscroll);
516    }
517
518    /// See [`ScrollActivity::dispatch_scroll_end_notification`].
519    pub fn dispatch_scroll_end_notification(
520        self,
521        app: &mut App,
522        metrics: Rc<dyn ScrollMetrics>,
523        context: BuildContext,
524    ) {
525        (self.vtable.dispatch_scroll_end_notification)(app, self.id, metrics, context);
526    }
527
528    /// See [`ScrollActivity::apply_new_dimensions`].
529    pub fn apply_new_dimensions(self, app: &mut App) {
530        (self.vtable.apply_new_dimensions)(app, self.id);
531    }
532
533    /// See [`ScrollActivity::should_ignore_pointer`].
534    pub fn should_ignore_pointer(self, app: &App) -> bool {
535        (self.vtable.should_ignore_pointer)(app, self.id)
536    }
537
538    /// See [`ScrollActivity::is_scrolling`].
539    pub fn is_scrolling(self, app: &App) -> bool {
540        (self.vtable.is_scrolling)(app, self.id)
541    }
542
543    /// See [`ScrollActivity::velocity`].
544    pub fn velocity(self, app: &mut App) -> f64 {
545        (self.vtable.velocity)(app, self.id)
546    }
547
548    /// See [`ScrollActivity::dispose`].
549    pub fn dispose(self, app: &mut App) {
550        (self.vtable.dispose)(app, self.id);
551    }
552
553    /// See [`ScrollActivity::describe`].
554    pub fn describe(self, app: &App) -> String {
555        (self.vtable.describe)(app, self.id)
556    }
557
558    /// Dart's `activity is ScrollHoldController`.
559    pub fn as_hold_controller(self) -> Option<Rc<dyn ScrollHoldController>> {
560        (self.vtable.as_hold_controller)(self.id)
561    }
562}
563
564/// A scroll activity that does nothing.
565///
566/// When a scroll view is not scrolling, it is performing the idle activity.
567///
568/// If the `Scrollable` changes dimensions, this activity triggers a ballistic
569/// activity to restore the view.
570pub struct IdleScrollActivity {
571    scroll_activity: ScrollActivityData,
572}
573
574impl IdleScrollActivity {
575    /// Creates a scroll activity that does nothing.
576    pub fn new(app: &mut App, delegate: AnyScrollActivityDelegate) -> Ref<IdleScrollActivity> {
577        app.create(IdleScrollActivity {
578            scroll_activity: ScrollActivityData::new(delegate),
579        })
580    }
581}
582
583impl ScrollActivity for IdleScrollActivity {
584    crate::scroll_activity_accessors!();
585
586    fn apply_new_dimensions(self: Handle<Self>, app: &mut App) {
587        self.delegate(app).go_ballistic(app, 0.0);
588    }
589
590    fn should_ignore_pointer(self: Handle<Self>, _app: &App) -> bool {
591        false
592    }
593
594    fn is_scrolling(self: Handle<Self>, _app: &App) -> bool {
595        false
596    }
597
598    fn velocity(self: Handle<Self>, _app: &mut App) -> f64 {
599        0.0
600    }
601}
602
603/// Interface for holding a `Scrollable` stationary.
604///
605/// An object that implements this interface is returned by
606/// `ScrollPosition::hold`. It holds the scrollable stationary until an activity
607/// is started or the [`cancel`](Self::cancel) method is called.
608///
609/// What Dart types as `ScrollHoldController` becomes an `Rc<dyn ScrollHoldController>`; an
610/// arena object implements [`ScrollHoldControllerObject`], and `Rc::new(handle)` is its erased
611/// form.
612pub trait ScrollHoldController {
613    /// Release the `Scrollable`, potentially letting it go ballistic if
614    /// necessary.
615    fn cancel(&self, app: &mut App);
616}
617
618/// The object side of [`ScrollHoldController`]: an arena object that holds a scrollable.
619/// Implementing it makes `Handle<Self>` a [`ScrollHoldController`].
620pub trait ScrollHoldControllerObject: Sized + 'static {
621    /// See [`ScrollHoldController::cancel`].
622    fn cancel(self: Handle<Self>, app: &mut App);
623}
624
625impl<T: ScrollHoldControllerObject> ScrollHoldController for Handle<T> {
626    fn cancel(&self, app: &mut App) {
627        T::cancel(*self, app);
628    }
629}
630
631/// A kept hold: what `ScrollPosition::hold` hands back, which the caller keeps until it cancels.
632impl<T: ScrollHoldControllerObject> ScrollHoldController for Ref<T> {
633    fn cancel(&self, app: &mut App) {
634        T::cancel(self.handle(), app);
635    }
636}
637
638/// A scroll activity that does nothing but can be released to resume
639/// normal idle behavior.
640///
641/// This is used while the user is touching the `Scrollable` but before the
642/// touch has become a [`waft_gestures::Drag`].
643///
644/// For the purposes of `ScrollNotification`s, this activity does not constitute
645/// scrolling, and does not prevent the user from interacting with the contents
646/// of the `Scrollable` (unlike when a drag has begun or there is a scroll
647/// animation underway).
648pub struct HoldScrollActivity {
649    scroll_activity: ScrollActivityData,
650    /// Called when [`ScrollActivity::dispose`] is called.
651    pub on_hold_canceled: Option<Listener>,
652}
653
654impl HoldScrollActivity {
655    /// Creates a scroll activity that does nothing.
656    pub fn new(
657        app: &mut App,
658        delegate: AnyScrollActivityDelegate,
659        on_hold_canceled: Option<Listener>,
660    ) -> Ref<HoldScrollActivity> {
661        app.create(HoldScrollActivity {
662            scroll_activity: ScrollActivityData::new(delegate),
663            on_hold_canceled,
664        })
665    }
666}
667
668impl ScrollActivity for HoldScrollActivity {
669    crate::scroll_activity_accessors!();
670
671    fn should_ignore_pointer(self: Handle<Self>, _app: &App) -> bool {
672        false
673    }
674
675    fn is_scrolling(self: Handle<Self>, _app: &App) -> bool {
676        false
677    }
678
679    fn velocity(self: Handle<Self>, _app: &mut App) -> f64 {
680        0.0
681    }
682
683    fn dispose(self: Handle<Self>, app: &mut App) {
684        if let Some(on_hold_canceled) = app.get(self).on_hold_canceled.clone() {
685            on_hold_canceled.call(app);
686        }
687        ScrollActivityBase::dispose(self, app);
688    }
689
690    fn as_hold_controller(self: Handle<Self>) -> Option<Rc<dyn ScrollHoldController>> {
691        Some(Rc::new(self))
692    }
693}
694
695impl ScrollHoldControllerObject for HoldScrollActivity {
696    fn cancel(self: Handle<Self>, app: &mut App) {
697        self.delegate(app).go_ballistic(app, 0.0);
698    }
699}
700
701/// The most recently observed drag details; Dart's `dynamic ScrollDragController.lastDetails`.
702#[derive(Clone)]
703pub enum LastDragDetails {
704    /// The drag has started and has not moved yet.
705    Start(DragStartDetails),
706    /// The drag has moved.
707    Update(DragUpdateDetails),
708    /// The drag has ended.
709    End(DragEndDetails),
710}
711
712/// Scrolls a scroll view as the user drags their finger across the screen.
713///
714/// See also:
715///
716///  * [`DragScrollActivity`], which is the activity the scroll view performs
717///    while a drag is underway.
718pub struct ScrollDragController {
719    delegate: AnyScrollActivityDelegate,
720
721    /// Called when [`dispose`](Self::dispose) is called.
722    pub on_drag_canceled: Option<Listener>,
723
724    /// Velocity that was present from a previous [`ScrollActivity`] when this drag
725    /// began.
726    pub carried_velocity: Option<f64>,
727
728    /// Amount of pixels in either direction the drag has to move by to start
729    /// scroll movement again after each time scrolling came to a stop.
730    pub motion_start_distance_threshold: Option<f64>,
731
732    last_non_stationary_timestamp: Option<Duration>,
733    retain_momentum: bool,
734    /// `None` if already in motion or has no
735    /// [`motion_start_distance_threshold`](Self::motion_start_distance_threshold).
736    offset_since_last_stop: Option<f64>,
737    kind: Option<PointerDeviceKind>,
738    last_details: Option<LastDragDetails>,
739}
740
741impl ScrollDragController {
742    /// Maximum amount of time interval the drag can have consecutive stationary
743    /// pointer update events before losing the momentum carried from a previous
744    /// scroll activity.
745    pub const MOMENTUM_RETAIN_STATIONARY_DURATION_THRESHOLD: Duration = Duration::from_millis(20);
746
747    /// The minimum amount of velocity needed to apply the
748    /// [`carried_velocity`](Self::carried_velocity) at the end of a drag. Expressed as a
749    /// factor. For example with a [`carried_velocity`](Self::carried_velocity) of 2000, we
750    /// will need a velocity of at least 1000 to apply the
751    /// [`carried_velocity`](Self::carried_velocity) as well. If the velocity does not meet
752    /// the threshold, the [`carried_velocity`](Self::carried_velocity) is lost. Decided by
753    /// fair eyeballing with the scroll_overlay platform test.
754    pub const MOMENTUM_RETAIN_VELOCITY_THRESHOLD_FACTOR: f64 = 0.5;
755
756    /// Maximum amount of time interval the drag can have consecutive stationary
757    /// pointer update events before needing to break the
758    /// [`motion_start_distance_threshold`](Self::motion_start_distance_threshold) to start
759    /// motion again.
760    pub const MOTION_STOPPED_DURATION_THRESHOLD: Duration = Duration::from_millis(50);
761
762    /// The drag distance past which, a
763    /// [`motion_start_distance_threshold`](Self::motion_start_distance_threshold) breaking
764    /// drag is considered a deliberate fling.
765    const BIG_THRESHOLD_BREAK_DISTANCE: f64 = 24.0;
766
767    /// Creates an object that scrolls a scroll view as the user drags their
768    /// finger across the screen.
769    pub fn new(
770        app: &mut App,
771        delegate: AnyScrollActivityDelegate,
772        details: DragStartDetails,
773        on_drag_canceled: Option<Listener>,
774        carried_velocity: Option<f64>,
775        motion_start_distance_threshold: Option<f64>,
776    ) -> Ref<ScrollDragController> {
777        debug_assert!(
778            motion_start_distance_threshold.is_none_or(|threshold| threshold > 0.0),
779            "motionStartDistanceThreshold must be a positive number or null"
780        );
781        app.create(ScrollDragController {
782            delegate,
783            on_drag_canceled,
784            carried_velocity,
785            motion_start_distance_threshold,
786            last_non_stationary_timestamp: details.source_time_stamp,
787            retain_momentum: carried_velocity.is_some_and(|velocity| velocity != 0.0),
788            offset_since_last_stop: motion_start_distance_threshold.map(|_| 0.0),
789            kind: details.kind,
790            last_details: Some(LastDragDetails::Start(details)),
791        })
792    }
793
794    /// The object that will actuate the scroll view as the user drags.
795    pub fn delegate(self: Handle<Self>, app: &App) -> AnyScrollActivityDelegate {
796        app.get(self).delegate
797    }
798
799    /// The type of input device driving the drag; Dart's `_kind`.
800    pub fn kind(self: Handle<Self>, app: &App) -> Option<PointerDeviceKind> {
801        app.get(self).kind
802    }
803
804    /// The most recently observed [`DragStartDetails`], [`DragUpdateDetails`], or
805    /// [`DragEndDetails`] object.
806    pub fn last_details(self: Handle<Self>, app: &App) -> Option<&LastDragDetails> {
807        app.get(self).last_details.as_ref()
808    }
809
810    /// Updates the controller's link to the [`ScrollActivityDelegate`].
811    ///
812    /// This should only be called when a controller is being moved from a defunct
813    /// (or about-to-be defunct) [`ScrollActivityDelegate`] object to a new one.
814    pub fn update_delegate(self: Handle<Self>, app: &mut App, value: AnyScrollActivityDelegate) {
815        debug_assert!(app.get(self).delegate != value);
816        app.get_mut(self).delegate = value;
817    }
818
819    /// Called by the delegate when it is no longer sending events to this object.
820    pub fn dispose(self: Handle<Self>, app: &mut App) {
821        app.get_mut(self).last_details = None;
822        if let Some(on_drag_canceled) = app.get(self).on_drag_canceled.clone() {
823            on_drag_canceled.call(app);
824        }
825    }
826
827    /// Dart's `toString`, which reads the arena and so cannot be [`std::fmt::Debug`].
828    pub fn describe(self: Handle<Self>) -> String {
829        describe_identity::<ScrollDragController>(self.id())
830    }
831
832    fn reversed(self: Handle<Self>, app: &App) -> bool {
833        axis_direction_is_reversed(self.delegate(app).axis_direction(app))
834    }
835
836    /// Determines whether to lose the existing incoming velocity when starting
837    /// the drag.
838    fn maybe_lose_momentum(
839        self: Handle<Self>,
840        app: &mut App,
841        offset: f64,
842        timestamp: Option<Duration>,
843    ) {
844        let controller = app.get(self);
845        if controller.retain_momentum
846            && offset == 0.0
847            && timestamp.is_none_or(|timestamp| {
848                // If drag event has no timestamp, we lose momentum.
849                timestamp.saturating_sub(
850                    controller
851                        .last_non_stationary_timestamp
852                        .expect("a retained momentum carries a timestamp"),
853                ) > Self::MOMENTUM_RETAIN_STATIONARY_DURATION_THRESHOLD
854            })
855        {
856            // If pointer is stationary for too long, we lose momentum.
857            app.get_mut(self).retain_momentum = false;
858        }
859    }
860
861    /// If a motion start threshold exists, determine whether the threshold needs
862    /// to be broken to scroll. Also possibly apply an offset adjustment when
863    /// threshold is first broken.
864    ///
865    /// Returns `0.0` when stationary or within threshold. Returns `offset`
866    /// transparently when already in motion.
867    fn adjust_for_scroll_start_threshold(
868        self: Handle<Self>,
869        app: &mut App,
870        offset: f64,
871        timestamp: Option<Duration>,
872    ) -> f64 {
873        let Some(timestamp) = timestamp else {
874            // If we can't track time, we can't apply thresholds.
875            // May be null for proxied drags like via accessibility.
876            return offset;
877        };
878        let controller = app.get(self);
879        let threshold = controller.motion_start_distance_threshold;
880        if offset == 0.0 {
881            if threshold.is_some()
882                && controller.offset_since_last_stop.is_none()
883                && timestamp.saturating_sub(
884                    controller
885                        .last_non_stationary_timestamp
886                        .expect("a stationary update follows a timestamped one"),
887                ) > Self::MOTION_STOPPED_DURATION_THRESHOLD
888            {
889                // Enforce a new threshold.
890                app.get_mut(self).offset_since_last_stop = Some(0.0);
891            }
892            // Not moving can't break threshold.
893            0.0
894        } else {
895            let Some(offset_since_last_stop) = controller.offset_since_last_stop else {
896                // Already in motion or no threshold behavior configured such as for
897                // Android. Allow transparent offset transmission.
898                return offset;
899            };
900            let offset_since_last_stop = offset_since_last_stop + offset;
901            app.get_mut(self).offset_since_last_stop = Some(offset_since_last_stop);
902            let threshold = threshold.expect("an offset since the last stop implies a threshold");
903            if offset_since_last_stop.abs() > threshold {
904                // Threshold broken.
905                app.get_mut(self).offset_since_last_stop = None;
906                if offset.abs() > Self::BIG_THRESHOLD_BREAK_DISTANCE {
907                    // This is heuristically a very deliberate fling. Leave the motion
908                    // unaffected.
909                    offset
910                } else {
911                    // This is a normal speed threshold break.
912                    // Ease into the motion when the threshold is initially broken
913                    // to avoid a visible jump.
914                    (threshold / 3.0).min(offset.abs()) * offset.signum()
915                }
916            } else {
917                0.0
918            }
919        }
920    }
921}
922
923impl DragObject for ScrollDragController {
924    fn update(self: Handle<Self>, app: &mut App, details: DragUpdateDetails) {
925        debug_assert!(details.primary_delta.is_some());
926        let mut offset = details.primary_delta.expect("a primary delta");
927        let source_time_stamp = details.source_time_stamp;
928        app.get_mut(self).last_details = Some(LastDragDetails::Update(details));
929        if offset != 0.0 {
930            app.get_mut(self).last_non_stationary_timestamp = source_time_stamp;
931        }
932        // By default, iOS platforms carries momentum and has a start threshold
933        // (configured in `BouncingScrollPhysics`). The 2 operations below are
934        // no-ops on Android.
935        self.maybe_lose_momentum(app, offset, source_time_stamp);
936        offset = self.adjust_for_scroll_start_threshold(app, offset, source_time_stamp);
937        if offset == 0.0 {
938            return;
939        }
940        if self.reversed(app) {
941            offset = -offset;
942        }
943        self.delegate(app).apply_user_offset(app, offset);
944    }
945
946    fn end(self: Handle<Self>, app: &mut App, details: DragEndDetails) {
947        debug_assert!(details.primary_velocity.is_some());
948        // We negate the velocity here because if the touch is moving downwards,
949        // the scroll has to move upwards. It's the same reason that `update`
950        // above negates the delta before applying it to the scroll offset.
951        let mut velocity = -details.primary_velocity.expect("a primary velocity");
952        if self.reversed(app) {
953            velocity = -velocity;
954        }
955        app.get_mut(self).last_details = Some(LastDragDetails::End(details));
956
957        let controller = app.get(self);
958        if controller.retain_momentum {
959            let carried_velocity = controller
960                .carried_velocity
961                .expect("a retained momentum carries a velocity");
962            // Build momentum only if dragging in the same direction.
963            let is_flinging_in_same_direction = velocity.signum() == carried_velocity.signum();
964            // Build momentum only if the velocity of the last drag was not
965            // substantially lower than the carried momentum.
966            let is_velocity_not_substantially_less_than_carried_momentum = velocity.abs()
967                > carried_velocity.abs() * Self::MOMENTUM_RETAIN_VELOCITY_THRESHOLD_FACTOR;
968            if is_flinging_in_same_direction
969                && is_velocity_not_substantially_less_than_carried_momentum
970            {
971                velocity += carried_velocity;
972            }
973        }
974        self.delegate(app).go_ballistic(app, velocity);
975    }
976
977    fn cancel(self: Handle<Self>, app: &mut App) {
978        self.delegate(app).go_ballistic(app, 0.0);
979    }
980}
981
982/// The activity a scroll view performs when the user drags their finger
983/// across the screen.
984///
985/// See also:
986///
987///  * [`ScrollDragController`], which listens to the [`waft_gestures::Drag`] and actually scrolls
988///    the scroll view.
989pub struct DragScrollActivity {
990    scroll_activity: ScrollActivityData,
991    controller: Option<Ref<ScrollDragController>>,
992}
993
994impl DragScrollActivity {
995    /// Creates an activity for when the user drags their finger across the
996    /// screen.
997    pub fn new(
998        app: &mut App,
999        delegate: AnyScrollActivityDelegate,
1000        controller: Ref<ScrollDragController>,
1001    ) -> Ref<DragScrollActivity> {
1002        app.create(DragScrollActivity {
1003            scroll_activity: ScrollActivityData::new(delegate),
1004            controller: Some(controller),
1005        })
1006    }
1007
1008    fn controller(self: Handle<Self>, app: &App) -> Handle<ScrollDragController> {
1009        app.get(self)
1010            .controller
1011            .handle()
1012            .expect("the drag activity outlives its controller")
1013    }
1014}
1015
1016impl ScrollActivity for DragScrollActivity {
1017    crate::scroll_activity_accessors!();
1018
1019    fn dispatch_scroll_start_notification(
1020        self: Handle<Self>,
1021        app: &mut App,
1022        metrics: Rc<dyn ScrollMetrics>,
1023        context: Option<BuildContext>,
1024    ) {
1025        let last_details = self.controller(app).last_details(app).cloned();
1026        let Some(LastDragDetails::Start(drag_details)) = last_details else {
1027            unreachable!("a drag activity starts with its start details");
1028        };
1029        ScrollStartNotification::new(metrics, context)
1030            .drag_details(drag_details)
1031            .dispatch(app, context);
1032    }
1033
1034    fn dispatch_scroll_update_notification(
1035        self: Handle<Self>,
1036        app: &mut App,
1037        metrics: Rc<dyn ScrollMetrics>,
1038        context: BuildContext,
1039        scroll_delta: f64,
1040    ) {
1041        let last_details = self.controller(app).last_details(app).cloned();
1042        let Some(LastDragDetails::Update(drag_details)) = last_details else {
1043            unreachable!("a drag update carries its update details");
1044        };
1045        ScrollUpdateNotification::new(metrics, context)
1046            .scroll_delta(scroll_delta)
1047            .drag_details(drag_details)
1048            .dispatch(app, Some(context));
1049    }
1050
1051    fn dispatch_overscroll_notification(
1052        self: Handle<Self>,
1053        app: &mut App,
1054        metrics: Rc<dyn ScrollMetrics>,
1055        context: BuildContext,
1056        overscroll: f64,
1057    ) {
1058        let last_details = self.controller(app).last_details(app).cloned();
1059        let Some(LastDragDetails::Update(drag_details)) = last_details else {
1060            unreachable!("an overscroll follows an update");
1061        };
1062        OverscrollNotification::new(metrics, context, overscroll)
1063            .drag_details(drag_details)
1064            .dispatch(app, Some(context));
1065    }
1066
1067    fn dispatch_scroll_end_notification(
1068        self: Handle<Self>,
1069        app: &mut App,
1070        metrics: Rc<dyn ScrollMetrics>,
1071        context: BuildContext,
1072    ) {
1073        // We might not have DragEndDetails yet if we're being called from `begin_activity`.
1074        let last_details = self.controller(app).last_details(app).cloned();
1075        let mut notification = ScrollEndNotification::new(metrics, context);
1076        if let Some(LastDragDetails::End(drag_details)) = last_details {
1077            notification = notification.drag_details(drag_details);
1078        }
1079        notification.dispatch(app, Some(context));
1080    }
1081
1082    fn should_ignore_pointer(self: Handle<Self>, app: &App) -> bool {
1083        app.get(self)
1084            .controller
1085            .as_ref()
1086            .and_then(|controller| controller.kind(app))
1087            != Some(PointerDeviceKind::Trackpad)
1088    }
1089
1090    fn is_scrolling(self: Handle<Self>, _app: &App) -> bool {
1091        true
1092    }
1093
1094    /// [`DragScrollActivity`] is not independently changing velocity yet
1095    /// until the drag is ended.
1096    fn velocity(self: Handle<Self>, _app: &mut App) -> f64 {
1097        0.0
1098    }
1099
1100    fn dispose(self: Handle<Self>, app: &mut App) {
1101        app.get_mut(self).controller = None;
1102        ScrollActivityBase::dispose(self, app);
1103    }
1104
1105    fn describe(self: Handle<Self>, app: &App) -> String {
1106        let controller = app.get(self).controller.handle();
1107        let described =
1108            controller.map_or_else(|| "null".to_string(), ScrollDragController::describe);
1109        format!(
1110            "{}({described})",
1111            describe_identity::<DragScrollActivity>(self.id())
1112        )
1113    }
1114}
1115
1116/// The activity a scroll view performs after being set into motion.
1117///
1118/// For example, a [`BallisticScrollActivity`] is used when the user
1119/// lifts their finger off the screen after a [`DragScrollActivity`],
1120/// to continue the scrolling motion starting from the current velocity.
1121///
1122/// [`BallisticScrollActivity`] is also used to restore a scroll view to a valid
1123/// scroll offset when the geometry of the scroll view changes. In these
1124/// situations, the [`Simulation`] typically starts with a zero velocity.
1125///
1126/// The scrolling will be driven by the given [`Simulation`]. If a
1127/// [`BallisticScrollActivity`] is in progress when the scroll metrics change,
1128/// then the activity will be replaced with a new ballistic activity starting
1129/// from the current velocity (see [`crate::ScrollPhysics::create_ballistic_simulation`]).
1130/// To ensure the user perceives smooth motion across such a change,
1131/// the simulation should typically be the result
1132/// of [`crate::ScrollPhysics::create_ballistic_simulation`]
1133/// for the scroll physics of the scroll view.
1134///
1135/// See also:
1136///
1137///  * [`DrivenScrollActivity`], which drives a scroll view through
1138///    a given animation, without resetting to a ballistic simulation
1139///    when scroll metrics change.
1140pub struct BallisticScrollActivity {
1141    scroll_activity: ScrollActivityData,
1142    controller: Ref<AnimationController>,
1143    should_ignore_pointer: bool,
1144}
1145
1146impl BallisticScrollActivity {
1147    /// Creates an activity that sets into motion a scroll view.
1148    ///
1149    /// The simulation should typically be the result
1150    /// of [`crate::ScrollPhysics::create_ballistic_simulation`]
1151    /// for the scroll physics of the scroll view.
1152    pub fn new(
1153        app: &mut App,
1154        delegate: AnyScrollActivityDelegate,
1155        simulation: Box<dyn Simulation>,
1156        vsync: impl TickerProvider,
1157        should_ignore_pointer: bool,
1158    ) -> Ref<BallisticScrollActivity> {
1159        let controller = AnimationController::unbounded(
1160            app,
1161            0.0,
1162            None,
1163            None,
1164            AnimationBehavior::Preserve,
1165            vsync,
1166        );
1167        let this = app.create(BallisticScrollActivity {
1168            scroll_activity: ScrollActivityData::new(delegate),
1169            controller: controller.clone(),
1170            should_ignore_pointer,
1171        });
1172        controller.add_listener(app, Listener::handle_method(this.handle(), Self::tick));
1173        let done = controller.animate_with(app, simulation);
1174        // Won't trigger if we dispose the controller before it completes.
1175        done.when_complete(app, Listener::handle_method(this.handle(), Self::end));
1176        this
1177    }
1178
1179    fn tick(self: Handle<Self>, app: &mut App) {
1180        let value = app.get(self).controller.value(app);
1181        if !self.apply_move_to(app, value) {
1182            self.delegate(app).go_idle(app);
1183        }
1184    }
1185
1186    /// Move the position to the given location.
1187    ///
1188    /// If the new position was fully applied, returns true. If there was any
1189    /// overflow, returns false.
1190    ///
1191    /// The default implementation calls [`ScrollActivityDelegate::set_pixels`]
1192    /// and returns true if the overflow was zero.
1193    pub fn apply_move_to(self: Handle<Self>, app: &mut App, value: f64) -> bool {
1194        self.delegate(app).set_pixels(app, value).abs() < PRECISION_ERROR_TOLERANCE
1195    }
1196
1197    fn end(self: Handle<Self>, app: &mut App) {
1198        // Check if the activity was disposed before going ballistic because `end` might be
1199        // called if the controller is disposed just after completion.
1200        if !self.is_disposed(app) {
1201            self.delegate(app).go_ballistic(app, 0.0);
1202        }
1203    }
1204}
1205
1206impl ScrollActivity for BallisticScrollActivity {
1207    crate::scroll_activity_accessors!();
1208
1209    fn reset_activity(self: Handle<Self>, app: &mut App) {
1210        let velocity = self.velocity(app);
1211        self.delegate(app).go_ballistic(app, velocity);
1212    }
1213
1214    fn apply_new_dimensions(self: Handle<Self>, app: &mut App) {
1215        let velocity = self.velocity(app);
1216        self.delegate(app).go_ballistic(app, velocity);
1217    }
1218
1219    fn dispatch_overscroll_notification(
1220        self: Handle<Self>,
1221        app: &mut App,
1222        metrics: Rc<dyn ScrollMetrics>,
1223        context: BuildContext,
1224        overscroll: f64,
1225    ) {
1226        let velocity = self.velocity(app);
1227        OverscrollNotification::new(metrics, context, overscroll)
1228            .velocity(velocity)
1229            .dispatch(app, Some(context));
1230    }
1231
1232    fn should_ignore_pointer(self: Handle<Self>, app: &App) -> bool {
1233        app.get(self).should_ignore_pointer
1234    }
1235
1236    fn is_scrolling(self: Handle<Self>, _app: &App) -> bool {
1237        true
1238    }
1239
1240    fn velocity(self: Handle<Self>, app: &mut App) -> f64 {
1241        app.get(self).controller.velocity(app)
1242    }
1243
1244    fn dispose(self: Handle<Self>, app: &mut App) {
1245        app.get(self).controller.dispose(app);
1246        ScrollActivityBase::dispose(self, app);
1247    }
1248
1249    fn describe(self: Handle<Self>, app: &App) -> String {
1250        format!(
1251            "{}({:?})",
1252            describe_identity::<BallisticScrollActivity>(self.id()),
1253            app.get(self).controller.id()
1254        )
1255    }
1256}
1257
1258/// An activity that drives a scroll view through a given animation.
1259///
1260/// For example, a [`DrivenScrollActivity`] is used to implement
1261/// `ScrollController::animate_to`.
1262///
1263/// The scrolling will be driven by the given animation parameters
1264/// or the given [`Simulation`].
1265///
1266/// Unlike a [`BallisticScrollActivity`], if a [`DrivenScrollActivity`] is
1267/// in progress when the scroll metrics change, the activity will continue
1268/// with its original animation.
1269///
1270/// See also:
1271///
1272///  * [`BallisticScrollActivity`], which sets into motion a scroll view.
1273pub struct DrivenScrollActivity {
1274    scroll_activity: ScrollActivityData,
1275    completer: Completer<()>,
1276    controller: Ref<AnimationController>,
1277}
1278
1279impl DrivenScrollActivity {
1280    /// Creates an activity that drives a scroll view through an animation
1281    /// given by animation parameters.
1282    pub fn new(
1283        app: &mut App,
1284        delegate: AnyScrollActivityDelegate,
1285        from: f64,
1286        to: f64,
1287        duration: Duration,
1288        curve: Rc<dyn Curve>,
1289        vsync: impl TickerProvider,
1290    ) -> Ref<DrivenScrollActivity> {
1291        debug_assert!(duration > Duration::ZERO);
1292        let completer = Completer::new();
1293        let controller = AnimationController::unbounded(
1294            app,
1295            from,
1296            None,
1297            None,
1298            AnimationBehavior::Preserve,
1299            vsync,
1300        );
1301        let this = app.create(DrivenScrollActivity {
1302            scroll_activity: ScrollActivityData::new(delegate),
1303            completer,
1304            controller: controller.clone(),
1305        });
1306        controller.add_listener(app, Listener::handle_method(this.handle(), Self::tick));
1307        let done = controller.animate_to(app, to, Some(duration), curve);
1308        // Won't trigger if we dispose the controller before it completes.
1309        done.when_complete(app, Listener::handle_method(this.handle(), Self::end));
1310        this
1311    }
1312
1313    /// Creates an activity that drives a scroll view through an animation
1314    /// given by a [`Simulation`].
1315    pub fn simulation(
1316        app: &mut App,
1317        delegate: AnyScrollActivityDelegate,
1318        simulation: Box<dyn Simulation>,
1319        vsync: impl TickerProvider,
1320    ) -> Ref<DrivenScrollActivity> {
1321        let completer = Completer::new();
1322        let controller = AnimationController::unbounded(
1323            app,
1324            0.0,
1325            None,
1326            None,
1327            AnimationBehavior::Preserve,
1328            vsync,
1329        );
1330        let this = app.create(DrivenScrollActivity {
1331            scroll_activity: ScrollActivityData::new(delegate),
1332            completer,
1333            controller: controller.clone(),
1334        });
1335        controller.add_listener(app, Listener::handle_method(this.handle(), Self::tick));
1336        let done = controller.animate_with(app, simulation);
1337        // Won't trigger if we dispose the controller before it completes.
1338        done.when_complete(app, Listener::handle_method(this.handle(), Self::end));
1339        this
1340    }
1341
1342    /// A future that completes when the activity stops.
1343    ///
1344    /// For example, this future will complete if the animation reaches the end
1345    /// or if the user interacts with the scroll view in way that causes the
1346    /// animation to stop before it reaches the end.
1347    pub fn done(self: Handle<Self>, app: &App) -> CompleterFuture<()> {
1348        app.get(self).completer.future()
1349    }
1350
1351    fn tick(self: Handle<Self>, app: &mut App) {
1352        let value = app.get(self).controller.value(app);
1353        if !self.apply_move_to(app, value) {
1354            self.delegate(app).go_idle(app);
1355        }
1356    }
1357
1358    /// Move the position to the given location.
1359    ///
1360    /// If the new position was fully applied, returns true. If there was any
1361    /// overflow, returns false.
1362    ///
1363    /// The default implementation calls [`ScrollActivityDelegate::set_pixels`]
1364    /// and returns true if the overflow was zero.
1365    pub fn apply_move_to(self: Handle<Self>, app: &mut App, value: f64) -> bool {
1366        self.delegate(app).set_pixels(app, value).abs() < PRECISION_ERROR_TOLERANCE
1367    }
1368
1369    fn end(self: Handle<Self>, app: &mut App) {
1370        // Check if the activity was disposed before going ballistic because `end` might be
1371        // called if the controller is disposed just after completion.
1372        if !self.is_disposed(app) {
1373            let velocity = self.velocity(app);
1374            self.delegate(app).go_ballistic(app, velocity);
1375        }
1376    }
1377}
1378
1379impl ScrollActivity for DrivenScrollActivity {
1380    crate::scroll_activity_accessors!();
1381
1382    fn dispatch_overscroll_notification(
1383        self: Handle<Self>,
1384        app: &mut App,
1385        metrics: Rc<dyn ScrollMetrics>,
1386        context: BuildContext,
1387        overscroll: f64,
1388    ) {
1389        let velocity = self.velocity(app);
1390        OverscrollNotification::new(metrics, context, overscroll)
1391            .velocity(velocity)
1392            .dispatch(app, Some(context));
1393    }
1394
1395    fn should_ignore_pointer(self: Handle<Self>, _app: &App) -> bool {
1396        true
1397    }
1398
1399    fn is_scrolling(self: Handle<Self>, _app: &App) -> bool {
1400        true
1401    }
1402
1403    fn velocity(self: Handle<Self>, app: &mut App) -> f64 {
1404        app.get(self).controller.velocity(app)
1405    }
1406
1407    fn dispose(self: Handle<Self>, app: &mut App) {
1408        let completer = app.get(self).completer.clone();
1409        completer.complete(app, ());
1410        app.get(self).controller.dispose(app);
1411        ScrollActivityBase::dispose(self, app);
1412    }
1413
1414    fn describe(self: Handle<Self>, app: &App) -> String {
1415        format!(
1416            "{}({:?})",
1417            describe_identity::<DrivenScrollActivity>(self.id()),
1418            app.get(self).controller.id()
1419        )
1420    }
1421}