Skip to main content

waft_widgets/widgets/
scroll_position.rs

1//! Flutter counterpart: `widgets/scroll_position.dart`.
2
3use std::any::{Any, TypeId};
4use std::cell::Cell;
5use std::fmt::{self, Debug};
6use std::hash::Hash;
7use std::rc::Rc;
8use std::time::Duration;
9
10use waft_animation::Curve;
11use waft_embedder::{Rect, clamp_double};
12use waft_foundation::{
13    App, ChangeNotifierData, CompleterFuture, Handle, HandleId, Listenable, ListenableObject,
14    Listener, OptionRetained, PRECISION_ERROR_TOLERANCE, Retained, ValueNotifier,
15};
16use waft_gestures::{Drag, DragStartDetails};
17use waft_painting::{Axis, AxisDirection, axis_direction_to_axis, transform_rect};
18use waft_physics::{Tolerance, near_equal};
19use waft_rendering::{
20    AnyRenderAbstractViewport, AnyRenderObject, AnyViewportOffset, ScrollDirection, ViewportOffset,
21};
22use waft_scheduler::{FrameCallback, SchedulerBinding, SchedulerPhase};
23
24use crate::framework::{BuildContext, Notification};
25use crate::view::View;
26use crate::widgets::page_storage::PageStorage;
27use crate::widgets::scroll_activity::{AnyScrollActivity, ScrollActivityRef, ScrollHoldController};
28use crate::widgets::scroll_context::ScrollContext;
29use crate::widgets::scroll_metrics::{FixedScrollMetrics, ScrollMetrics};
30use crate::widgets::scroll_notification::{
31    ScrollUpdateNotification, UserScrollNotification, ViewportNotificationData,
32    ViewportNotificationMixin,
33};
34use crate::widgets::scroll_physics::ScrollPhysicsRef;
35use waft_foundation::Ref;
36
37/// The policy to use when applying the `alignment` parameter of
38/// [`ScrollPosition::ensure_visible`].
39#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
40pub enum ScrollPositionAlignmentPolicy {
41    /// Use the `alignment` property of [`ScrollPosition::ensure_visible`] to decide
42    /// where to align the visible object.
43    Explicit,
44
45    /// Find the bottom edge of the scroll container, and scroll the container, if
46    /// necessary, to show the bottom of the object.
47    ///
48    /// For example, find the bottom edge of the scroll container. If the bottom
49    /// edge of the item is below the bottom edge of the scroll container, scroll
50    /// the item so that the bottom of the item is just visible. If the entire
51    /// item is already visible, then do nothing.
52    KeepVisibleAtEnd,
53
54    /// Find the top edge of the scroll container, and scroll the container if
55    /// necessary to show the top of the object.
56    ///
57    /// For example, find the top edge of the scroll container. If the top edge of
58    /// the item is above the top edge of the scroll container, scroll the item so
59    /// that the top of the item is just visible. If the entire item is already
60    /// visible, then do nothing.
61    KeepVisibleAtStart,
62}
63
64/// The fields of Dart's `ScrollPosition` base class, held under the field `scroll_position`.
65pub struct ScrollPositionData {
66    physics: ScrollPhysicsRef,
67    context: Rc<dyn ScrollContext>,
68    keep_scroll_offset: bool,
69    debug_label: Option<String>,
70    min_scroll_extent: Option<f64>,
71    max_scroll_extent: Option<f64>,
72    implied_velocity: f64,
73    pixels: Option<f64>,
74    viewport_dimension: Option<f64>,
75    have_dimensions: bool,
76    did_change_viewport_dimension_or_receive_correction: bool,
77    pending_dimensions: bool,
78    last_metrics: Option<Rc<dyn ScrollMetrics>>,
79    have_scheduled_update_notification: bool,
80    last_axis: Option<Axis>,
81    is_scrolling_notifier: Ref<ValueNotifier<bool>>,
82    activity: Option<ScrollActivityRef>,
83}
84
85impl ScrollPositionData {
86    /// The bag of a position that has neither dimensions nor an activity yet.
87    pub fn new(
88        app: &mut App,
89        physics: ScrollPhysicsRef,
90        context: Rc<dyn ScrollContext>,
91        keep_scroll_offset: bool,
92        debug_label: Option<String>,
93    ) -> ScrollPositionData {
94        ScrollPositionData {
95            physics,
96            context,
97            keep_scroll_offset,
98            debug_label,
99            min_scroll_extent: None,
100            max_scroll_extent: None,
101            implied_velocity: 0.0,
102            pixels: None,
103            viewport_dimension: None,
104            have_dimensions: false,
105            did_change_viewport_dimension_or_receive_correction: true,
106            pending_dimensions: false,
107            last_metrics: None,
108            have_scheduled_update_notification: false,
109            last_axis: None,
110            is_scrolling_notifier: app.create(ValueNotifier::new(false)),
111            activity: None,
112        }
113    }
114}
115
116/// The accessors [`ScrollPosition`] asks for, for a struct whose bag is the field
117/// `scroll_position`.
118#[macro_export]
119macro_rules! scroll_position_accessors {
120    () => {
121        fn scroll_position_data(
122            self: ::waft_foundation::Handle<Self>,
123            app: &::waft_foundation::App,
124        ) -> &$crate::ScrollPositionData {
125            &app.get(self).scroll_position
126        }
127
128        fn scroll_position_data_mut(
129            self: ::waft_foundation::Handle<Self>,
130            app: &mut ::waft_foundation::App,
131        ) -> &mut $crate::ScrollPositionData {
132            &mut app.get_mut(self).scroll_position
133        }
134    };
135}
136
137/// Determines which portion of the content is visible in a scroll view.
138///
139/// The [`pixels`](ViewportOffset::pixels) value determines the scroll offset that the scroll
140/// view uses to select which part of its content to display. As the user scrolls the
141/// viewport, this value changes, which changes the content that is displayed.
142///
143/// The [`ScrollPosition`] applies [`physics`](Self::physics) to scrolling, and stores the
144/// [`min_scroll_extent`](Self::min_scroll_extent) and
145/// [`max_scroll_extent`](Self::max_scroll_extent).
146///
147/// Scrolling is controlled by the current [`activity`](Self::activity), which is set by
148/// [`begin_activity`](Self::begin_activity). [`ScrollPosition`] itself does not start any
149/// activities. Instead, implementors, such as `ScrollPositionWithSingleContext`, typically
150/// start activities in response to user input or instructions from a `ScrollController`.
151///
152/// This object is a [`Listenable`] that notifies its listeners when
153/// [`pixels`](ViewportOffset::pixels) changes.
154///
155/// Dart's `ScrollMetrics` mixin members are re-declared here with the arena receiver;
156/// [`copy_with`](Self::copy_with) is the [`ScrollMetrics`] snapshot to hand to anything that
157/// reads the position's metrics.
158///
159/// ## Implementing ScrollPosition
160///
161/// Over time, a `Scrollable` might have many different [`ScrollPosition`]
162/// objects. For example, if `Scrollable.physics` changes type, `Scrollable`
163/// creates a new [`ScrollPosition`] with the new physics. To transfer state from
164/// the old instance to the new instance, implementors override
165/// [`absorb`](Self::absorb).
166///
167/// Implementors also need to call
168/// [`did_update_scroll_direction`](Self::did_update_scroll_direction) whenever
169/// [`user_scroll_direction`](ViewportOffset::user_scroll_direction) changes values.
170///
171/// See also:
172///
173///  * `Scrollable`, which uses a [`ScrollPosition`] to determine which portion of
174///    its content to display.
175///  * `ScrollController`, which can be used with `ListView`, `GridView` and
176///    other scrollable widgets to control a [`ScrollPosition`].
177///  * `ScrollPositionWithSingleContext`, which is the most commonly used
178///    concrete implementor.
179///  * [`ScrollNotification`](crate::ScrollNotification) and `NotificationListener`, which can be used to watch
180///    the scroll position without using a `ScrollController`.
181pub trait ScrollPosition: ViewportOffset {
182    /// Dart's `ScrollPosition` fields, held under the field `scroll_position`
183    /// ([`scroll_position_accessors!`](crate::scroll_position_accessors)).
184    fn scroll_position_data(self: Handle<Self>, app: &App) -> &ScrollPositionData;
185
186    /// See [`scroll_position_data`](Self::scroll_position_data).
187    fn scroll_position_data_mut(self: Handle<Self>, app: &mut App) -> &mut ScrollPositionData;
188
189    /// How the scroll position should respond to user input.
190    ///
191    /// For example, determines how the widget continues to animate after the
192    /// user stops dragging the scroll view.
193    fn physics(self: Handle<Self>, app: &App) -> ScrollPhysicsRef {
194        self.scroll_position_data(app).physics.clone()
195    }
196
197    /// Where the scrolling is taking place.
198    ///
199    /// Typically implemented by `ScrollableState`.
200    fn context(self: Handle<Self>, app: &App) -> Rc<dyn ScrollContext> {
201        Rc::clone(&self.scroll_position_data(app).context)
202    }
203
204    /// Save the current scroll offset with `PageStorage` and restore it if
205    /// this scroll position's scrollable is recreated.
206    ///
207    /// See also:
208    ///
209    ///  * `ScrollController::keep_scroll_offset`, which creates scroll positions and
210    ///    initializes this property.
211    fn keep_scroll_offset(self: Handle<Self>, app: &App) -> bool {
212        self.scroll_position_data(app).keep_scroll_offset
213    }
214
215    /// A label that is used in the [`to_string`](Self::to_string) output.
216    ///
217    /// Intended to aid with identifying scroll position instances in debug
218    /// output.
219    fn debug_label(self: Handle<Self>, app: &App) -> Option<&str> {
220        self.scroll_position_data(app).debug_label.as_deref()
221    }
222
223    /// See [`ScrollMetrics::min_scroll_extent`].
224    fn min_scroll_extent(self: Handle<Self>, app: &App) -> f64 {
225        self.scroll_position_data(app)
226            .min_scroll_extent
227            .expect("minScrollExtent was read without content dimensions")
228    }
229
230    /// See [`ScrollMetrics::max_scroll_extent`].
231    fn max_scroll_extent(self: Handle<Self>, app: &App) -> f64 {
232        self.scroll_position_data(app)
233            .max_scroll_extent
234            .expect("maxScrollExtent was read without content dimensions")
235    }
236
237    /// See [`ScrollMetrics::has_content_dimensions`].
238    fn has_content_dimensions(self: Handle<Self>, app: &App) -> bool {
239        let data = self.scroll_position_data(app);
240        data.min_scroll_extent.is_some() && data.max_scroll_extent.is_some()
241    }
242
243    /// See [`ScrollMetrics::viewport_dimension`].
244    fn viewport_dimension(self: Handle<Self>, app: &App) -> f64 {
245        self.scroll_position_data(app)
246            .viewport_dimension
247            .expect("viewportDimension was read before it was available")
248    }
249
250    /// See [`ScrollMetrics::has_viewport_dimension`].
251    fn has_viewport_dimension(self: Handle<Self>, app: &App) -> bool {
252        self.scroll_position_data(app).viewport_dimension.is_some()
253    }
254
255    /// The direction in which the scroll view scrolls; Dart's `ScrollMetrics.axisDirection`.
256    fn axis_direction(self: Handle<Self>, app: &App) -> AxisDirection;
257
258    /// See [`ScrollMetrics::axis`].
259    fn axis(self: Handle<Self>, app: &App) -> Axis {
260        axis_direction_to_axis(self.axis_direction(app))
261    }
262
263    /// See [`ScrollMetrics::device_pixel_ratio`].
264    fn device_pixel_ratio(self: Handle<Self>, app: &App) -> f64 {
265        self.context(app).device_pixel_ratio(app)
266    }
267
268    /// See [`ScrollMetrics::out_of_range`].
269    fn out_of_range(self: Handle<Self>, app: &App) -> bool {
270        self.copy_with(app).out_of_range()
271    }
272
273    /// See [`ScrollMetrics::at_edge`].
274    fn at_edge(self: Handle<Self>, app: &App) -> bool {
275        self.copy_with(app).at_edge()
276    }
277
278    /// See [`ScrollMetrics::extent_before`].
279    fn extent_before(self: Handle<Self>, app: &App) -> f64 {
280        self.copy_with(app).extent_before()
281    }
282
283    /// See [`ScrollMetrics::extent_inside`].
284    fn extent_inside(self: Handle<Self>, app: &App) -> f64 {
285        self.copy_with(app).extent_inside()
286    }
287
288    /// See [`ScrollMetrics::extent_after`].
289    fn extent_after(self: Handle<Self>, app: &App) -> f64 {
290        self.copy_with(app).extent_after()
291    }
292
293    /// See [`ScrollMetrics::extent_total`].
294    fn extent_total(self: Handle<Self>, app: &App) -> f64 {
295        self.copy_with(app).extent_total()
296    }
297
298    /// A snapshot of this position's [`ScrollMetrics`]; Dart's `ScrollMetrics.copyWith`.
299    ///
300    /// This is what to hand to anything that reads the metrics — the physics, a
301    /// [`ScrollNotification`](crate::ScrollNotification), `ScrollIncrementDetails`.
302    fn copy_with(self: Handle<Self>, app: &App) -> Rc<dyn ScrollMetrics> {
303        let has_content_dimensions = self.has_content_dimensions(app);
304        Rc::new(FixedScrollMetrics::new(
305            has_content_dimensions.then(|| self.min_scroll_extent(app)),
306            has_content_dimensions.then(|| self.max_scroll_extent(app)),
307            self.has_pixels(app).then(|| self.pixels(app)),
308            self.has_viewport_dimension(app)
309                .then(|| self.viewport_dimension(app)),
310            self.axis_direction(app),
311            self.device_pixel_ratio(app),
312        ))
313    }
314
315    /// Whether [`viewport_dimension`](Self::viewport_dimension),
316    /// [`min_scroll_extent`](Self::min_scroll_extent),
317    /// [`max_scroll_extent`](Self::max_scroll_extent), [`out_of_range`](Self::out_of_range),
318    /// and [`at_edge`](Self::at_edge) are available.
319    ///
320    /// Set to true just before the first time
321    /// [`apply_new_dimensions`](Self::apply_new_dimensions) is called.
322    fn have_dimensions(self: Handle<Self>, app: &App) -> bool {
323        self.scroll_position_data(app).have_dimensions
324    }
325
326    /// Whether scrollables should absorb pointer events at this position.
327    ///
328    /// This value relates to the current [`activity`](Self::activity), which determines
329    /// if additional touch input should be received by the scroll view or its children.
330    /// If the position is overscrolled, as is allowed by
331    /// [`crate::BouncingScrollPhysics`], children of the scroll view will receive pointer
332    /// events as the scroll view settles back from the overscrolled state.
333    fn should_ignore_pointer(self: Handle<Self>, app: &App) -> bool {
334        !self.out_of_range(app)
335            && self
336                .activity(app)
337                .is_none_or(|activity| activity.should_ignore_pointer(app))
338    }
339
340    /// Take any current applicable state from the given [`ScrollPosition`].
341    ///
342    /// This method is called by [`ScrollPositionBase::init`] if it is given an `old_position`.
343    /// The `other` argument might not have the same runtime type as this object.
344    ///
345    /// This method can be destructive to the other [`ScrollPosition`]. The other
346    /// object must be disposed immediately after this call.
347    ///
348    /// If the old [`ScrollPosition`] object has a different runtime type than this
349    /// one, the [`AnyScrollActivity::reset_activity`] method is invoked on the newly
350    /// adopted activity.
351    ///
352    /// ## Overriding
353    ///
354    /// Overrides of this method must call [`ScrollPositionBase::absorb`] after setting any
355    /// metrics-related or activity-related state, since this method may restart
356    /// the activity and scroll activities tend to use those metrics when being
357    /// restarted.
358    ///
359    /// Overrides of this method might need to start an [`crate::IdleScrollActivity`] if
360    /// they are unable to absorb the activity from the other [`ScrollPosition`].
361    ///
362    /// Overrides of this method might also need to update the delegates of
363    /// absorbed scroll activities if they use themselves as a
364    /// [`crate::ScrollActivityDelegate`].
365    fn absorb(self: Handle<Self>, app: &mut App, other: AnyScrollPosition) {
366        ScrollPositionBase::absorb(self, app, other);
367    }
368
369    /// Update the scroll position ([`pixels`](ViewportOffset::pixels)) to a given pixel value.
370    ///
371    /// This should only be called by the current [`activity`](Self::activity), either during
372    /// the transient callback phase or in response to user input.
373    ///
374    /// Returns the overscroll, if any. If the return value is 0.0, that means
375    /// that [`pixels`](ViewportOffset::pixels) now returns the given `new_pixels`. If the
376    /// return value is positive, then [`pixels`](ViewportOffset::pixels) is less than the
377    /// requested value by the given amount (overscroll past the max extent), and if it is
378    /// negative, it is greater than the requested value by the given amount (underscroll past
379    /// the min extent).
380    ///
381    /// The amount of overscroll is computed by
382    /// [`apply_boundary_conditions`](Self::apply_boundary_conditions).
383    ///
384    /// The amount of the change that is applied is reported using
385    /// [`did_update_scroll_position_by`](Self::did_update_scroll_position_by).
386    /// If there is any overscroll, it is reported using
387    /// [`did_overscroll_by`](Self::did_overscroll_by).
388    fn set_pixels(self: Handle<Self>, app: &mut App, new_pixels: f64) -> f64 {
389        ScrollPositionBase::set_pixels(self, app, new_pixels)
390    }
391
392    /// Change the value of [`pixels`](ViewportOffset::pixels) to the new value, without
393    /// notifying any customers.
394    ///
395    /// This is used to adjust the position while doing layout. In particular,
396    /// this is typically called as a response to
397    /// [`ViewportOffset::apply_viewport_dimension`] or
398    /// [`ViewportOffset::apply_content_dimensions`] (in both cases, if this method is called,
399    /// those methods should then return false to indicate that the position has been
400    /// adjusted).
401    ///
402    /// Calling this is rarely correct in other contexts. It will not immediately
403    /// cause the rendering to change, since it does not notify the widgets or
404    /// render objects that might be listening to this object.
405    ///
406    /// To cause the position to jump or animate to a new value, consider
407    /// [`ViewportOffset::jump_to`] or [`ViewportOffset::animate_to`], which will honor the
408    /// normal conventions for changing the scroll offset.
409    ///
410    /// To force the [`pixels`](ViewportOffset::pixels) to a particular value without honoring
411    /// the normal conventions for changing the scroll offset, consider
412    /// [`force_pixels`](Self::force_pixels).
413    fn correct_pixels(self: Handle<Self>, app: &mut App, value: f64) {
414        self.scroll_position_data_mut(app).pixels = Some(value);
415    }
416
417    /// Change the value of [`pixels`](ViewportOffset::pixels) to the new value, and notify any
418    /// customers, but without honoring normal conventions for changing the scroll offset.
419    ///
420    /// This is used to implement [`ViewportOffset::jump_to`]. It can also be used to adjust
421    /// the position when the dimensions of the viewport change. It should only be
422    /// used when manually implementing the logic for honoring the relevant
423    /// conventions of the class.
424    ///
425    /// This should not be called during layout (e.g. when setting the initial
426    /// scroll offset). Consider [`correct_pixels`](Self::correct_pixels) if you find you need
427    /// to adjust the position during layout.
428    fn force_pixels(self: Handle<Self>, app: &mut App, value: f64) {
429        ScrollPositionBase::force_pixels(self, app, value);
430    }
431
432    /// Called whenever scrolling ends, to store the current scroll offset in a
433    /// storage mechanism with a lifetime that matches the app's lifetime.
434    ///
435    /// The stored value will be used by
436    /// [`restore_scroll_offset`](Self::restore_scroll_offset) when the [`ScrollPosition`] is
437    /// recreated, in the case of the `Scrollable` being disposed then recreated in the same
438    /// session.
439    ///
440    /// The default implementation writes the [`pixels`](ViewportOffset::pixels) using the
441    /// nearest [`PageStorage`] found from the [`context`](Self::context)'s
442    /// [`ScrollContext::storage_context`] property.
443    fn save_scroll_offset(self: Handle<Self>, app: &mut App) {
444        ScrollPositionBase::save_scroll_offset(self, app);
445    }
446
447    /// Called whenever the [`ScrollPosition`] is created, to restore the scroll
448    /// offset if possible.
449    ///
450    /// The value is stored by [`save_scroll_offset`](Self::save_scroll_offset) when the scroll
451    /// position changes, so that it can be restored in the case of the `Scrollable` being
452    /// disposed then recreated in the same session.
453    ///
454    /// The default implementation reads the value from the nearest [`PageStorage`]
455    /// found from the [`context`](Self::context)'s [`ScrollContext::storage_context`]
456    /// property, and sets it using [`correct_pixels`](Self::correct_pixels), if
457    /// [`pixels`](ViewportOffset::pixels) is still unset.
458    ///
459    /// This method is called from [`ScrollPositionBase::init`], so layout has not yet
460    /// occurred, and the viewport dimensions aren't yet known when it is called.
461    fn restore_scroll_offset(self: Handle<Self>, app: &mut App) {
462        ScrollPositionBase::restore_scroll_offset(self, app);
463    }
464
465    /// Called by [`context`](Self::context) to restore the scroll offset to the provided
466    /// value.
467    ///
468    /// The provided value has previously been provided to the [`context`](Self::context) by
469    /// calling [`ScrollContext::save_offset`], e.g. from [`save_offset`](Self::save_offset).
470    ///
471    /// This method may be called right after the scroll position is created
472    /// before layout has occurred. In that case, `initial_restore` is set to true
473    /// and the viewport dimensions will not be known yet. If the
474    /// [`context`](Self::context) doesn't have any information to restore the scroll offset
475    /// this method is not called.
476    ///
477    /// The method may be called multiple times in the lifecycle of a
478    /// [`ScrollPosition`] to restore it to different scroll offsets.
479    fn restore_offset(self: Handle<Self>, app: &mut App, offset: f64, initial_restore: bool) {
480        ScrollPositionBase::restore_offset(self, app, offset, initial_restore);
481    }
482
483    /// Called whenever scrolling ends, to persist the current scroll offset for
484    /// state restoration purposes.
485    ///
486    /// The default implementation stores the current value of
487    /// [`pixels`](ViewportOffset::pixels) on the [`context`](Self::context) by calling
488    /// [`ScrollContext::save_offset`]. At a later point in time or after the application
489    /// restarts, the [`context`](Self::context) may restore the scroll position to the
490    /// persisted offset by calling [`restore_offset`](Self::restore_offset).
491    fn save_offset(self: Handle<Self>, app: &mut App) {
492        ScrollPositionBase::save_offset(self, app);
493    }
494
495    /// Returns the overscroll by applying the boundary conditions.
496    ///
497    /// If the given value is in bounds, returns 0.0. Otherwise, returns the
498    /// amount of value that cannot be applied to [`pixels`](ViewportOffset::pixels) as a
499    /// result of the boundary conditions. If the [`physics`](Self::physics) allow
500    /// out-of-bounds scrolling, this method always returns 0.0.
501    ///
502    /// The default implementation defers to the [`physics`](Self::physics) object's
503    /// [`crate::ScrollPhysics::apply_boundary_conditions`].
504    fn apply_boundary_conditions(self: Handle<Self>, app: &mut App, value: f64) -> f64 {
505        ScrollPositionBase::apply_boundary_conditions(self, app, value)
506    }
507
508    /// Verifies that the new content and viewport dimensions are acceptable.
509    ///
510    /// Called by [`ViewportOffset::apply_content_dimensions`] to determine its return value.
511    ///
512    /// Should return true if the current scroll offset is correct given
513    /// the new content and viewport dimensions.
514    ///
515    /// Otherwise, should call [`correct_pixels`](Self::correct_pixels) to correct the scroll
516    /// offset given the new dimensions, and then return false.
517    ///
518    /// This is only called when [`have_dimensions`](Self::have_dimensions) is true.
519    ///
520    /// The default implementation defers to
521    /// [`crate::ScrollPhysics::adjust_position_for_new_dimensions`].
522    fn correct_for_new_dimensions(
523        self: Handle<Self>,
524        app: &mut App,
525        old_position: &dyn ScrollMetrics,
526        new_position: &dyn ScrollMetrics,
527    ) -> bool {
528        ScrollPositionBase::correct_for_new_dimensions(self, app, old_position, new_position)
529    }
530
531    /// Notifies the activity that the dimensions of the underlying viewport or
532    /// contents have changed.
533    ///
534    /// Called after [`ViewportOffset::apply_viewport_dimension`] or
535    /// [`ViewportOffset::apply_content_dimensions`] have changed the
536    /// [`min_scroll_extent`](Self::min_scroll_extent), the
537    /// [`max_scroll_extent`](Self::max_scroll_extent), or the
538    /// [`viewport_dimension`](Self::viewport_dimension). When this method is called, it
539    /// should be called _after_ any corrections are applied to
540    /// [`pixels`](ViewportOffset::pixels) using [`correct_pixels`](Self::correct_pixels), not
541    /// before.
542    ///
543    /// The default implementation informs the [`activity`](Self::activity) of the new
544    /// dimensions by calling its [`AnyScrollActivity::apply_new_dimensions`] method.
545    ///
546    /// An override calls [`ScrollPositionBase::apply_new_dimensions`] where Dart writes
547    /// `super.applyNewDimensions()`.
548    fn apply_new_dimensions(self: Handle<Self>, app: &mut App) {
549        ScrollPositionBase::apply_new_dimensions(self, app);
550    }
551
552    /// Animates the position such that the given object is as visible as possible
553    /// by just scrolling this position.
554    ///
555    /// The optional `target_render_object` parameter is used to determine which area
556    /// of that object should be as visible as possible. If it is `None`, the entire
557    /// render object (as defined by its paint bounds) will be as visible as possible. If
558    /// it is provided, it must be a descendant of the object.
559    ///
560    /// See also:
561    ///
562    ///  * [`ScrollPositionAlignmentPolicy`] for the way in which `alignment` is
563    ///    applied, and the way the given `object` is aligned.
564    #[allow(clippy::too_many_arguments)]
565    fn ensure_visible(
566        self: Handle<Self>,
567        app: &mut App,
568        object: AnyRenderObject,
569        alignment: f64,
570        duration: Duration,
571        curve: Rc<dyn Curve>,
572        alignment_policy: ScrollPositionAlignmentPolicy,
573        target_render_object: Option<AnyRenderObject>,
574    ) -> CompleterFuture<()> {
575        ScrollPositionBase::ensure_visible(
576            self,
577            app,
578            object,
579            alignment,
580            duration,
581            curve,
582            alignment_policy,
583            target_render_object,
584        )
585    }
586
587    /// This notifier's value is true if a scroll is underway and false if the scroll
588    /// position is idle.
589    ///
590    /// Listeners added by stateful widgets should be removed in the widget's
591    /// `State::dispose` method.
592    fn is_scrolling_notifier(self: Handle<Self>, app: &App) -> Handle<ValueNotifier<bool>> {
593        self.scroll_position_data(app)
594            .is_scrolling_notifier
595            .handle()
596    }
597
598    /// Changes the scrolling position based on a pointer signal from current
599    /// value to delta without animation and without checking if new value is in
600    /// range, taking min/max scroll extent into account.
601    ///
602    /// Any active animation is canceled. If the user is currently scrolling, that
603    /// action is canceled.
604    ///
605    /// This method dispatches the start/update/end sequence of scrolling
606    /// notifications.
607    ///
608    /// This method is very similar to [`ViewportOffset::jump_to`], but
609    /// [`pointer_scroll`](Self::pointer_scroll) will update the [`ScrollDirection`].
610    fn pointer_scroll(self: Handle<Self>, app: &mut App, delta: f64);
611
612    /// Deprecated. Use [`ViewportOffset::jump_to`] or a custom [`ScrollPosition`] instead.
613    #[deprecated(
614        note = "This method bypasses scroll activity management and can cause inconsistent \
615                layouts or scrolling behavior. Use jump_to or a custom ScrollPosition instead."
616    )]
617    fn jump_to_without_settling(self: Handle<Self>, app: &mut App, value: f64);
618
619    /// Stop the current activity and start a [`crate::HoldScrollActivity`].
620    fn hold(
621        self: Handle<Self>,
622        app: &mut App,
623        hold_cancel_callback: Listener,
624    ) -> Rc<dyn ScrollHoldController>;
625
626    /// Start a drag activity corresponding to the given [`DragStartDetails`].
627    ///
628    /// The `drag_cancel_callback` argument will be invoked if the drag is ended
629    /// prematurely (e.g. from another activity taking over). See
630    /// [`crate::ScrollDragController::on_drag_canceled`] for details.
631    fn drag(
632        self: Handle<Self>,
633        app: &mut App,
634        details: DragStartDetails,
635        drag_cancel_callback: Listener,
636    ) -> Rc<dyn Drag>;
637
638    /// The currently operative [`AnyScrollActivity`].
639    ///
640    /// If the scroll position is not performing any more specific activity, the
641    /// activity will be an [`crate::IdleScrollActivity`]. To determine whether the scroll
642    /// position is idle, check the [`is_scrolling_notifier`](Self::is_scrolling_notifier).
643    ///
644    /// Call [`begin_activity`](Self::begin_activity) to change the current activity.
645    fn activity(self: Handle<Self>, app: &App) -> Option<AnyScrollActivity> {
646        self.scroll_position_data(app).activity.handle()
647    }
648
649    /// Change the current [`activity`](Self::activity), disposing of the old one and
650    /// sending scroll notifications as necessary.
651    ///
652    /// If the argument is `None`, this method has no effect. This is convenient for
653    /// cases where the new activity is obtained from another method, and that
654    /// method might return `None`.
655    fn begin_activity(self: Handle<Self>, app: &mut App, new_activity: Option<ScrollActivityRef>) {
656        ScrollPositionBase::begin_activity(self, app, new_activity);
657    }
658
659    /// Called by [`begin_activity`](Self::begin_activity) to report when an activity has
660    /// started.
661    fn did_start_scroll(self: Handle<Self>, app: &mut App) {
662        ScrollPositionBase::did_start_scroll(self, app);
663    }
664
665    /// Called by [`set_pixels`](Self::set_pixels) to report a change to the
666    /// [`pixels`](ViewportOffset::pixels) position.
667    fn did_update_scroll_position_by(self: Handle<Self>, app: &mut App, delta: f64) {
668        ScrollPositionBase::did_update_scroll_position_by(self, app, delta);
669    }
670
671    /// Called by [`begin_activity`](Self::begin_activity) to report when an activity has
672    /// ended.
673    ///
674    /// This also saves the scroll offset using
675    /// [`save_scroll_offset`](Self::save_scroll_offset).
676    fn did_end_scroll(self: Handle<Self>, app: &mut App) {
677        ScrollPositionBase::did_end_scroll(self, app);
678    }
679
680    /// Called by [`set_pixels`](Self::set_pixels) to report overscroll when an attempt is made
681    /// to change the [`pixels`](ViewportOffset::pixels) position. Overscroll is the amount of
682    /// change that was not applied to the [`pixels`](ViewportOffset::pixels) value.
683    fn did_overscroll_by(self: Handle<Self>, app: &mut App, value: f64) {
684        ScrollPositionBase::did_overscroll_by(self, app, value);
685    }
686
687    /// Dispatches a notification that the [`ViewportOffset::user_scroll_direction`] has
688    /// changed.
689    ///
690    /// Implementors should call this function when they change
691    /// [`ViewportOffset::user_scroll_direction`].
692    fn did_update_scroll_direction(self: Handle<Self>, app: &mut App, direction: ScrollDirection) {
693        ScrollPositionBase::did_update_scroll_direction(self, app, direction);
694    }
695
696    /// Dispatches a notification that the [`ScrollMetrics`] have changed.
697    fn did_update_scroll_metrics(self: Handle<Self>, app: &mut App) {
698        ScrollPositionBase::did_update_scroll_metrics(self, app);
699    }
700
701    /// Provides a heuristic to determine if expensive frame-bound tasks should be
702    /// deferred.
703    ///
704    /// The actual work of this is delegated to the [`physics`](Self::physics) via
705    /// [`crate::ScrollPhysics::recommend_deferred_loading`] called with the current
706    /// [`activity`](Self::activity)'s [`AnyScrollActivity::velocity`].
707    ///
708    /// Returning true from this method indicates that the [`crate::ScrollPhysics`]
709    /// evaluate the current scroll velocity to be great enough that expensive
710    /// operations impacting the UI should be deferred.
711    fn recommend_deferred_loading(
712        self: Handle<Self>,
713        app: &mut App,
714        context: BuildContext,
715    ) -> bool {
716        ScrollPositionBase::recommend_deferred_loading(self, app, context)
717    }
718
719    /// Discards any resources used by the object.
720    fn dispose(self: Handle<Self>, app: &mut App) {
721        ScrollPositionBase::dispose(self, app);
722    }
723
724    /// Add additional information to the given `description` for use by
725    /// [`to_string`](Self::to_string).
726    ///
727    /// An override calls [`ScrollPositionBase::debug_fill_description`] where Dart writes
728    /// `super.debugFillDescription(description)`.
729    fn debug_fill_description(self: Handle<Self>, app: &App, description: &mut Vec<String>) {
730        ScrollPositionBase::debug_fill_description(self, app, description);
731    }
732
733    /// Dart's `toString`, which reads the arena and so cannot be [`Debug`].
734    fn to_string(self: Handle<Self>, app: &App) -> String {
735        let mut description = Vec::new();
736        ScrollPosition::debug_fill_description(self, app, &mut description);
737        format!(
738            "{}({})",
739            describe_identity::<Self>(self.id()),
740            description.join(", ")
741        )
742    }
743
744    /// This position as the erased [`AnyScrollPosition`] — what to pass where a Dart API takes
745    /// a `ScrollPosition`.
746    fn as_scroll_position(self: Handle<Self>) -> AnyScrollPosition {
747        AnyScrollPosition {
748            id: self.id(),
749            vtable: const { &ScrollPositionVTable::of::<Self>() },
750        }
751    }
752}
753
754/// Dart's `describeIdentity`: the runtime type and a short identity hash.
755fn describe_identity<T: ?Sized>(id: HandleId) -> String {
756    let name = std::any::type_name::<T>();
757    let short = name.rsplit("::").next().unwrap_or(name);
758    format!("{short}#{id:?}")
759}
760
761/// The typed handle for an erased id. Free: nothing is looked up; `get` checks the slot.
762fn resolve<T: 'static>(id: HandleId) -> Handle<T> {
763    Handle::from_id(id)
764}
765
766/// The shared bodies of Dart's `ScrollPosition`: call one where Dart writes `super.…`.
767pub struct ScrollPositionBase;
768
769impl ScrollPositionBase {
770    /// Dart's `ScrollPosition` constructor body: absorb the old position, then restore the
771    /// saved scroll offset.
772    ///
773    /// A leaf's constructor calls this right after `App::create`, where Dart's superclass
774    /// constructor would run.
775    pub fn init<P: ScrollPosition>(
776        this: Handle<P>,
777        app: &mut App,
778        old_position: Option<AnyScrollPosition>,
779    ) {
780        if let Some(old_position) = old_position {
781            P::absorb(this, app, old_position);
782        }
783        if this.keep_scroll_offset(app) {
784            P::restore_scroll_offset(this, app);
785        }
786    }
787
788    /// See [`ViewportOffset::pixels`], which a [`ScrollPosition`] answers from its bag.
789    pub fn pixels<P: ScrollPosition>(this: Handle<P>, app: &App) -> f64 {
790        this.scroll_position_data(app)
791            .pixels
792            .expect("pixels was read before it was available")
793    }
794
795    /// See [`ViewportOffset::has_pixels`], which a [`ScrollPosition`] answers from its bag.
796    pub fn has_pixels<P: ScrollPosition>(this: Handle<P>, app: &App) -> bool {
797        this.scroll_position_data(app).pixels.is_some()
798    }
799
800    /// See [`ScrollPosition::absorb`].
801    pub fn absorb<P: ScrollPosition>(this: Handle<P>, app: &mut App, other: AnyScrollPosition) {
802        debug_assert!(Rc::ptr_eq(&other.context(app), &this.context(app)));
803        debug_assert!(this.scroll_position_data(app).pixels.is_none());
804        if other.has_content_dimensions(app) {
805            let (min, max) = (other.min_scroll_extent(app), other.max_scroll_extent(app));
806            let data = this.scroll_position_data_mut(app);
807            data.min_scroll_extent = Some(min);
808            data.max_scroll_extent = Some(max);
809        }
810        if other.has_pixels(app) {
811            let pixels = other.pixels(app);
812            this.scroll_position_data_mut(app).pixels = Some(pixels);
813        }
814        if other.has_viewport_dimension(app) {
815            let viewport_dimension = other.viewport_dimension(app);
816            this.scroll_position_data_mut(app).viewport_dimension = Some(viewport_dimension);
817        }
818
819        debug_assert!(this.activity(app).is_none());
820        debug_assert!(other.activity(app).is_some());
821        let activity = other
822            .take_activity(app)
823            .expect("the old position has an activity");
824        this.scroll_position_data_mut(app).activity = Some(activity.clone());
825        if other.type_id() != TypeId::of::<P>() {
826            activity.reset_activity(app);
827        }
828        let should_ignore_pointer = activity.should_ignore_pointer(app);
829        this.context(app)
830            .set_ignore_pointer(app, should_ignore_pointer);
831        let is_scrolling = activity.is_scrolling(app);
832        this.is_scrolling_notifier(app).set_value(app, is_scrolling);
833    }
834
835    /// See [`ScrollPosition::set_pixels`].
836    pub fn set_pixels<P: ScrollPosition>(this: Handle<P>, app: &mut App, new_pixels: f64) -> f64 {
837        debug_assert!(this.has_pixels(app));
838        if cfg!(debug_assertions) {
839            assert!(
840                SchedulerBinding::scheduler_phase(app) != SchedulerPhase::PersistentCallbacks,
841                "A scrollable's position should not change during the build, layout, and paint \
842                 phases, otherwise the rendering will be confused."
843            );
844        }
845        let pixels = this.pixels(app);
846        if new_pixels != pixels {
847            let overscroll = P::apply_boundary_conditions(this, app, new_pixels);
848            debug_assert!(
849                overscroll.abs() <= (new_pixels - pixels).abs(),
850                "applyBoundaryConditions returned invalid overscroll value."
851            );
852            let old_pixels = pixels;
853            this.scroll_position_data_mut(app).pixels = Some(new_pixels - overscroll);
854            if this.pixels(app) != old_pixels {
855                if this.out_of_range(app) {
856                    this.context(app).set_ignore_pointer(app, false);
857                }
858                this.notify_listeners(app);
859                let delta = this.pixels(app) - old_pixels;
860                P::did_update_scroll_position_by(this, app, delta);
861            }
862            if overscroll.abs() > PRECISION_ERROR_TOLERANCE {
863                P::did_overscroll_by(this, app, overscroll);
864                return overscroll;
865            }
866        }
867        0.0
868    }
869
870    /// See [`ViewportOffset::correct_by`], which a [`ScrollPosition`] overrides.
871    pub fn correct_by<P: ScrollPosition>(this: Handle<P>, app: &mut App, correction: f64) {
872        debug_assert!(
873            this.has_pixels(app),
874            "An initial pixels value must exist by calling correctPixels on the ScrollPosition"
875        );
876        let data = this.scroll_position_data_mut(app);
877        data.pixels = Some(data.pixels.expect("an initial pixels value") + correction);
878        data.did_change_viewport_dimension_or_receive_correction = true;
879    }
880
881    /// See [`ScrollPosition::force_pixels`].
882    pub fn force_pixels<P: ScrollPosition>(this: Handle<P>, app: &mut App, value: f64) {
883        debug_assert!(this.has_pixels(app));
884        let implied_velocity = value - this.pixels(app);
885        let data = this.scroll_position_data_mut(app);
886        data.implied_velocity = implied_velocity;
887        data.pixels = Some(value);
888        this.notify_listeners(app);
889        SchedulerBinding::add_post_frame_callback(
890            app,
891            FrameCallback::handle_method(this, reset_implied_velocity::<P>),
892            View::maybe_id_of(app, this.context(app).storage_context(app)),
893        );
894    }
895
896    /// See [`ScrollPosition::save_scroll_offset`].
897    pub fn save_scroll_offset<P: ScrollPosition>(this: Handle<P>, app: &mut App) {
898        let storage_context = this.context(app).storage_context(app);
899        if let Some(bucket) = PageStorage::maybe_of(app, storage_context) {
900            let pixels = this.pixels(app);
901            bucket.write_state(app, storage_context, Rc::new(pixels), None);
902        }
903    }
904
905    /// See [`ScrollPosition::restore_scroll_offset`].
906    pub fn restore_scroll_offset<P: ScrollPosition>(this: Handle<P>, app: &mut App) {
907        if !this.has_pixels(app) {
908            let storage_context = this.context(app).storage_context(app);
909            let value = PageStorage::maybe_of(app, storage_context)
910                .and_then(|bucket| bucket.read_state(app, storage_context, None))
911                .and_then(|data| data.downcast_ref::<f64>().copied());
912            if let Some(value) = value {
913                P::correct_pixels(this, app, value);
914            }
915        }
916    }
917
918    /// See [`ScrollPosition::restore_offset`].
919    pub fn restore_offset<P: ScrollPosition>(
920        this: Handle<P>,
921        app: &mut App,
922        offset: f64,
923        initial_restore: bool,
924    ) {
925        if initial_restore {
926            P::correct_pixels(this, app, offset);
927        } else {
928            P::jump_to(this, app, offset);
929        }
930    }
931
932    /// See [`ScrollPosition::save_offset`].
933    pub fn save_offset<P: ScrollPosition>(this: Handle<P>, app: &mut App) {
934        debug_assert!(this.has_pixels(app));
935        let pixels = this.pixels(app);
936        this.context(app).save_offset(app, pixels);
937    }
938
939    /// See [`ScrollPosition::apply_boundary_conditions`].
940    pub fn apply_boundary_conditions<P: ScrollPosition>(
941        this: Handle<P>,
942        app: &mut App,
943        value: f64,
944    ) -> f64 {
945        let physics = this.physics(app);
946        let metrics = this.copy_with(app);
947        let result = physics.apply_boundary_conditions(&*metrics, value);
948        debug_assert!(
949            result.abs() <= (value - this.pixels(app)).abs(),
950            "{physics:?}.applyBoundaryConditions returned invalid overscroll value. The \
951             applyBoundaryConditions method is only supposed to reduce the possible range of \
952             movement, not increase it."
953        );
954        result
955    }
956
957    /// See [`ViewportOffset::apply_viewport_dimension`], which a [`ScrollPosition`] overrides.
958    pub fn apply_viewport_dimension<P: ScrollPosition>(
959        this: Handle<P>,
960        app: &mut App,
961        viewport_dimension: f64,
962    ) -> bool {
963        let data = this.scroll_position_data_mut(app);
964        if data.viewport_dimension != Some(viewport_dimension) {
965            data.viewport_dimension = Some(viewport_dimension);
966            data.did_change_viewport_dimension_or_receive_correction = true;
967            // If this is called, you can rely on `apply_content_dimensions` being called soon
968            // afterwards in the same layout phase. So we put all the logic that relies on both
969            // values being computed into `apply_content_dimensions`.
970        }
971        true
972    }
973
974    /// Dart's `_isMetricsChanged`.
975    fn is_metrics_changed<P: ScrollPosition>(this: Handle<P>, app: &App) -> bool {
976        debug_assert!(this.have_dimensions(app));
977        let current_metrics = this.copy_with(app);
978        let Some(last_metrics) = this.scroll_position_data(app).last_metrics.clone() else {
979            return true;
980        };
981        !(current_metrics.extent_before() == last_metrics.extent_before()
982            && current_metrics.extent_inside() == last_metrics.extent_inside()
983            && current_metrics.extent_after() == last_metrics.extent_after()
984            && current_metrics.axis_direction() == last_metrics.axis_direction())
985    }
986
987    /// See [`ViewportOffset::apply_content_dimensions`], which a [`ScrollPosition`] overrides.
988    pub fn apply_content_dimensions<P: ScrollPosition>(
989        this: Handle<P>,
990        app: &mut App,
991        min_scroll_extent: f64,
992        max_scroll_extent: f64,
993    ) -> bool {
994        debug_assert!(
995            this.have_dimensions(app) == this.scroll_position_data(app).last_metrics.is_some()
996        );
997        let data = this.scroll_position_data(app);
998        let distance = Tolerance::DEFAULT_TOLERANCE.distance;
999        if !near_equal(data.min_scroll_extent, Some(min_scroll_extent), distance)
1000            || !near_equal(data.max_scroll_extent, Some(max_scroll_extent), distance)
1001            || data.did_change_viewport_dimension_or_receive_correction
1002            || data.last_axis != Some(this.axis(app))
1003        {
1004            debug_assert!(min_scroll_extent <= max_scroll_extent);
1005            let axis = this.axis(app);
1006            let data = this.scroll_position_data_mut(app);
1007            data.min_scroll_extent = Some(min_scroll_extent);
1008            data.max_scroll_extent = Some(max_scroll_extent);
1009            data.last_axis = Some(axis);
1010            let current_metrics = this.have_dimensions(app).then(|| this.copy_with(app));
1011            let last_metrics = this.scroll_position_data(app).last_metrics.clone();
1012            let data = this.scroll_position_data_mut(app);
1013            data.did_change_viewport_dimension_or_receive_correction = false;
1014            data.pending_dimensions = true;
1015            if this.have_dimensions(app) {
1016                let last_metrics = last_metrics.expect("dimensions imply the last metrics");
1017                let current_metrics = current_metrics.expect("dimensions imply current metrics");
1018                if !P::correct_for_new_dimensions(this, app, &*last_metrics, &*current_metrics) {
1019                    return false;
1020                }
1021            }
1022            this.scroll_position_data_mut(app).have_dimensions = true;
1023        }
1024        debug_assert!(this.have_dimensions(app));
1025        if this.scroll_position_data(app).pending_dimensions {
1026            P::apply_new_dimensions(this, app);
1027            this.scroll_position_data_mut(app).pending_dimensions = false;
1028        }
1029        debug_assert!(
1030            !this
1031                .scroll_position_data(app)
1032                .did_change_viewport_dimension_or_receive_correction,
1033            "Use correct_for_new_dimensions() (and return true) to change the scroll offset \
1034             during apply_content_dimensions()."
1035        );
1036
1037        if Self::is_metrics_changed(this, app) {
1038            // It is too late to send useful notifications, because the potential listeners
1039            // have, by definition, already been built this frame. To make sure the
1040            // notification is sent at all, we delay it until after the frame is complete.
1041            if !this
1042                .scroll_position_data(app)
1043                .have_scheduled_update_notification
1044            {
1045                // Dart's microtask holds the position, and through it its context, until it runs
1046                // (scroll_position.dart:678-680): a scrollable disposed in this frame stays
1047                // readable, its notification context `null` (scrollable.dart:603), so nothing is
1048                // sent (scroll_position.dart:1089).
1049                let position = this.keep(app);
1050                let context = this.context(app).handle_id().upgrade(app);
1051                app.schedule_microtask(Listener::new(move |app| {
1052                    let _context = &context;
1053                    P::did_update_scroll_metrics(position.handle(), app);
1054                }));
1055                this.scroll_position_data_mut(app)
1056                    .have_scheduled_update_notification = true;
1057            }
1058            let metrics = this.copy_with(app);
1059            this.scroll_position_data_mut(app).last_metrics = Some(metrics);
1060        }
1061        true
1062    }
1063
1064    /// See [`ScrollPosition::correct_for_new_dimensions`].
1065    pub fn correct_for_new_dimensions<P: ScrollPosition>(
1066        this: Handle<P>,
1067        app: &mut App,
1068        old_position: &dyn ScrollMetrics,
1069        new_position: &dyn ScrollMetrics,
1070    ) -> bool {
1071        let activity = this.activity(app).expect("a position has an activity");
1072        let is_scrolling = activity.is_scrolling(app);
1073        let velocity = activity.velocity(app);
1074        let physics = this.physics(app);
1075        let new_pixels = physics.adjust_position_for_new_dimensions(
1076            old_position,
1077            new_position,
1078            is_scrolling,
1079            velocity,
1080        );
1081        if new_pixels != this.pixels(app) {
1082            P::correct_pixels(this, app, new_pixels);
1083            return false;
1084        }
1085        true
1086    }
1087
1088    /// See [`ScrollPosition::apply_new_dimensions`].
1089    pub fn apply_new_dimensions<P: ScrollPosition>(this: Handle<P>, app: &mut App) {
1090        debug_assert!(this.has_pixels(app));
1091        debug_assert!(this.scroll_position_data(app).pending_dimensions);
1092        this.activity(app)
1093            .expect("a position has an activity")
1094            .apply_new_dimensions(app);
1095    }
1096
1097    /// Dart's `_maybeFlipAlignment`.
1098    fn maybe_flip_alignment(
1099        alignment_policy: ScrollPositionAlignmentPolicy,
1100    ) -> ScrollPositionAlignmentPolicy {
1101        match alignment_policy {
1102            // Don't flip when explicit.
1103            ScrollPositionAlignmentPolicy::Explicit => alignment_policy,
1104            ScrollPositionAlignmentPolicy::KeepVisibleAtEnd => {
1105                ScrollPositionAlignmentPolicy::KeepVisibleAtStart
1106            }
1107            ScrollPositionAlignmentPolicy::KeepVisibleAtStart => {
1108                ScrollPositionAlignmentPolicy::KeepVisibleAtEnd
1109            }
1110        }
1111    }
1112
1113    /// Dart's `_applyAxisDirectionToAlignmentPolicy`.
1114    fn apply_axis_direction_to_alignment_policy<P: ScrollPosition>(
1115        this: Handle<P>,
1116        app: &App,
1117        alignment_policy: ScrollPositionAlignmentPolicy,
1118    ) -> ScrollPositionAlignmentPolicy {
1119        match this.axis_direction(app) {
1120            // Start and end alignments must account for axis direction.
1121            // When focus is requested for example, it knows the directionality of the
1122            // keyboard keys initiating traversal, but not the direction of the `Scrollable`.
1123            AxisDirection::Up | AxisDirection::Left => Self::maybe_flip_alignment(alignment_policy),
1124            AxisDirection::Down | AxisDirection::Right => alignment_policy,
1125        }
1126    }
1127
1128    /// See [`ScrollPosition::ensure_visible`].
1129    #[allow(clippy::too_many_arguments)]
1130    pub fn ensure_visible<P: ScrollPosition>(
1131        this: Handle<P>,
1132        app: &mut App,
1133        object: AnyRenderObject,
1134        alignment: f64,
1135        duration: Duration,
1136        curve: Rc<dyn Curve>,
1137        alignment_policy: ScrollPositionAlignmentPolicy,
1138        target_render_object: Option<AnyRenderObject>,
1139    ) -> CompleterFuture<()> {
1140        debug_assert!(object.attached(app));
1141        // If no viewport is found, return.
1142        let Some(viewport) = AnyRenderAbstractViewport::maybe_of(app, Some(object)) else {
1143            return CompleterFuture::ready(());
1144        };
1145
1146        let mut target_rect: Option<Rect> = None;
1147        if let Some(target) = target_render_object
1148            && target != object
1149        {
1150            target_rect = Some(transform_rect(
1151                &target.get_transform_to(app, Some(object)),
1152                object.paint_bounds(app).intersect(target.paint_bounds(app)),
1153            ));
1154        }
1155
1156        let axis = this.axis(app);
1157        let (min, max) = (this.min_scroll_extent(app), this.max_scroll_extent(app));
1158        let target =
1159            match Self::apply_axis_direction_to_alignment_policy(this, app, alignment_policy) {
1160                ScrollPositionAlignmentPolicy::Explicit => clamp_double(
1161                    viewport
1162                        .get_offset_to_reveal(app, object, alignment, target_rect, Some(axis))
1163                        .offset,
1164                    min,
1165                    max,
1166                ),
1167                ScrollPositionAlignmentPolicy::KeepVisibleAtEnd => {
1168                    // Aligns to end.
1169                    let revealed = clamp_double(
1170                        viewport
1171                            .get_offset_to_reveal(app, object, 1.0, target_rect, Some(axis))
1172                            .offset,
1173                        min,
1174                        max,
1175                    );
1176                    revealed.max(this.pixels(app))
1177                }
1178                ScrollPositionAlignmentPolicy::KeepVisibleAtStart => {
1179                    // Aligns to start.
1180                    let revealed = clamp_double(
1181                        viewport
1182                            .get_offset_to_reveal(app, object, 0.0, target_rect, Some(axis))
1183                            .offset,
1184                        min,
1185                        max,
1186                    );
1187                    revealed.min(this.pixels(app))
1188                }
1189            };
1190
1191        if target == this.pixels(app) {
1192            return CompleterFuture::ready(());
1193        }
1194
1195        if duration.is_zero() {
1196            P::jump_to(this, app, target);
1197            return CompleterFuture::ready(());
1198        }
1199
1200        P::animate_to(this, app, target, duration, curve)
1201    }
1202
1203    /// See [`ViewportOffset::move_to`], which a [`ScrollPosition`] overrides.
1204    pub fn move_to<P: ScrollPosition>(
1205        this: Handle<P>,
1206        app: &mut App,
1207        to: f64,
1208        duration: Option<Duration>,
1209        curve: Option<Rc<dyn Curve>>,
1210        clamp: Option<bool>,
1211    ) -> CompleterFuture<()> {
1212        let clamp = clamp.unwrap_or(true);
1213        let to = if clamp {
1214            clamp_double(to, this.min_scroll_extent(app), this.max_scroll_extent(app))
1215        } else {
1216            to
1217        };
1218        waft_rendering::ViewportOffsetBase::move_to(this, app, to, duration, curve, Some(clamp))
1219    }
1220
1221    /// See [`ViewportOffset::allow_implicit_scrolling`], which a [`ScrollPosition`] overrides.
1222    pub fn allow_implicit_scrolling<P: ScrollPosition>(this: Handle<P>, app: &App) -> bool {
1223        this.scroll_position_data(app)
1224            .physics
1225            .allow_implicit_scrolling()
1226    }
1227
1228    /// See [`ScrollPosition::begin_activity`].
1229    pub fn begin_activity<P: ScrollPosition>(
1230        this: Handle<P>,
1231        app: &mut App,
1232        new_activity: Option<ScrollActivityRef>,
1233    ) {
1234        let Some(new_activity_ref) = new_activity else {
1235            return;
1236        };
1237        let new_activity = new_activity_ref.handle();
1238        let was_scrolling;
1239        let old_ignore_pointer;
1240        if let Some(activity) = this.activity(app) {
1241            old_ignore_pointer = activity.should_ignore_pointer(app);
1242            was_scrolling = activity.is_scrolling(app);
1243            if was_scrolling && !new_activity.is_scrolling(app) {
1244                // Notifies and then saves the scroll offset.
1245                P::did_end_scroll(this, app);
1246            }
1247            activity.dispose(app);
1248        } else {
1249            old_ignore_pointer = false;
1250            was_scrolling = false;
1251        }
1252        this.scroll_position_data_mut(app).activity = Some(new_activity_ref);
1253        let should_ignore_pointer = new_activity.should_ignore_pointer(app);
1254        if old_ignore_pointer != should_ignore_pointer {
1255            this.context(app)
1256                .set_ignore_pointer(app, should_ignore_pointer);
1257        }
1258        let is_scrolling = new_activity.is_scrolling(app);
1259        this.is_scrolling_notifier(app).set_value(app, is_scrolling);
1260        if !was_scrolling && is_scrolling {
1261            P::did_start_scroll(this, app);
1262        }
1263    }
1264
1265    /// See [`ScrollPosition::did_start_scroll`].
1266    pub fn did_start_scroll<P: ScrollPosition>(this: Handle<P>, app: &mut App) {
1267        let metrics = this.copy_with(app);
1268        let context = this.context(app).notification_context(app);
1269        this.activity(app)
1270            .expect("a position has an activity")
1271            .dispatch_scroll_start_notification(app, metrics, context);
1272    }
1273
1274    /// See [`ScrollPosition::did_update_scroll_position_by`].
1275    pub fn did_update_scroll_position_by<P: ScrollPosition>(
1276        this: Handle<P>,
1277        app: &mut App,
1278        delta: f64,
1279    ) {
1280        let metrics = this.copy_with(app);
1281        let context = notification_context(this, app);
1282        this.activity(app)
1283            .expect("a position has an activity")
1284            .dispatch_scroll_update_notification(app, metrics, context, delta);
1285    }
1286
1287    /// See [`ScrollPosition::did_end_scroll`].
1288    pub fn did_end_scroll<P: ScrollPosition>(this: Handle<P>, app: &mut App) {
1289        let metrics = this.copy_with(app);
1290        let context = notification_context(this, app);
1291        this.activity(app)
1292            .expect("a position has an activity")
1293            .dispatch_scroll_end_notification(app, metrics, context);
1294        P::save_offset(this, app);
1295        if this.keep_scroll_offset(app) {
1296            P::save_scroll_offset(this, app);
1297        }
1298    }
1299
1300    /// See [`ScrollPosition::did_overscroll_by`].
1301    pub fn did_overscroll_by<P: ScrollPosition>(this: Handle<P>, app: &mut App, value: f64) {
1302        let activity = this.activity(app).expect("a position has an activity");
1303        debug_assert!(activity.is_scrolling(app));
1304        let metrics = this.copy_with(app);
1305        let context = notification_context(this, app);
1306        activity.dispatch_overscroll_notification(app, metrics, context, value);
1307    }
1308
1309    /// See [`ScrollPosition::did_update_scroll_direction`].
1310    pub fn did_update_scroll_direction<P: ScrollPosition>(
1311        this: Handle<P>,
1312        app: &mut App,
1313        direction: ScrollDirection,
1314    ) {
1315        let metrics = this.copy_with(app);
1316        let context = notification_context(this, app);
1317        UserScrollNotification::new(metrics, context, direction).dispatch(app, Some(context));
1318    }
1319
1320    /// See [`ScrollPosition::did_update_scroll_metrics`].
1321    pub fn did_update_scroll_metrics<P: ScrollPosition>(this: Handle<P>, app: &mut App) {
1322        if cfg!(debug_assertions) {
1323            assert!(SchedulerBinding::scheduler_phase(app) != SchedulerPhase::PersistentCallbacks);
1324        }
1325        debug_assert!(
1326            this.scroll_position_data(app)
1327                .have_scheduled_update_notification
1328        );
1329        this.scroll_position_data_mut(app)
1330            .have_scheduled_update_notification = false;
1331        if let Some(context) = this.context(app).notification_context(app) {
1332            let metrics = this.copy_with(app);
1333            ScrollMetricsNotification::new(metrics, context).dispatch(app, Some(context));
1334        }
1335    }
1336
1337    /// See [`ScrollPosition::recommend_deferred_loading`].
1338    pub fn recommend_deferred_loading<P: ScrollPosition>(
1339        this: Handle<P>,
1340        app: &mut App,
1341        context: BuildContext,
1342    ) -> bool {
1343        let activity = this.activity(app).expect("a position has an activity");
1344        let velocity = activity.velocity(app) + this.scroll_position_data(app).implied_velocity;
1345        let metrics = this.copy_with(app);
1346        let physics = this.physics(app);
1347        physics.recommend_deferred_loading(app, velocity, &*metrics, context)
1348    }
1349
1350    /// See [`ScrollPosition::dispose`].
1351    pub fn dispose<P: ScrollPosition>(this: Handle<P>, app: &mut App) {
1352        // The activity will be `None` if it got absorbed by another `ScrollPosition`.
1353        if let Some(activity) = this.activity(app) {
1354            activity.dispose(app);
1355        }
1356        this.scroll_position_data_mut(app).activity = None;
1357        let is_scrolling_notifier = this.is_scrolling_notifier(app);
1358        is_scrolling_notifier.dispose(app);
1359        ChangeNotifierData::dispose(app, this);
1360    }
1361
1362    /// See [`ScrollPosition::debug_fill_description`].
1363    pub fn debug_fill_description<P: ScrollPosition>(
1364        this: Handle<P>,
1365        app: &App,
1366        description: &mut Vec<String>,
1367    ) {
1368        if let Some(debug_label) = this.debug_label(app) {
1369            description.push(debug_label.to_string());
1370        }
1371        ViewportOffset::debug_fill_description(this, app, description);
1372        let data = this.scroll_position_data(app);
1373        description.push(format!(
1374            "range: {}..{}",
1375            format_optional(data.min_scroll_extent),
1376            format_optional(data.max_scroll_extent)
1377        ));
1378        description.push(format!(
1379            "viewport: {}",
1380            format_optional(data.viewport_dimension)
1381        ));
1382    }
1383}
1384
1385/// Dart's `'${value?.toStringAsFixed(1)}'`, which prints `null` for a missing value.
1386fn format_optional(value: Option<f64>) -> String {
1387    value.map_or_else(|| "null".to_string(), |value| format!("{value:.1}"))
1388}
1389
1390/// Dart's `context.notificationContext!`.
1391fn notification_context<P: ScrollPosition>(this: Handle<P>, app: &mut App) -> BuildContext {
1392    this.context(app).notification_context(app).expect(
1393        "a ScrollPosition dispatches its notifications from the ScrollContext's notification \
1394         context, which is only available once the Scrollable has built",
1395    )
1396}
1397
1398/// The post-frame callback [`ScrollPositionBase::force_pixels`] schedules; Dart's
1399/// `'ScrollPosition.resetVelocity'`.
1400fn reset_implied_velocity<P: ScrollPosition>(
1401    this: Handle<P>,
1402    app: &mut App,
1403    _time_stamp: Duration,
1404) {
1405    this.scroll_position_data_mut(app).implied_velocity = 0.0;
1406}
1407
1408/// The dispatch signature of [`ViewportOffset::animate_to`].
1409type AnimateToFn = fn(&mut App, HandleId, f64, Duration, Rc<dyn Curve>) -> CompleterFuture<()>;
1410
1411/// The dispatch signature of [`ViewportOffset::move_to`].
1412type MoveToFn = fn(
1413    &mut App,
1414    HandleId,
1415    f64,
1416    Option<Duration>,
1417    Option<Rc<dyn Curve>>,
1418    Option<bool>,
1419) -> CompleterFuture<()>;
1420
1421/// The dispatch signature of [`ScrollPosition::ensure_visible`].
1422type EnsureVisibleFn = fn(
1423    &mut App,
1424    HandleId,
1425    AnyRenderObject,
1426    f64,
1427    Duration,
1428    Rc<dyn Curve>,
1429    ScrollPositionAlignmentPolicy,
1430    Option<AnyRenderObject>,
1431) -> CompleterFuture<()>;
1432
1433/// The vtable of an erased [`AnyScrollPosition`]: one `&'static` table per concrete
1434/// [`ScrollPosition`] type.
1435struct ScrollPositionVTable {
1436    type_id: fn() -> TypeId,
1437    add_listener: fn(&mut App, HandleId, Listener),
1438    remove_listener: fn(&mut App, HandleId, &Listener),
1439    as_viewport_offset: fn(HandleId) -> AnyViewportOffset,
1440    physics: fn(&App, HandleId) -> ScrollPhysicsRef,
1441    context: fn(&App, HandleId) -> Rc<dyn ScrollContext>,
1442    keep_scroll_offset: fn(&App, HandleId) -> bool,
1443    debug_label: fn(&App, HandleId) -> Option<String>,
1444    min_scroll_extent: fn(&App, HandleId) -> f64,
1445    max_scroll_extent: fn(&App, HandleId) -> f64,
1446    has_content_dimensions: fn(&App, HandleId) -> bool,
1447    pixels: fn(&App, HandleId) -> f64,
1448    has_pixels: fn(&App, HandleId) -> bool,
1449    viewport_dimension: fn(&App, HandleId) -> f64,
1450    has_viewport_dimension: fn(&App, HandleId) -> bool,
1451    axis_direction: fn(&App, HandleId) -> AxisDirection,
1452    device_pixel_ratio: fn(&App, HandleId) -> f64,
1453    copy_with: fn(&App, HandleId) -> Rc<dyn ScrollMetrics>,
1454    have_dimensions: fn(&App, HandleId) -> bool,
1455    should_ignore_pointer: fn(&App, HandleId) -> bool,
1456    absorb: fn(&mut App, HandleId, AnyScrollPosition),
1457    take_activity: fn(&mut App, HandleId) -> Option<ScrollActivityRef>,
1458    set_pixels: fn(&mut App, HandleId, f64) -> f64,
1459    correct_pixels: fn(&mut App, HandleId, f64),
1460    correct_by: fn(&mut App, HandleId, f64),
1461    apply_viewport_dimension: fn(&mut App, HandleId, f64) -> bool,
1462    apply_content_dimensions: fn(&mut App, HandleId, f64, f64) -> bool,
1463    ensure_visible: EnsureVisibleFn,
1464    is_scrolling_notifier: fn(&App, HandleId) -> Handle<ValueNotifier<bool>>,
1465    animate_to: AnimateToFn,
1466    jump_to: fn(&mut App, HandleId, f64),
1467    pointer_scroll: fn(&mut App, HandleId, f64),
1468    move_to: MoveToFn,
1469    user_scroll_direction: fn(&App, HandleId) -> ScrollDirection,
1470    allow_implicit_scrolling: fn(&App, HandleId) -> bool,
1471    jump_to_without_settling: fn(&mut App, HandleId, f64),
1472    hold: fn(&mut App, HandleId, Listener) -> Rc<dyn ScrollHoldController>,
1473    drag: fn(&mut App, HandleId, DragStartDetails, Listener) -> Rc<dyn Drag>,
1474    restore_offset: fn(&mut App, HandleId, f64, bool),
1475    activity: fn(&App, HandleId) -> Option<AnyScrollActivity>,
1476    begin_activity: fn(&mut App, HandleId, Option<ScrollActivityRef>),
1477    did_start_scroll: fn(&mut App, HandleId),
1478    did_update_scroll_position_by: fn(&mut App, HandleId, f64),
1479    did_end_scroll: fn(&mut App, HandleId),
1480    did_overscroll_by: fn(&mut App, HandleId, f64),
1481    did_update_scroll_direction: fn(&mut App, HandleId, ScrollDirection),
1482    did_update_scroll_metrics: fn(&mut App, HandleId),
1483    recommend_deferred_loading: fn(&mut App, HandleId, BuildContext) -> bool,
1484    dispose: fn(&mut App, HandleId),
1485    to_string: fn(&App, HandleId) -> String,
1486}
1487
1488impl ScrollPositionVTable {
1489    /// The table for one concrete position type.
1490    #[allow(deprecated)]
1491    const fn of<P: ScrollPosition>() -> ScrollPositionVTable {
1492        ScrollPositionVTable {
1493            type_id: TypeId::of::<P>,
1494            add_listener: |app, id, listener| {
1495                ListenableObject::add_listener(resolve::<P>(id), app, listener);
1496            },
1497            remove_listener: |app, id, listener| {
1498                ListenableObject::remove_listener(resolve::<P>(id), app, listener);
1499            },
1500            as_viewport_offset: |id| P::as_viewport_offset(resolve(id)),
1501            physics: |app, id| P::physics(resolve(id), app),
1502            context: |app, id| P::context(resolve(id), app),
1503            keep_scroll_offset: |app, id| P::keep_scroll_offset(resolve(id), app),
1504            debug_label: |app, id| P::debug_label(resolve(id), app).map(str::to_string),
1505            min_scroll_extent: |app, id| P::min_scroll_extent(resolve(id), app),
1506            max_scroll_extent: |app, id| P::max_scroll_extent(resolve(id), app),
1507            has_content_dimensions: |app, id| P::has_content_dimensions(resolve(id), app),
1508            pixels: |app, id| P::pixels(resolve(id), app),
1509            has_pixels: |app, id| P::has_pixels(resolve(id), app),
1510            viewport_dimension: |app, id| P::viewport_dimension(resolve(id), app),
1511            has_viewport_dimension: |app, id| P::has_viewport_dimension(resolve(id), app),
1512            axis_direction: |app, id| P::axis_direction(resolve(id), app),
1513            device_pixel_ratio: |app, id| P::device_pixel_ratio(resolve(id), app),
1514            copy_with: |app, id| P::copy_with(resolve(id), app),
1515            have_dimensions: |app, id| P::have_dimensions(resolve(id), app),
1516            should_ignore_pointer: |app, id| P::should_ignore_pointer(resolve(id), app),
1517            absorb: |app, id, other| P::absorb(resolve(id), app, other),
1518            take_activity: |app, id| {
1519                P::scroll_position_data_mut(resolve::<P>(id), app)
1520                    .activity
1521                    .take()
1522            },
1523            set_pixels: |app, id, pixels| P::set_pixels(resolve(id), app, pixels),
1524            correct_pixels: |app, id, value| P::correct_pixels(resolve(id), app, value),
1525            correct_by: |app, id, correction| P::correct_by(resolve(id), app, correction),
1526            apply_viewport_dimension: |app, id, dimension| {
1527                P::apply_viewport_dimension(resolve(id), app, dimension)
1528            },
1529            apply_content_dimensions: |app, id, min, max| {
1530                P::apply_content_dimensions(resolve(id), app, min, max)
1531            },
1532            ensure_visible: |app, id, object, alignment, duration, curve, policy, target| {
1533                P::ensure_visible(
1534                    resolve(id),
1535                    app,
1536                    object,
1537                    alignment,
1538                    duration,
1539                    curve,
1540                    policy,
1541                    target,
1542                )
1543            },
1544            is_scrolling_notifier: |app, id| P::is_scrolling_notifier(resolve(id), app),
1545            animate_to: |app, id, to, duration, curve| {
1546                P::animate_to(resolve(id), app, to, duration, curve)
1547            },
1548            jump_to: |app, id, value| P::jump_to(resolve(id), app, value),
1549            pointer_scroll: |app, id, delta| P::pointer_scroll(resolve(id), app, delta),
1550            move_to: |app, id, to, duration, curve, clamp| {
1551                P::move_to(resolve(id), app, to, duration, curve, clamp)
1552            },
1553            user_scroll_direction: |app, id| P::user_scroll_direction(resolve(id), app),
1554            allow_implicit_scrolling: |app, id| P::allow_implicit_scrolling(resolve(id), app),
1555            jump_to_without_settling: |app, id, value| {
1556                P::jump_to_without_settling(resolve(id), app, value);
1557            },
1558            hold: |app, id, callback| P::hold(resolve(id), app, callback),
1559            drag: |app, id, details, callback| P::drag(resolve(id), app, details, callback),
1560            restore_offset: |app, id, offset, initial| {
1561                P::restore_offset(resolve(id), app, offset, initial);
1562            },
1563            activity: |app, id| P::activity(resolve(id), app),
1564            begin_activity: |app, id, activity| P::begin_activity(resolve(id), app, activity),
1565            did_start_scroll: |app, id| P::did_start_scroll(resolve(id), app),
1566            did_update_scroll_position_by: |app, id, delta| {
1567                P::did_update_scroll_position_by(resolve(id), app, delta);
1568            },
1569            did_end_scroll: |app, id| P::did_end_scroll(resolve(id), app),
1570            did_overscroll_by: |app, id, value| P::did_overscroll_by(resolve(id), app, value),
1571            did_update_scroll_direction: |app, id, direction| {
1572                P::did_update_scroll_direction(resolve(id), app, direction);
1573            },
1574            did_update_scroll_metrics: |app, id| P::did_update_scroll_metrics(resolve(id), app),
1575            recommend_deferred_loading: |app, id, context| {
1576                P::recommend_deferred_loading(resolve(id), app, context)
1577            },
1578            dispose: |app, id| P::dispose(resolve(id), app),
1579            to_string: |app, id| P::to_string(resolve(id), app),
1580        }
1581    }
1582}
1583
1584/// Erased [`ScrollPosition`]: what a field or parameter Dart types as `ScrollPosition`
1585/// becomes.
1586///
1587/// Equality is Dart's `==` on an object reference.
1588#[derive(Clone, Copy)]
1589pub struct AnyScrollPosition {
1590    id: HandleId,
1591    vtable: &'static ScrollPositionVTable,
1592}
1593
1594/// A field Dart types as the erased object, kept: AnyScrollPosition with its count.
1595pub type ScrollPositionRef = Retained<AnyScrollPosition>;
1596
1597waft_foundation::erased_handle!(AnyScrollPosition: ScrollPosition => ScrollPosition::as_scroll_position);
1598
1599/// A kept position erases to a `ViewportOffsetRef` with [`Retained::erase`]: Dart's upcast of a
1600/// `ScrollPosition` to the `ViewportOffset` a viewport keeps.
1601impl From<AnyScrollPosition> for AnyViewportOffset {
1602    fn from(position: AnyScrollPosition) -> AnyViewportOffset {
1603        position.as_viewport_offset()
1604    }
1605}
1606
1607impl AnyScrollPosition {
1608    /// Dart's `position.runtimeType`.
1609    /// The identity a dump shows, Dart's `describeIdentity(position)` without the description
1610    /// Dart's `toString` collects.
1611    pub fn identity_hash(self) -> u64 {
1612        self.id.identity_hash()
1613    }
1614
1615    pub fn type_id(self) -> TypeId {
1616        (self.vtable.type_id)()
1617    }
1618
1619    /// The typed handle, when this position is a `P`; Dart's `position is P`.
1620    pub fn downcast<P: ScrollPosition>(self, app: &App) -> Option<Handle<P>> {
1621        app.handle::<P>(self.id)
1622    }
1623
1624    /// This position as an erased [`ViewportOffset`].
1625    pub fn as_viewport_offset(self) -> AnyViewportOffset {
1626        (self.vtable.as_viewport_offset)(self.id)
1627    }
1628
1629    /// See [`ScrollPosition::physics`].
1630    pub fn physics(self, app: &App) -> ScrollPhysicsRef {
1631        (self.vtable.physics)(app, self.id)
1632    }
1633
1634    /// See [`ScrollPosition::context`].
1635    pub fn context(self, app: &App) -> Rc<dyn ScrollContext> {
1636        (self.vtable.context)(app, self.id)
1637    }
1638
1639    /// See [`ScrollPosition::keep_scroll_offset`].
1640    pub fn keep_scroll_offset(self, app: &App) -> bool {
1641        (self.vtable.keep_scroll_offset)(app, self.id)
1642    }
1643
1644    /// See [`ScrollPosition::debug_label`].
1645    pub fn debug_label(self, app: &App) -> Option<String> {
1646        (self.vtable.debug_label)(app, self.id)
1647    }
1648
1649    /// See [`ScrollMetrics::min_scroll_extent`].
1650    pub fn min_scroll_extent(self, app: &App) -> f64 {
1651        (self.vtable.min_scroll_extent)(app, self.id)
1652    }
1653
1654    /// See [`ScrollMetrics::max_scroll_extent`].
1655    pub fn max_scroll_extent(self, app: &App) -> f64 {
1656        (self.vtable.max_scroll_extent)(app, self.id)
1657    }
1658
1659    /// See [`ScrollMetrics::has_content_dimensions`].
1660    pub fn has_content_dimensions(self, app: &App) -> bool {
1661        (self.vtable.has_content_dimensions)(app, self.id)
1662    }
1663
1664    /// See [`ViewportOffset::pixels`].
1665    pub fn pixels(self, app: &App) -> f64 {
1666        (self.vtable.pixels)(app, self.id)
1667    }
1668
1669    /// See [`ViewportOffset::has_pixels`].
1670    pub fn has_pixels(self, app: &App) -> bool {
1671        (self.vtable.has_pixels)(app, self.id)
1672    }
1673
1674    /// See [`ScrollMetrics::viewport_dimension`].
1675    pub fn viewport_dimension(self, app: &App) -> f64 {
1676        (self.vtable.viewport_dimension)(app, self.id)
1677    }
1678
1679    /// See [`ScrollMetrics::has_viewport_dimension`].
1680    pub fn has_viewport_dimension(self, app: &App) -> bool {
1681        (self.vtable.has_viewport_dimension)(app, self.id)
1682    }
1683
1684    /// See [`ScrollMetrics::axis_direction`].
1685    pub fn axis_direction(self, app: &App) -> AxisDirection {
1686        (self.vtable.axis_direction)(app, self.id)
1687    }
1688
1689    /// See [`ScrollMetrics::axis`].
1690    pub fn axis(self, app: &App) -> Axis {
1691        axis_direction_to_axis(self.axis_direction(app))
1692    }
1693
1694    /// See [`ScrollMetrics::device_pixel_ratio`].
1695    pub fn device_pixel_ratio(self, app: &App) -> f64 {
1696        (self.vtable.device_pixel_ratio)(app, self.id)
1697    }
1698
1699    /// See [`ScrollPosition::copy_with`].
1700    pub fn copy_with(self, app: &App) -> Rc<dyn ScrollMetrics> {
1701        (self.vtable.copy_with)(app, self.id)
1702    }
1703
1704    /// See [`ScrollMetrics::out_of_range`].
1705    pub fn out_of_range(self, app: &App) -> bool {
1706        self.copy_with(app).out_of_range()
1707    }
1708
1709    /// See [`ScrollMetrics::at_edge`].
1710    pub fn at_edge(self, app: &App) -> bool {
1711        self.copy_with(app).at_edge()
1712    }
1713
1714    /// See [`ScrollMetrics::extent_before`].
1715    pub fn extent_before(self, app: &App) -> f64 {
1716        self.copy_with(app).extent_before()
1717    }
1718
1719    /// See [`ScrollMetrics::extent_inside`].
1720    pub fn extent_inside(self, app: &App) -> f64 {
1721        self.copy_with(app).extent_inside()
1722    }
1723
1724    /// See [`ScrollMetrics::extent_after`].
1725    pub fn extent_after(self, app: &App) -> f64 {
1726        self.copy_with(app).extent_after()
1727    }
1728
1729    /// See [`ScrollMetrics::extent_total`].
1730    pub fn extent_total(self, app: &App) -> f64 {
1731        self.copy_with(app).extent_total()
1732    }
1733
1734    /// See [`ScrollPosition::have_dimensions`].
1735    pub fn have_dimensions(self, app: &App) -> bool {
1736        (self.vtable.have_dimensions)(app, self.id)
1737    }
1738
1739    /// See [`ScrollPosition::should_ignore_pointer`].
1740    pub fn should_ignore_pointer(self, app: &App) -> bool {
1741        (self.vtable.should_ignore_pointer)(app, self.id)
1742    }
1743
1744    /// See [`ScrollPosition::absorb`].
1745    pub fn absorb(self, app: &mut App, other: AnyScrollPosition) {
1746        (self.vtable.absorb)(app, self.id, other);
1747    }
1748
1749    /// Dart's `other.activity` read and then `other._activity = null` inside `absorb`.
1750    fn take_activity(self, app: &mut App) -> Option<ScrollActivityRef> {
1751        (self.vtable.take_activity)(app, self.id)
1752    }
1753
1754    /// See [`ScrollPosition::set_pixels`].
1755    pub fn set_pixels(self, app: &mut App, new_pixels: f64) -> f64 {
1756        (self.vtable.set_pixels)(app, self.id, new_pixels)
1757    }
1758
1759    /// See [`ScrollPosition::correct_pixels`].
1760    pub fn correct_pixels(self, app: &mut App, value: f64) {
1761        (self.vtable.correct_pixels)(app, self.id, value);
1762    }
1763
1764    /// See [`ViewportOffset::correct_by`].
1765    pub fn correct_by(self, app: &mut App, correction: f64) {
1766        (self.vtable.correct_by)(app, self.id, correction);
1767    }
1768
1769    /// See [`ViewportOffset::apply_viewport_dimension`].
1770    pub fn apply_viewport_dimension(self, app: &mut App, viewport_dimension: f64) -> bool {
1771        (self.vtable.apply_viewport_dimension)(app, self.id, viewport_dimension)
1772    }
1773
1774    /// See [`ViewportOffset::apply_content_dimensions`].
1775    pub fn apply_content_dimensions(
1776        self,
1777        app: &mut App,
1778        min_scroll_extent: f64,
1779        max_scroll_extent: f64,
1780    ) -> bool {
1781        (self.vtable.apply_content_dimensions)(app, self.id, min_scroll_extent, max_scroll_extent)
1782    }
1783
1784    /// See [`ScrollPosition::ensure_visible`].
1785    #[allow(clippy::too_many_arguments)]
1786    pub fn ensure_visible(
1787        self,
1788        app: &mut App,
1789        object: AnyRenderObject,
1790        alignment: f64,
1791        duration: Duration,
1792        curve: Rc<dyn Curve>,
1793        alignment_policy: ScrollPositionAlignmentPolicy,
1794        target_render_object: Option<AnyRenderObject>,
1795    ) -> CompleterFuture<()> {
1796        (self.vtable.ensure_visible)(
1797            app,
1798            self.id,
1799            object,
1800            alignment,
1801            duration,
1802            curve,
1803            alignment_policy,
1804            target_render_object,
1805        )
1806    }
1807
1808    /// See [`ScrollPosition::is_scrolling_notifier`].
1809    pub fn is_scrolling_notifier(self, app: &App) -> Handle<ValueNotifier<bool>> {
1810        (self.vtable.is_scrolling_notifier)(app, self.id)
1811    }
1812
1813    /// See [`ViewportOffset::animate_to`].
1814    pub fn animate_to(
1815        self,
1816        app: &mut App,
1817        to: f64,
1818        duration: Duration,
1819        curve: Rc<dyn Curve>,
1820    ) -> CompleterFuture<()> {
1821        (self.vtable.animate_to)(app, self.id, to, duration, curve)
1822    }
1823
1824    /// See [`ViewportOffset::jump_to`].
1825    pub fn jump_to(self, app: &mut App, value: f64) {
1826        (self.vtable.jump_to)(app, self.id, value);
1827    }
1828
1829    /// See [`ScrollPosition::pointer_scroll`].
1830    pub fn pointer_scroll(self, app: &mut App, delta: f64) {
1831        (self.vtable.pointer_scroll)(app, self.id, delta);
1832    }
1833
1834    /// See [`ViewportOffset::move_to`].
1835    pub fn move_to(
1836        self,
1837        app: &mut App,
1838        to: f64,
1839        duration: Option<Duration>,
1840        curve: Option<Rc<dyn Curve>>,
1841        clamp: Option<bool>,
1842    ) -> CompleterFuture<()> {
1843        (self.vtable.move_to)(app, self.id, to, duration, curve, clamp)
1844    }
1845
1846    /// See [`ViewportOffset::user_scroll_direction`].
1847    pub fn user_scroll_direction(self, app: &App) -> ScrollDirection {
1848        (self.vtable.user_scroll_direction)(app, self.id)
1849    }
1850
1851    /// See [`ViewportOffset::allow_implicit_scrolling`].
1852    pub fn allow_implicit_scrolling(self, app: &App) -> bool {
1853        (self.vtable.allow_implicit_scrolling)(app, self.id)
1854    }
1855
1856    /// See [`ScrollPosition::jump_to_without_settling`].
1857    #[deprecated(
1858        note = "This method bypasses scroll activity management and can cause inconsistent \
1859                layouts or scrolling behavior. Use jump_to or a custom ScrollPosition instead."
1860    )]
1861    pub fn jump_to_without_settling(self, app: &mut App, value: f64) {
1862        (self.vtable.jump_to_without_settling)(app, self.id, value);
1863    }
1864
1865    /// See [`ScrollPosition::hold`].
1866    pub fn hold(
1867        self,
1868        app: &mut App,
1869        hold_cancel_callback: Listener,
1870    ) -> Rc<dyn ScrollHoldController> {
1871        (self.vtable.hold)(app, self.id, hold_cancel_callback)
1872    }
1873
1874    /// See [`ScrollPosition::drag`].
1875    pub fn drag(
1876        self,
1877        app: &mut App,
1878        details: DragStartDetails,
1879        drag_cancel_callback: Listener,
1880    ) -> Rc<dyn Drag> {
1881        (self.vtable.drag)(app, self.id, details, drag_cancel_callback)
1882    }
1883
1884    /// See [`ScrollPosition::restore_offset`].
1885    pub fn restore_offset(self, app: &mut App, offset: f64, initial_restore: bool) {
1886        (self.vtable.restore_offset)(app, self.id, offset, initial_restore);
1887    }
1888
1889    /// See [`ScrollPosition::activity`].
1890    pub fn activity(self, app: &App) -> Option<AnyScrollActivity> {
1891        (self.vtable.activity)(app, self.id)
1892    }
1893
1894    /// See [`ScrollPosition::begin_activity`].
1895    pub fn begin_activity(self, app: &mut App, new_activity: Option<ScrollActivityRef>) {
1896        (self.vtable.begin_activity)(app, self.id, new_activity);
1897    }
1898
1899    /// See [`ScrollPosition::did_start_scroll`].
1900    pub fn did_start_scroll(self, app: &mut App) {
1901        (self.vtable.did_start_scroll)(app, self.id);
1902    }
1903
1904    /// See [`ScrollPosition::did_update_scroll_position_by`].
1905    pub fn did_update_scroll_position_by(self, app: &mut App, delta: f64) {
1906        (self.vtable.did_update_scroll_position_by)(app, self.id, delta);
1907    }
1908
1909    /// See [`ScrollPosition::did_end_scroll`].
1910    pub fn did_end_scroll(self, app: &mut App) {
1911        (self.vtable.did_end_scroll)(app, self.id);
1912    }
1913
1914    /// See [`ScrollPosition::did_overscroll_by`].
1915    pub fn did_overscroll_by(self, app: &mut App, value: f64) {
1916        (self.vtable.did_overscroll_by)(app, self.id, value);
1917    }
1918
1919    /// See [`ScrollPosition::did_update_scroll_direction`].
1920    pub fn did_update_scroll_direction(self, app: &mut App, direction: ScrollDirection) {
1921        (self.vtable.did_update_scroll_direction)(app, self.id, direction);
1922    }
1923
1924    /// See [`ScrollPosition::did_update_scroll_metrics`].
1925    pub fn did_update_scroll_metrics(self, app: &mut App) {
1926        (self.vtable.did_update_scroll_metrics)(app, self.id);
1927    }
1928
1929    /// See [`ScrollPosition::recommend_deferred_loading`].
1930    pub fn recommend_deferred_loading(self, app: &mut App, context: BuildContext) -> bool {
1931        (self.vtable.recommend_deferred_loading)(app, self.id, context)
1932    }
1933
1934    /// See [`ScrollPosition::dispose`].
1935    pub fn dispose(self, app: &mut App) {
1936        (self.vtable.dispose)(app, self.id);
1937    }
1938
1939    /// See [`ScrollPosition::to_string`].
1940    pub fn to_string(self, app: &App) -> String {
1941        (self.vtable.to_string)(app, self.id)
1942    }
1943}
1944
1945impl Debug for AnyScrollPosition {
1946    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1947        write!(f, "AnyScrollPosition({:?})", self.id)
1948    }
1949}
1950
1951impl Listenable for AnyScrollPosition {
1952    fn add_listener(&self, app: &mut App, listener: Listener) {
1953        (self.vtable.add_listener)(app, self.id, listener);
1954    }
1955
1956    fn remove_listener(&self, app: &mut App, listener: &Listener) {
1957        (self.vtable.remove_listener)(app, self.id, listener);
1958    }
1959}
1960
1961/// A notification that a scrollable widget's [`ScrollMetrics`] have changed.
1962///
1963/// For example, when the content of a scrollable is altered, making it larger
1964/// or smaller, this notification will be dispatched. Similarly, if the size
1965/// of the window or parent changes, the scrollable can notify of these
1966/// changes in dimensions.
1967///
1968/// The above behaviors usually do not trigger [`ScrollNotification`](crate::ScrollNotification) events,
1969/// so this is useful for listening to [`ScrollMetrics`] changes that are not
1970/// caused by the user scrolling.
1971pub struct ScrollMetricsNotification {
1972    viewport_notification: ViewportNotificationData,
1973
1974    /// Description of a scrollable widget's [`ScrollMetrics`].
1975    pub metrics: Rc<dyn ScrollMetrics>,
1976
1977    /// The build context of the widget that fired this notification.
1978    ///
1979    /// This can be used to find the scrollable widget's render objects to
1980    /// determine the size of the viewport, for instance.
1981    pub context: BuildContext,
1982}
1983
1984impl ScrollMetricsNotification {
1985    /// Creates a notification that the scrollable widget's [`ScrollMetrics`] have
1986    /// changed.
1987    pub fn new(metrics: Rc<dyn ScrollMetrics>, context: BuildContext) -> ScrollMetricsNotification {
1988        ScrollMetricsNotification {
1989            viewport_notification: ViewportNotificationData::new(),
1990            metrics,
1991            context,
1992        }
1993    }
1994
1995    /// Convert this notification to a [`ScrollNotification`](crate::ScrollNotification).
1996    ///
1997    /// This allows it to be used with [`crate::ScrollNotificationPredicate`]s.
1998    pub fn as_scroll_update(&self) -> ScrollUpdateNotification {
1999        ScrollUpdateNotification::new(self.metrics.clone(), self.context).with_depth(self.depth())
2000    }
2001}
2002
2003impl Notification for ScrollMetricsNotification {
2004    fn as_any(&self) -> &dyn Any {
2005        self
2006    }
2007
2008    fn viewport_depth(&self) -> Option<&Cell<u32>> {
2009        Some(self.viewport_notification.depth_cell())
2010    }
2011}
2012
2013impl ViewportNotificationMixin for ScrollMetricsNotification {
2014    fn viewport_notification_data(&self) -> &ViewportNotificationData {
2015        &self.viewport_notification
2016    }
2017}
2018
2019impl Debug for ScrollMetricsNotification {
2020    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2021        let mut description = Vec::new();
2022        ViewportNotificationMixin::debug_fill_description(self, &mut description);
2023        description.push(format!("{:?}", self.metrics));
2024        write!(f, "ScrollMetricsNotification({})", description.join(", "))
2025    }
2026}