Skip to main content

waft_widgets/widgets/
scroll_physics.rs

1//! Flutter counterpart: `widgets/scroll_physics.dart`.
2
3use std::any::Any;
4use std::fmt::{self, Debug};
5use std::rc::Rc;
6
7use waft_embedder::clamp_double;
8use waft_foundation::App;
9use waft_gestures::{K_MAX_FLING_VELOCITY, K_MIN_FLING_VELOCITY, K_TOUCH_SLOP};
10use waft_physics::{ScrollSpringSimulation, Simulation, SpringDescription, Tolerance};
11
12use crate::framework::BuildContext;
13use crate::view::View;
14use crate::widgets::scroll_metrics::ScrollMetrics;
15use crate::widgets::scroll_simulation::{BouncingScrollSimulation, ClampingScrollSimulation};
16
17/// A [`ScrollPhysics`] held by value: what a Dart field or parameter typed `ScrollPhysics`
18/// becomes, and what [`ScrollPhysics::apply_to`] returns.
19pub type ScrollPhysicsRef = Rc<dyn ScrollPhysics>;
20
21/// The rate at which scroll momentum will be decelerated.
22#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
23pub enum ScrollDecelerationRate {
24    /// Standard deceleration, aligned with mobile software expectations.
25    Normal,
26
27    /// Increased deceleration, aligned with desktop software expectations.
28    ///
29    /// Appropriate for use with input devices more precise than touch screens,
30    /// such as trackpads or mouse wheels.
31    Fast,
32}
33
34/// Determines the physics of a `Scrollable` widget.
35///
36/// For example, determines how the `Scrollable` will behave when the user
37/// reaches the maximum scroll extent or when the user stops scrolling.
38///
39/// When starting a physics [`Simulation`], the current scroll position and
40/// velocity are used as the initial conditions for the particle in the
41/// simulation. The movement of the particle in the simulation is then used to
42/// determine the scroll position for the widget.
43///
44/// Instead of writing your own implementors, [`parent`](Self::parent) can be used to
45/// combine [`ScrollPhysics`] objects of different types to get the desired scroll physics.
46/// For example:
47///
48/// ```text
49/// BouncingScrollPhysics::new().with_parent(Rc::new(AlwaysScrollableScrollPhysics::new()))
50/// ```
51///
52/// You can also use [`apply_to`](Self::apply_to), which is useful when you already have an
53/// instance of [`ScrollPhysics`]:
54///
55/// ```text
56/// let physics = BouncingScrollPhysics::new();
57/// let merged = physics.apply_to(Some(Rc::new(AlwaysScrollableScrollPhysics::new())));
58/// ```
59///
60/// When writing an implementor, you must override [`apply_to`](Self::apply_to) so that it
61/// returns an appropriate instance of your own type. Otherwise, types like `Scrollable`
62/// that inform a `ScrollPosition` will combine them with the default [`ScrollPhysics`]
63/// object instead of yours.
64///
65/// The base-class bodies Dart reaches with `super` live on [`ScrollPhysicsBase`], which
66/// every implementor gets for free.
67pub trait ScrollPhysics: Debug {
68    /// The value behind the erased physics, for Dart's `physics.runtimeType` — which
69    /// `ScrollableState._shouldUpdatePosition` compares along the whole parent chain.
70    fn as_any(&self) -> &dyn Any;
71
72    /// If non-null, determines the default behavior for each method.
73    ///
74    /// If an implementor of [`ScrollPhysics`] does not override a method, that implementor
75    /// will inherit an implementation from [`ScrollPhysicsBase`] that defers to
76    /// [`parent`](Self::parent). This mechanism lets you assemble novel combinations of
77    /// [`ScrollPhysics`] implementors at runtime. For example:
78    ///
79    /// ```text
80    /// BouncingScrollPhysics::new().with_parent(Rc::new(AlwaysScrollableScrollPhysics::new()))
81    /// ```
82    ///
83    /// will result in a [`ScrollPhysics`] that has the combined behavior
84    /// of [`BouncingScrollPhysics`] and [`AlwaysScrollableScrollPhysics`]:
85    /// behaviors that are not specified in [`BouncingScrollPhysics`]
86    /// (e.g. [`should_accept_user_offset`](Self::should_accept_user_offset)) will defer to
87    /// [`AlwaysScrollableScrollPhysics`].
88    fn parent(&self) -> Option<&ScrollPhysicsRef>;
89
90    /// Combines this [`ScrollPhysics`] instance with the given physics.
91    ///
92    /// The returned object uses this instance's physics when it has an
93    /// opinion, and defers to the given `ancestor` object's physics
94    /// when it does not.
95    ///
96    /// If [`parent`](Self::parent) is null then this returns a [`ScrollPhysics`] of the
97    /// same type, but where the parent has been replaced with the `ancestor`.
98    ///
99    /// If this scroll physics object already has a parent, then this
100    /// method is applied recursively and ancestor will appear at the
101    /// end of the existing chain of parents.
102    ///
103    /// Calling this method with `None` will copy the current object. This is inefficient.
104    ///
105    /// ## Implementing [`apply_to`](Self::apply_to)
106    ///
107    /// When writing a custom [`ScrollPhysics`] implementor, this method must be
108    /// implemented. If the physics type has no constructor arguments, then implementing
109    /// this method is merely a matter of calling the constructor with a parent constructed
110    /// using [`build_parent`](ScrollPhysicsBase::build_parent). If it has constructor
111    /// arguments, they must be passed here as well, so as to create a clone.
112    fn apply_to(&self, ancestor: Option<ScrollPhysicsRef>) -> ScrollPhysicsRef {
113        ScrollPhysicsBase::apply_to(self, ancestor)
114    }
115
116    /// Used by `DragScrollActivity` and other user-driven activities to convert
117    /// an offset in logical pixels as provided by the `DragUpdateDetails` into a
118    /// delta to apply (subtract from the current position) using
119    /// `ScrollActivityDelegate.setPixels`.
120    ///
121    /// This is used by some `ScrollPosition` implementors to apply friction during
122    /// overscroll situations.
123    ///
124    /// This method must not adjust parts of the offset that are entirely within
125    /// the bounds described by the given `position`.
126    ///
127    /// The given `position` is only valid during this method call. Do not keep a
128    /// reference to it to use later, as the values may update, may not update, or
129    /// may update to reflect an entirely unrelated scrollable.
130    fn apply_physics_to_user_offset(&self, position: &dyn ScrollMetrics, offset: f64) -> f64 {
131        ScrollPhysicsBase::apply_physics_to_user_offset(self, position, offset)
132    }
133
134    /// Whether the scrollable should let the user adjust the scroll offset, for
135    /// example by dragging. If [`allow_user_scrolling`](Self::allow_user_scrolling) is
136    /// false, the scrollable will never allow user input to change the scroll position.
137    ///
138    /// By default, the user can manipulate the scroll offset if, and only if,
139    /// there is actually content outside the viewport to reveal.
140    ///
141    /// The given `position` is only valid during this method call. Do not keep a
142    /// reference to it to use later, as the values may update, may not update, or
143    /// may update to reflect an entirely unrelated scrollable.
144    fn should_accept_user_offset(&self, position: &dyn ScrollMetrics) -> bool {
145        ScrollPhysicsBase::should_accept_user_offset(self, position)
146    }
147
148    /// Whether a viewport may scroll to reveal more content when a selection gesture extends
149    /// past the visible area, i.e. the viewport's edge.
150    ///
151    /// Paged scrollables that want to prevent selection gestures from revealing an adjacent page
152    /// override this to `false` in their physics, as `PageScrollPhysics` does.
153    fn allow_selection_edge_scrolling(&self) -> bool {
154        match self.parent() {
155            None => true,
156            Some(parent) => parent.allow_selection_edge_scrolling(),
157        }
158    }
159
160    /// Provides a heuristic to determine if expensive frame-bound tasks should be
161    /// deferred.
162    ///
163    /// The `velocity` parameter may be positive, negative, or zero.
164    ///
165    /// The `context` parameter normally refers to the [`BuildContext`] of the widget
166    /// making the call, such as an `Image` widget in a `ListView`.
167    ///
168    /// This can be used to determine whether decoding or fetching complex data
169    /// for the currently visible part of the viewport should be delayed
170    /// to avoid doing work that will not have a chance to appear before a new
171    /// frame is rendered.
172    ///
173    /// The default implementation is a heuristic that compares the current
174    /// scroll velocity in local logical pixels to the longest side of the window
175    /// in physical pixels. Implementors can change this heuristic by overriding
176    /// this method and providing their custom physics to the scrollable widget.
177    ///
178    /// The default implementation is stateless, and provides a point-in-time
179    /// decision about how fast the scrollable is scrolling. It would always
180    /// return true for a scrollable that is animating back and forth at high
181    /// velocity in a loop. It is assumed that callers will handle such
182    /// a case, or that a custom stateful implementation would be written that
183    /// tracks the sign of the velocity on successive calls.
184    ///
185    /// Returning true from this method indicates that the current scroll velocity
186    /// is great enough that expensive operations impacting the UI should be
187    /// deferred.
188    fn recommend_deferred_loading(
189        &self,
190        app: &mut App,
191        velocity: f64,
192        metrics: &dyn ScrollMetrics,
193        context: BuildContext,
194    ) -> bool {
195        ScrollPhysicsBase::recommend_deferred_loading(self, app, velocity, metrics, context)
196    }
197
198    /// Determines the overscroll by applying the boundary conditions.
199    ///
200    /// Called by `ScrollPosition.applyBoundaryConditions`, which is called by
201    /// `ScrollPosition.setPixels` just before the `ScrollPosition.pixels` value
202    /// is updated, to determine how much of the offset is to be clamped off and
203    /// sent to `ScrollPosition.didOverscrollBy`.
204    ///
205    /// The `value` argument is guaranteed to not equal the
206    /// [`ScrollMetrics::pixels`] of the `position` argument when this is called.
207    ///
208    /// It is possible for this method to be called when the `position` describes
209    /// an already-out-of-bounds position. In that case, the boundary conditions
210    /// should usually only prevent a further increase in the extent to which the
211    /// position is out of bounds, allowing a decrease to be applied successfully,
212    /// so that (for instance) an animation can smoothly snap an out of bounds
213    /// position to the bounds.
214    ///
215    /// This method must not clamp parts of the offset that are entirely within
216    /// the bounds described by the given `position`.
217    ///
218    /// The given `position` is only valid during this method call. Do not keep a
219    /// reference to it to use later, as the values may update, may not update, or
220    /// may update to reflect an entirely unrelated scrollable.
221    ///
222    /// ## Examples
223    ///
224    /// [`BouncingScrollPhysics`] returns zero. In other words, it allows scrolling
225    /// past the boundary unhindered.
226    ///
227    /// [`ClampingScrollPhysics`] returns the amount by which the value is beyond
228    /// the position or the boundary, whichever is furthest from the content. In
229    /// other words, it disallows scrolling past the boundary, but allows
230    /// scrolling back from being overscrolled, if for some reason the position
231    /// ends up overscrolled.
232    fn apply_boundary_conditions(&self, position: &dyn ScrollMetrics, value: f64) -> f64 {
233        ScrollPhysicsBase::apply_boundary_conditions(self, position, value)
234    }
235
236    /// Describes what the scroll position should be given new viewport dimensions.
237    ///
238    /// This is called by `ScrollPosition.correctForNewDimensions`.
239    ///
240    /// The arguments consist of the scroll metrics as they stood in the previous
241    /// frame and the scroll metrics as they now stand after the last layout,
242    /// including the position and minimum and maximum scroll extents; a flag
243    /// indicating if the current `ScrollActivity` considers that the user is
244    /// actively scrolling; and the current velocity of the scroll position, if it is being
245    /// driven by the scroll activity (this is 0.0 during a user gesture).
246    ///
247    /// The scroll metrics will be identical except for the
248    /// [`ScrollMetrics::min_scroll_extent`] and [`ScrollMetrics::max_scroll_extent`].
249    /// They are referred to as the `old_position` and `new_position` (even though they
250    /// both technically have the same "position", in the form of [`ScrollMetrics::pixels`])
251    /// because they are generated from the `ScrollPosition` before and after updating the
252    /// scroll extents.
253    ///
254    /// If the returned value does not exactly match the scroll offset given by
255    /// the `new_position` argument, then the `ScrollPosition` will call
256    /// `ScrollPosition.correctPixels` to update the new scroll position to the returned
257    /// value, and layout will be re-run. This is expensive. The new value is subject to
258    /// further manipulation by [`apply_boundary_conditions`](Self::apply_boundary_conditions).
259    ///
260    /// If the returned value _does_ match the `new_position.pixels()` scroll offset
261    /// exactly, then `ScrollPosition.applyNewDimensions` will be called next. In
262    /// that case, [`apply_boundary_conditions`](Self::apply_boundary_conditions) is not
263    /// applied to the return value.
264    ///
265    /// The given [`ScrollMetrics`] are only valid during this method call. Do not
266    /// keep references to them to use later, as the values may update, may not
267    /// update, or may update to reflect an entirely unrelated scrollable.
268    ///
269    /// The default implementation returns the [`ScrollMetrics::pixels`] of the
270    /// `new_position`, which indicates that the current scroll offset is acceptable.
271    ///
272    /// See also:
273    ///
274    ///  * [`RangeMaintainingScrollPhysics`], which is enabled by default, and
275    ///    which prevents unexpected changes to the content dimensions from
276    ///    causing the scroll position to get any further out of bounds.
277    fn adjust_position_for_new_dimensions(
278        &self,
279        old_position: &dyn ScrollMetrics,
280        new_position: &dyn ScrollMetrics,
281        is_scrolling: bool,
282        velocity: f64,
283    ) -> f64 {
284        ScrollPhysicsBase::adjust_position_for_new_dimensions(
285            self,
286            old_position,
287            new_position,
288            is_scrolling,
289            velocity,
290        )
291    }
292
293    /// Returns a simulation for ballistic scrolling starting from the given
294    /// position with the given velocity.
295    ///
296    /// This is used by `ScrollPositionWithSingleContext` in its `goBallistic` method. If
297    /// the result is non-null, `ScrollPositionWithSingleContext` will begin a
298    /// `BallisticScrollActivity` with the returned value. Otherwise, it will
299    /// begin an idle activity instead.
300    ///
301    /// The given `position` is only valid during this method call. Do not keep a
302    /// reference to it to use later, as the values may update, may not update, or
303    /// may update to reflect an entirely unrelated scrollable.
304    ///
305    /// This method can potentially be called in every frame, even in the middle
306    /// of what the user perceives as a single ballistic scroll. For example, in
307    /// a `ListView` when previously off-screen items come into view and are laid
308    /// out, this method may be called with a new [`ScrollMetrics::max_scroll_extent`].
309    /// The implementation should ensure that when the same ballistic scroll motion is still
310    /// intended, these calls have no side effects on the physics beyond continuing that
311    /// motion.
312    ///
313    /// Generally this is ensured by having the [`Simulation`] conform to a physical
314    /// metaphor of a particle in ballistic flight, where the forces on the
315    /// particle depend only on its position, velocity, and environment, and not
316    /// on the current time or any internal state. This means that the
317    /// time-derivative of [`Simulation::dx`] should be possible to write
318    /// mathematically as a function purely of the values of [`Simulation::x`],
319    /// [`Simulation::dx`], and the parameters used to construct the [`Simulation`],
320    /// independent of the time.
321    fn create_ballistic_simulation(
322        &self,
323        position: &dyn ScrollMetrics,
324        velocity: f64,
325    ) -> Option<Box<dyn Simulation>> {
326        ScrollPhysicsBase::create_ballistic_simulation(self, position, velocity)
327    }
328
329    /// The spring to use for ballistic simulations.
330    fn spring(&self) -> SpringDescription {
331        ScrollPhysicsBase::spring(self)
332    }
333
334    /// The tolerance to use for ballistic simulations.
335    fn tolerance_for(&self, metrics: &dyn ScrollMetrics) -> Tolerance {
336        ScrollPhysicsBase::tolerance_for(self, metrics)
337    }
338
339    /// The minimum distance an input pointer drag must have moved to be
340    /// considered a scroll fling gesture.
341    ///
342    /// This value is typically compared with the distance traveled along the
343    /// scrolling axis.
344    fn min_fling_distance(&self) -> f64 {
345        ScrollPhysicsBase::min_fling_distance(self)
346    }
347
348    /// The minimum velocity for an input pointer drag to be considered a
349    /// scroll fling.
350    ///
351    /// This value is typically compared with the magnitude of fling gesture's
352    /// velocity along the scrolling axis.
353    fn min_fling_velocity(&self) -> f64 {
354        ScrollPhysicsBase::min_fling_velocity(self)
355    }
356
357    /// Scroll fling velocity magnitudes will be clamped to this value.
358    fn max_fling_velocity(&self) -> f64 {
359        ScrollPhysicsBase::max_fling_velocity(self)
360    }
361
362    /// Returns the velocity carried on repeated flings.
363    ///
364    /// The function is applied to the existing scroll velocity when another
365    /// scroll drag is applied in the same direction.
366    ///
367    /// By default, physics for platforms other than iOS doesn't carry momentum.
368    fn carried_momentum(&self, existing_velocity: f64) -> f64 {
369        ScrollPhysicsBase::carried_momentum(self, existing_velocity)
370    }
371
372    /// The minimum amount of pixel distance drags must move by to start motion
373    /// the first time or after each time the drag motion stopped.
374    ///
375    /// If null, no minimum threshold is enforced.
376    fn drag_start_distance_motion_threshold(&self) -> Option<f64> {
377        ScrollPhysicsBase::drag_start_distance_motion_threshold(self)
378    }
379
380    /// Whether a viewport is allowed to change its scroll position implicitly in
381    /// response to a call to `RenderObject.showOnScreen`.
382    ///
383    /// `RenderObject.showOnScreen` is for example used to bring a text field
384    /// fully on screen after it has received focus. This property controls
385    /// whether the viewport associated with this object is allowed to change the
386    /// scroll position to fulfill such a request.
387    fn allow_implicit_scrolling(&self) -> bool {
388        true
389    }
390
391    /// Whether a viewport is allowed to change the scroll position as the result of user
392    /// input.
393    fn allow_user_scrolling(&self) -> bool {
394        true
395    }
396}
397
398/// The bodies of Dart's `ScrollPhysics` base class: what `super.foo(..)` calls.
399///
400/// A trait default cannot be reached from an implementor that overrides it, so these are
401/// associated functions on a namespace rather than a second trait: a second trait carrying
402/// Dart's method names would make every `physics.foo()` call ambiguous.
403pub struct ScrollPhysicsBase;
404
405impl ScrollPhysicsBase {
406    /// If [`parent`](ScrollPhysics::parent) is null then return `ancestor`, otherwise
407    /// recursively build a [`ScrollPhysics`] that has `ancestor` as its parent.
408    ///
409    /// This function is typically used to define [`apply_to`](ScrollPhysics::apply_to).
410    pub fn build_parent<P: ScrollPhysics + ?Sized>(
411        physics: &P,
412        ancestor: Option<ScrollPhysicsRef>,
413    ) -> Option<ScrollPhysicsRef> {
414        match physics.parent() {
415            Some(parent) => Some(parent.apply_to(ancestor)),
416            None => ancestor,
417        }
418    }
419
420    /// See [`ScrollPhysics::apply_to`].
421    pub fn apply_to<P: ScrollPhysics + ?Sized>(
422        physics: &P,
423        ancestor: Option<ScrollPhysicsRef>,
424    ) -> ScrollPhysicsRef {
425        Rc::new(PlainScrollPhysics {
426            parent: ScrollPhysicsBase::build_parent(physics, ancestor),
427        })
428    }
429
430    /// See [`ScrollPhysics::apply_physics_to_user_offset`].
431    pub fn apply_physics_to_user_offset<P: ScrollPhysics + ?Sized>(
432        physics: &P,
433        position: &dyn ScrollMetrics,
434        offset: f64,
435    ) -> f64 {
436        match physics.parent() {
437            Some(parent) => parent.apply_physics_to_user_offset(position, offset),
438            None => offset,
439        }
440    }
441
442    /// See [`ScrollPhysics::should_accept_user_offset`].
443    pub fn should_accept_user_offset<P: ScrollPhysics + ?Sized>(
444        physics: &P,
445        position: &dyn ScrollMetrics,
446    ) -> bool {
447        if !physics.allow_user_scrolling() {
448            return false;
449        }
450
451        match physics.parent() {
452            None => {
453                position.pixels() != 0.0
454                    || position.min_scroll_extent() != position.max_scroll_extent()
455            }
456            Some(parent) => parent.should_accept_user_offset(position),
457        }
458    }
459
460    /// See [`ScrollPhysics::recommend_deferred_loading`].
461    pub fn recommend_deferred_loading<P: ScrollPhysics + ?Sized>(
462        physics: &P,
463        app: &mut App,
464        velocity: f64,
465        metrics: &dyn ScrollMetrics,
466        context: BuildContext,
467    ) -> bool {
468        match physics.parent() {
469            None => {
470                let physical_size = View::of(app, context).metrics().physical_size;
471                let max_physical_pixels = physical_size[0].max(physical_size[1]);
472                velocity.abs() > max_physical_pixels
473            }
474            Some(parent) => {
475                let parent = Rc::clone(parent);
476                parent.recommend_deferred_loading(app, velocity, metrics, context)
477            }
478        }
479    }
480
481    /// See [`ScrollPhysics::apply_boundary_conditions`].
482    pub fn apply_boundary_conditions<P: ScrollPhysics + ?Sized>(
483        physics: &P,
484        position: &dyn ScrollMetrics,
485        value: f64,
486    ) -> f64 {
487        match physics.parent() {
488            Some(parent) => parent.apply_boundary_conditions(position, value),
489            None => 0.0,
490        }
491    }
492
493    /// See [`ScrollPhysics::adjust_position_for_new_dimensions`].
494    pub fn adjust_position_for_new_dimensions<P: ScrollPhysics + ?Sized>(
495        physics: &P,
496        old_position: &dyn ScrollMetrics,
497        new_position: &dyn ScrollMetrics,
498        is_scrolling: bool,
499        velocity: f64,
500    ) -> f64 {
501        match physics.parent() {
502            None => new_position.pixels(),
503            Some(parent) => parent.adjust_position_for_new_dimensions(
504                old_position,
505                new_position,
506                is_scrolling,
507                velocity,
508            ),
509        }
510    }
511
512    /// See [`ScrollPhysics::create_ballistic_simulation`].
513    pub fn create_ballistic_simulation<P: ScrollPhysics + ?Sized>(
514        physics: &P,
515        position: &dyn ScrollMetrics,
516        velocity: f64,
517    ) -> Option<Box<dyn Simulation>> {
518        physics
519            .parent()
520            .and_then(|parent| parent.create_ballistic_simulation(position, velocity))
521    }
522
523    /// See [`ScrollPhysics::spring`].
524    pub fn spring<P: ScrollPhysics + ?Sized>(physics: &P) -> SpringDescription {
525        match physics.parent() {
526            Some(parent) => parent.spring(),
527            None => k_default_spring(),
528        }
529    }
530
531    /// See [`ScrollPhysics::tolerance_for`].
532    pub fn tolerance_for<P: ScrollPhysics + ?Sized>(
533        physics: &P,
534        metrics: &dyn ScrollMetrics,
535    ) -> Tolerance {
536        match physics.parent() {
537            Some(parent) => parent.tolerance_for(metrics),
538            None => Tolerance {
539                // logical pixels per second
540                velocity: 1.0 / (0.050 * metrics.device_pixel_ratio()),
541                // logical pixels
542                distance: 1.0 / metrics.device_pixel_ratio(),
543                ..Tolerance::DEFAULT_TOLERANCE
544            },
545        }
546    }
547
548    /// See [`ScrollPhysics::min_fling_distance`].
549    pub fn min_fling_distance<P: ScrollPhysics + ?Sized>(physics: &P) -> f64 {
550        match physics.parent() {
551            Some(parent) => parent.min_fling_distance(),
552            None => K_TOUCH_SLOP,
553        }
554    }
555
556    /// See [`ScrollPhysics::min_fling_velocity`].
557    pub fn min_fling_velocity<P: ScrollPhysics + ?Sized>(physics: &P) -> f64 {
558        match physics.parent() {
559            Some(parent) => parent.min_fling_velocity(),
560            None => K_MIN_FLING_VELOCITY,
561        }
562    }
563
564    /// See [`ScrollPhysics::max_fling_velocity`].
565    pub fn max_fling_velocity<P: ScrollPhysics + ?Sized>(physics: &P) -> f64 {
566        match physics.parent() {
567            Some(parent) => parent.max_fling_velocity(),
568            None => K_MAX_FLING_VELOCITY,
569        }
570    }
571
572    /// See [`ScrollPhysics::carried_momentum`].
573    pub fn carried_momentum<P: ScrollPhysics + ?Sized>(physics: &P, existing_velocity: f64) -> f64 {
574        match physics.parent() {
575            Some(parent) => parent.carried_momentum(existing_velocity),
576            None => 0.0,
577        }
578    }
579
580    /// See [`ScrollPhysics::drag_start_distance_motion_threshold`].
581    pub fn drag_start_distance_motion_threshold<P: ScrollPhysics + ?Sized>(
582        physics: &P,
583    ) -> Option<f64> {
584        physics
585            .parent()
586            .and_then(|parent| parent.drag_start_distance_motion_threshold())
587    }
588}
589
590fn k_default_spring() -> SpringDescription {
591    SpringDescription::with_damping_ratio_value(0.5, 100.0, 1.1)
592}
593
594/// Dart's `ScrollPhysics.toString`: the runtime type, then the parent chain.
595fn fmt_scroll_physics(
596    f: &mut fmt::Formatter<'_>,
597    name: &str,
598    parent: Option<&ScrollPhysicsRef>,
599) -> fmt::Result {
600    match parent {
601        None => write!(f, "{name}"),
602        Some(parent) => write!(f, "{name} -> {parent:?}"),
603    }
604}
605
606/// Dart's concrete `ScrollPhysics` base class: physics that only ever defer to their
607/// parent.
608///
609/// This is what Dart writes as `const ScrollPhysics()`, and what
610/// [`ScrollPhysicsBase::apply_to`] returns.
611#[derive(Default)]
612pub struct PlainScrollPhysics {
613    /// See [`ScrollPhysics::parent`].
614    pub parent: Option<ScrollPhysicsRef>,
615}
616
617impl PlainScrollPhysics {
618    /// Creates an object with the default scroll physics.
619    pub fn new() -> PlainScrollPhysics {
620        PlainScrollPhysics::default()
621    }
622
623    /// Dart `ScrollPhysics(parent:)`.
624    pub fn with_parent(mut self, parent: ScrollPhysicsRef) -> PlainScrollPhysics {
625        self.parent = Some(parent);
626        self
627    }
628}
629
630impl ScrollPhysics for PlainScrollPhysics {
631    fn as_any(&self) -> &dyn Any {
632        self
633    }
634
635    fn parent(&self) -> Option<&ScrollPhysicsRef> {
636        self.parent.as_ref()
637    }
638}
639
640impl Debug for PlainScrollPhysics {
641    /// Dart's `objectRuntimeType(this, 'ScrollPhysics')`: this is that class.
642    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
643        fmt_scroll_physics(f, "ScrollPhysics", self.parent.as_ref())
644    }
645}
646
647/// Scroll physics that attempt to keep the scroll position in range when the
648/// contents change dimensions suddenly.
649///
650/// This attempts to maintain the amount of overscroll or underscroll already present,
651/// if the scroll position is already out of range _and_ the extents
652/// have decreased, meaning that some content was removed. The reason for this
653/// condition is that when new content is added, keeping the same overscroll
654/// would mean that instead of showing it to the user, all of it is
655/// being skipped by jumping right to the max extent.
656///
657/// If the scroll activity is animating the scroll position, sudden changes to
658/// the scroll dimensions are allowed to happen (so as to prevent animations
659/// from jumping back and forth between in-range and out-of-range values).
660///
661/// These physics should be combined with other scroll physics, e.g.
662/// [`BouncingScrollPhysics`] or [`ClampingScrollPhysics`], to obtain a complete
663/// description of typical scroll physics. See [`ScrollPhysics::apply_to`].
664///
665/// ## Implementation details
666///
667/// Specifically, these physics perform two adjustments.
668///
669/// The first is to maintain overscroll when the position is out of range.
670///
671/// The second is to enforce the boundary when the position is in range.
672///
673/// If the current velocity is non-zero, neither adjustment is made. The
674/// assumption is that there is an ongoing animation and therefore
675/// further changing the scroll position would disrupt the experience.
676///
677/// If the extents haven't changed, then the overscroll adjustment is
678/// not made. The assumption is that if the position is overscrolled,
679/// it is intentional, otherwise the position could not have reached
680/// that position. (Consider [`ClampingScrollPhysics`] vs
681/// [`BouncingScrollPhysics`] for example.)
682///
683/// If the position itself changed since the last animation frame,
684/// then the overscroll is not maintained. The assumption is similar
685/// to the previous case: the position would not have been placed out
686/// of range unless it was intentional.
687///
688/// In addition, if the position changed and the boundaries were and
689/// still are finite, then the boundary isn't enforced either, for
690/// the same reason. However, if any of the boundaries were or are
691/// now infinite, the boundary _is_ enforced, on the assumption that
692/// infinite boundaries indicate a lazy-loading scroll view, which
693/// cannot enforce boundaries while the full list has not loaded.
694///
695/// If the range was out of range, then the boundary is not enforced
696/// even if the range is not maintained. If the range is maintained,
697/// then the distance between the old position and the old boundary is
698/// applied to the new boundary to obtain the new position.
699///
700/// If the range was in range, and the boundary is to be enforced,
701/// then the new position is obtained by deferring to the other physics,
702/// if any, and then clamped to the new range.
703#[derive(Default)]
704pub struct RangeMaintainingScrollPhysics {
705    /// See [`ScrollPhysics::parent`].
706    pub parent: Option<ScrollPhysicsRef>,
707}
708
709impl RangeMaintainingScrollPhysics {
710    /// Creates scroll physics that maintain the scroll position in range.
711    pub fn new() -> RangeMaintainingScrollPhysics {
712        RangeMaintainingScrollPhysics::default()
713    }
714
715    /// Dart `RangeMaintainingScrollPhysics(parent:)`.
716    pub fn with_parent(mut self, parent: ScrollPhysicsRef) -> RangeMaintainingScrollPhysics {
717        self.parent = Some(parent);
718        self
719    }
720}
721
722impl ScrollPhysics for RangeMaintainingScrollPhysics {
723    fn as_any(&self) -> &dyn Any {
724        self
725    }
726
727    fn parent(&self) -> Option<&ScrollPhysicsRef> {
728        self.parent.as_ref()
729    }
730
731    fn apply_to(&self, ancestor: Option<ScrollPhysicsRef>) -> ScrollPhysicsRef {
732        Rc::new(RangeMaintainingScrollPhysics {
733            parent: ScrollPhysicsBase::build_parent(self, ancestor),
734        })
735    }
736
737    fn adjust_position_for_new_dimensions(
738        &self,
739        old_position: &dyn ScrollMetrics,
740        new_position: &dyn ScrollMetrics,
741        is_scrolling: bool,
742        velocity: f64,
743    ) -> f64 {
744        let mut maintain_overscroll = true;
745        let mut enforce_boundary = true;
746        if velocity != 0.0 {
747            // Don't try to adjust an animating position, the jumping around
748            // would be distracting.
749            maintain_overscroll = false;
750            enforce_boundary = false;
751        }
752        if old_position.min_scroll_extent() == new_position.min_scroll_extent()
753            && old_position.max_scroll_extent() == new_position.max_scroll_extent()
754        {
755            // If the extents haven't changed then ignore overscroll.
756            maintain_overscroll = false;
757        }
758        if old_position.pixels() != new_position.pixels() {
759            // If the position has been changed already, then it might have
760            // been adjusted to expect new overscroll, so don't try to
761            // maintain the relative overscroll.
762            maintain_overscroll = false;
763            if old_position.min_scroll_extent().is_finite()
764                && old_position.max_scroll_extent().is_finite()
765                && new_position.min_scroll_extent().is_finite()
766                && new_position.max_scroll_extent().is_finite()
767            {
768                // In addition, if the position changed then we don't enforce the new
769                // boundary if both the new and previous boundaries are entirely finite.
770                // A common case where the position changes while one
771                // of the extents is infinite is a lazily-loaded list. (If the
772                // boundaries were finite, and the position changed, then we
773                // assume it was intentional.)
774                enforce_boundary = false;
775            }
776        }
777        if old_position.pixels() < old_position.min_scroll_extent()
778            || old_position.pixels() > old_position.max_scroll_extent()
779        {
780            // If the old position was out of range, then we should
781            // not try to keep the new position in range.
782            enforce_boundary = false;
783        }
784        if maintain_overscroll {
785            // Force the new position to be no more out of range than it was before, if:
786            //  * it was overscrolled, and
787            //  * the extents have decreased, meaning that some content was removed. The
788            //    reason for this condition is that when new content is added, keeping
789            //    the same overscroll would mean that instead of showing it to the user,
790            //    all of it is being skipped by jumping right to the max extent.
791            if old_position.pixels() < old_position.min_scroll_extent()
792                && new_position.min_scroll_extent() > old_position.min_scroll_extent()
793            {
794                let old_delta = old_position.min_scroll_extent() - old_position.pixels();
795                return new_position.min_scroll_extent() - old_delta;
796            }
797            if old_position.pixels() > old_position.max_scroll_extent()
798                && new_position.max_scroll_extent() < old_position.max_scroll_extent()
799            {
800                let old_delta = old_position.pixels() - old_position.max_scroll_extent();
801                return new_position.max_scroll_extent() + old_delta;
802            }
803        }
804        // If we're not forcing the overscroll, defer to other physics.
805        let mut result = ScrollPhysicsBase::adjust_position_for_new_dimensions(
806            self,
807            old_position,
808            new_position,
809            is_scrolling,
810            velocity,
811        );
812        if enforce_boundary {
813            // ...but if they put us out of range then reinforce the boundary.
814            result = clamp_double(
815                result,
816                new_position.min_scroll_extent(),
817                new_position.max_scroll_extent(),
818            );
819        }
820        result
821    }
822}
823
824impl Debug for RangeMaintainingScrollPhysics {
825    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
826        fmt_scroll_physics(f, "RangeMaintainingScrollPhysics", self.parent.as_ref())
827    }
828}
829
830/// Scroll physics for environments that allow the scroll offset to go beyond
831/// the bounds of the content, but then bounce the content back to the edge of
832/// those bounds.
833///
834/// This is the behavior typically seen on iOS.
835///
836/// [`BouncingScrollPhysics`] by itself will not create an overscroll effect if
837/// the contents of the scroll view do not extend beyond the size of the
838/// viewport. To create the overscroll and bounce effect regardless of the
839/// length of your scroll view, combine with [`AlwaysScrollableScrollPhysics`].
840///
841/// See also:
842///
843///  * `ScrollConfiguration`, which uses this to provide the default
844///    scroll behavior on iOS.
845///  * [`ClampingScrollPhysics`], which is the analogous physics for Android's
846///    clamping behavior.
847///  * [`ScrollPhysics`], for more examples of combining [`ScrollPhysics`] objects
848///    of different types to get the desired scroll physics.
849pub struct BouncingScrollPhysics {
850    /// Used to determine parameters for friction simulations.
851    pub deceleration_rate: ScrollDecelerationRate,
852
853    /// See [`ScrollPhysics::parent`].
854    pub parent: Option<ScrollPhysicsRef>,
855}
856
857impl Default for BouncingScrollPhysics {
858    fn default() -> BouncingScrollPhysics {
859        BouncingScrollPhysics {
860            deceleration_rate: ScrollDecelerationRate::Normal,
861            parent: None,
862        }
863    }
864}
865
866impl BouncingScrollPhysics {
867    /// Creates scroll physics that bounce back from the edge.
868    pub fn new() -> BouncingScrollPhysics {
869        BouncingScrollPhysics::default()
870    }
871
872    /// Dart `BouncingScrollPhysics(decelerationRate:)`.
873    pub fn with_deceleration_rate(
874        mut self,
875        deceleration_rate: ScrollDecelerationRate,
876    ) -> BouncingScrollPhysics {
877        self.deceleration_rate = deceleration_rate;
878        self
879    }
880
881    /// Dart `BouncingScrollPhysics(parent:)`.
882    pub fn with_parent(mut self, parent: ScrollPhysicsRef) -> BouncingScrollPhysics {
883        self.parent = Some(parent);
884        self
885    }
886
887    /// The multiple applied to overscroll to make it appear that scrolling past
888    /// the edge of the scrollable contents is harder than scrolling within bounds.
889    /// This is done by reducing the ratio of the scroll effect output vs the
890    /// scroll gesture input.
891    ///
892    /// This factor starts at 0.52 for [`ScrollDecelerationRate::Normal`] and 0.26 for
893    /// [`ScrollDecelerationRate::Fast`].
894    ///
895    /// The `overscroll_fraction` represents how far past the edge the user has
896    /// dragged, where 0.0 means no overscroll. As this value increases, the
897    /// friction factor decreases quadratically, making further overscroll harder.
898    pub fn friction_factor(&self, overscroll_fraction: f64) -> f64 {
899        (1.0 - overscroll_fraction).powi(2)
900            * match self.deceleration_rate {
901                ScrollDecelerationRate::Fast => 0.26,
902                ScrollDecelerationRate::Normal => 0.52,
903            }
904    }
905}
906
907fn apply_friction(extent_outside: f64, abs_delta: f64, gamma: f64) -> f64 {
908    debug_assert!(abs_delta > 0.0);
909    let mut abs_delta = abs_delta;
910    let mut total = 0.0;
911    if extent_outside > 0.0 {
912        let delta_to_limit = extent_outside / gamma;
913        if abs_delta < delta_to_limit {
914            return abs_delta * gamma;
915        }
916        total += extent_outside;
917        abs_delta -= delta_to_limit;
918    }
919    total + abs_delta
920}
921
922impl ScrollPhysics for BouncingScrollPhysics {
923    fn as_any(&self) -> &dyn Any {
924        self
925    }
926
927    fn parent(&self) -> Option<&ScrollPhysicsRef> {
928        self.parent.as_ref()
929    }
930
931    fn apply_to(&self, ancestor: Option<ScrollPhysicsRef>) -> ScrollPhysicsRef {
932        Rc::new(BouncingScrollPhysics {
933            parent: ScrollPhysicsBase::build_parent(self, ancestor),
934            deceleration_rate: self.deceleration_rate,
935        })
936    }
937
938    fn apply_physics_to_user_offset(&self, position: &dyn ScrollMetrics, offset: f64) -> f64 {
939        debug_assert!(offset != 0.0);
940        debug_assert!(position.min_scroll_extent() <= position.max_scroll_extent());
941
942        if !position.out_of_range() {
943            return offset;
944        }
945
946        let overscroll_past_start = (position.min_scroll_extent() - position.pixels()).max(0.0);
947        let overscroll_past_end = (position.pixels() - position.max_scroll_extent()).max(0.0);
948        let overscroll_past = overscroll_past_start.max(overscroll_past_end);
949        let easing = (overscroll_past_start > 0.0 && offset < 0.0)
950            || (overscroll_past_end > 0.0 && offset > 0.0);
951
952        let friction = if easing {
953            // Apply less resistance when easing the overscroll vs tensioning.
954            self.friction_factor((overscroll_past - offset.abs()) / position.viewport_dimension())
955        } else {
956            self.friction_factor(overscroll_past / position.viewport_dimension())
957        };
958        let direction = offset.signum();
959
960        if easing && self.deceleration_rate == ScrollDecelerationRate::Fast {
961            return direction * offset.abs();
962        }
963        direction * apply_friction(overscroll_past, offset.abs(), friction)
964    }
965
966    fn apply_boundary_conditions(&self, _position: &dyn ScrollMetrics, _value: f64) -> f64 {
967        0.0
968    }
969
970    fn create_ballistic_simulation(
971        &self,
972        position: &dyn ScrollMetrics,
973        velocity: f64,
974    ) -> Option<Box<dyn Simulation>> {
975        let tolerance = self.tolerance_for(position);
976        if velocity.abs() >= tolerance.velocity || position.out_of_range() {
977            return Some(Box::new(BouncingScrollSimulation::with_options(
978                position.pixels(),
979                velocity,
980                position.min_scroll_extent(),
981                position.max_scroll_extent(),
982                self.spring(),
983                match self.deceleration_rate {
984                    ScrollDecelerationRate::Fast => 1400.0,
985                    ScrollDecelerationRate::Normal => 0.0,
986                },
987                tolerance,
988            )));
989        }
990        None
991    }
992
993    // The ballistic simulation here decelerates more slowly than the one for
994    // ClampingScrollPhysics so we require a more deliberate input gesture
995    // to trigger a fling.
996    fn min_fling_velocity(&self) -> f64 {
997        K_MIN_FLING_VELOCITY * 2.0
998    }
999
1000    // Methodology:
1001    // 1- Use https://github.com/flutter/platform_tests/tree/main/scroll_overlay to test with
1002    //    Flutter and platform scroll views superimposed.
1003    // 3- If the scrollables stopped overlapping at any moment, adjust the desired
1004    //    output value of this function at that input speed.
1005    // 4- Feed new input/output set into a power curve fitter. Change function
1006    //    and repeat from 2.
1007    // 5- Repeat from 2 with medium and slow flings.
1008    /// Momentum build-up function that mimics iOS's scroll speed increase with repeated
1009    /// flings.
1010    ///
1011    /// The velocity of the last fling is not an important factor. Existing speed
1012    /// and (related) time since last fling are factors for the velocity transfer
1013    /// calculations.
1014    fn carried_momentum(&self, existing_velocity: f64) -> f64 {
1015        existing_velocity.signum() * (0.000816 * existing_velocity.abs().powf(1.967)).min(40000.0)
1016    }
1017
1018    // Eyeballed from observation to counter the effect of an unintended scroll
1019    // from the natural motion of lifting the finger after a scroll.
1020    fn drag_start_distance_motion_threshold(&self) -> Option<f64> {
1021        Some(3.5)
1022    }
1023
1024    fn max_fling_velocity(&self) -> f64 {
1025        match self.deceleration_rate {
1026            ScrollDecelerationRate::Fast => K_MAX_FLING_VELOCITY * 8.0,
1027            ScrollDecelerationRate::Normal => ScrollPhysicsBase::max_fling_velocity(self),
1028        }
1029    }
1030
1031    fn spring(&self) -> SpringDescription {
1032        match self.deceleration_rate {
1033            ScrollDecelerationRate::Fast => {
1034                SpringDescription::with_damping_ratio_value(0.3, 75.0, 1.3)
1035            }
1036            ScrollDecelerationRate::Normal => ScrollPhysicsBase::spring(self),
1037        }
1038    }
1039}
1040
1041impl Debug for BouncingScrollPhysics {
1042    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1043        fmt_scroll_physics(f, "BouncingScrollPhysics", self.parent.as_ref())
1044    }
1045}
1046
1047/// Scroll physics for environments that prevent the scroll offset from reaching
1048/// beyond the bounds of the content.
1049///
1050/// This is the behavior typically seen on Android.
1051///
1052/// See also:
1053///
1054///  * `ScrollConfiguration`, which uses this to provide the default
1055///    scroll behavior on Android.
1056///  * [`BouncingScrollPhysics`], which is the analogous physics for iOS' bouncing
1057///    behavior.
1058///  * `GlowingOverscrollIndicator`, which is used by `ScrollConfiguration` to
1059///    provide the glowing effect that is usually found with this clamping effect
1060///    on Android.
1061#[derive(Default)]
1062pub struct ClampingScrollPhysics {
1063    /// See [`ScrollPhysics::parent`].
1064    pub parent: Option<ScrollPhysicsRef>,
1065}
1066
1067impl ClampingScrollPhysics {
1068    /// Creates scroll physics that prevent the scroll offset from exceeding the
1069    /// bounds of the content.
1070    pub fn new() -> ClampingScrollPhysics {
1071        ClampingScrollPhysics::default()
1072    }
1073
1074    /// Dart `ClampingScrollPhysics(parent:)`.
1075    pub fn with_parent(mut self, parent: ScrollPhysicsRef) -> ClampingScrollPhysics {
1076        self.parent = Some(parent);
1077        self
1078    }
1079}
1080
1081impl ScrollPhysics for ClampingScrollPhysics {
1082    fn as_any(&self) -> &dyn Any {
1083        self
1084    }
1085
1086    fn parent(&self) -> Option<&ScrollPhysicsRef> {
1087        self.parent.as_ref()
1088    }
1089
1090    fn apply_to(&self, ancestor: Option<ScrollPhysicsRef>) -> ScrollPhysicsRef {
1091        Rc::new(ClampingScrollPhysics {
1092            parent: ScrollPhysicsBase::build_parent(self, ancestor),
1093        })
1094    }
1095
1096    fn apply_boundary_conditions(&self, position: &dyn ScrollMetrics, value: f64) -> f64 {
1097        debug_assert!(
1098            value != position.pixels(),
1099            "ClampingScrollPhysics.applyBoundaryConditions() was called redundantly.\n\
1100             The proposed new position, {value}, is exactly equal to the current position \
1101             of the given ScrollMetrics, {}.\n\
1102             The applyBoundaryConditions method should only be called when the value is \
1103             going to actually change the pixels, otherwise it is redundant.",
1104            position.pixels()
1105        );
1106        if value < position.pixels() && position.pixels() <= position.min_scroll_extent() {
1107            // Underscroll.
1108            return value - position.pixels();
1109        }
1110        if position.max_scroll_extent() <= position.pixels() && position.pixels() < value {
1111            // Overscroll.
1112            return value - position.pixels();
1113        }
1114        if value < position.min_scroll_extent() && position.min_scroll_extent() < position.pixels()
1115        {
1116            // Hit top edge.
1117            return value - position.min_scroll_extent();
1118        }
1119        if position.pixels() < position.max_scroll_extent() && position.max_scroll_extent() < value
1120        {
1121            // Hit bottom edge.
1122            return value - position.max_scroll_extent();
1123        }
1124        0.0
1125    }
1126
1127    fn create_ballistic_simulation(
1128        &self,
1129        position: &dyn ScrollMetrics,
1130        velocity: f64,
1131    ) -> Option<Box<dyn Simulation>> {
1132        let tolerance = self.tolerance_for(position);
1133        if position.out_of_range() {
1134            let mut end = None;
1135            if position.pixels() > position.max_scroll_extent() {
1136                end = Some(position.max_scroll_extent());
1137            }
1138            if position.pixels() < position.min_scroll_extent() {
1139                end = Some(position.min_scroll_extent());
1140            }
1141            let end = end.expect("an out-of-range position is past one of the two extents");
1142            return Some(Box::new(ScrollSpringSimulation::new(
1143                self.spring(),
1144                position.pixels(),
1145                end,
1146                velocity.min(0.0),
1147                tolerance,
1148            )));
1149        }
1150        if velocity.abs() < tolerance.velocity {
1151            return None;
1152        }
1153        if velocity > 0.0 && position.pixels() >= position.max_scroll_extent() {
1154            return None;
1155        }
1156        if velocity < 0.0 && position.pixels() <= position.min_scroll_extent() {
1157            return None;
1158        }
1159        Some(Box::new(ClampingScrollSimulation::with_options(
1160            position.pixels(),
1161            velocity,
1162            ClampingScrollSimulation::DEFAULT_FRICTION,
1163            tolerance,
1164        )))
1165    }
1166}
1167
1168impl Debug for ClampingScrollPhysics {
1169    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1170        fmt_scroll_physics(f, "ClampingScrollPhysics", self.parent.as_ref())
1171    }
1172}
1173
1174/// Scroll physics that always lets the user scroll.
1175///
1176/// This overrides the default behavior which is to disable scrolling
1177/// when there is no content to scroll. It does not override the
1178/// handling of overscrolling.
1179///
1180/// On Android, overscrolls will be clamped by default and result in an
1181/// overscroll glow. On iOS, overscrolls will load a spring that will return the
1182/// scroll view to its normal range when released.
1183///
1184/// See also:
1185///
1186///  * [`ScrollPhysics`], which can be used instead of this type when the default
1187///    behavior is desired instead.
1188///  * [`BouncingScrollPhysics`], which provides the bouncing overscroll behavior
1189///    found on iOS.
1190///  * [`ClampingScrollPhysics`], which provides the clamping overscroll behavior
1191///    found on Android.
1192#[derive(Default)]
1193pub struct AlwaysScrollableScrollPhysics {
1194    /// See [`ScrollPhysics::parent`].
1195    pub parent: Option<ScrollPhysicsRef>,
1196}
1197
1198impl AlwaysScrollableScrollPhysics {
1199    /// Creates scroll physics that always lets the user scroll.
1200    pub fn new() -> AlwaysScrollableScrollPhysics {
1201        AlwaysScrollableScrollPhysics::default()
1202    }
1203
1204    /// Dart `AlwaysScrollableScrollPhysics(parent:)`.
1205    pub fn with_parent(mut self, parent: ScrollPhysicsRef) -> AlwaysScrollableScrollPhysics {
1206        self.parent = Some(parent);
1207        self
1208    }
1209}
1210
1211impl ScrollPhysics for AlwaysScrollableScrollPhysics {
1212    fn as_any(&self) -> &dyn Any {
1213        self
1214    }
1215
1216    fn parent(&self) -> Option<&ScrollPhysicsRef> {
1217        self.parent.as_ref()
1218    }
1219
1220    fn apply_to(&self, ancestor: Option<ScrollPhysicsRef>) -> ScrollPhysicsRef {
1221        Rc::new(AlwaysScrollableScrollPhysics {
1222            parent: ScrollPhysicsBase::build_parent(self, ancestor),
1223        })
1224    }
1225
1226    fn should_accept_user_offset(&self, _position: &dyn ScrollMetrics) -> bool {
1227        true
1228    }
1229}
1230
1231impl Debug for AlwaysScrollableScrollPhysics {
1232    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1233        fmt_scroll_physics(f, "AlwaysScrollableScrollPhysics", self.parent.as_ref())
1234    }
1235}
1236
1237/// Scroll physics that does not allow the user to scroll.
1238///
1239/// See also:
1240///
1241///  * [`ScrollPhysics`], which can be used instead of this type when the default
1242///    behavior is desired instead.
1243///  * [`BouncingScrollPhysics`], which provides the bouncing overscroll behavior
1244///    found on iOS.
1245///  * [`ClampingScrollPhysics`], which provides the clamping overscroll behavior
1246///    found on Android.
1247#[derive(Default)]
1248pub struct NeverScrollableScrollPhysics {
1249    /// See [`ScrollPhysics::parent`].
1250    pub parent: Option<ScrollPhysicsRef>,
1251}
1252
1253impl NeverScrollableScrollPhysics {
1254    /// Creates scroll physics that does not let the user scroll.
1255    pub fn new() -> NeverScrollableScrollPhysics {
1256        NeverScrollableScrollPhysics::default()
1257    }
1258
1259    /// Dart `NeverScrollableScrollPhysics(parent:)`.
1260    pub fn with_parent(mut self, parent: ScrollPhysicsRef) -> NeverScrollableScrollPhysics {
1261        self.parent = Some(parent);
1262        self
1263    }
1264}
1265
1266impl ScrollPhysics for NeverScrollableScrollPhysics {
1267    fn as_any(&self) -> &dyn Any {
1268        self
1269    }
1270
1271    fn parent(&self) -> Option<&ScrollPhysicsRef> {
1272        self.parent.as_ref()
1273    }
1274
1275    fn apply_to(&self, ancestor: Option<ScrollPhysicsRef>) -> ScrollPhysicsRef {
1276        Rc::new(NeverScrollableScrollPhysics {
1277            parent: ScrollPhysicsBase::build_parent(self, ancestor),
1278        })
1279    }
1280
1281    fn allow_implicit_scrolling(&self) -> bool {
1282        false
1283    }
1284
1285    fn allow_user_scrolling(&self) -> bool {
1286        false
1287    }
1288}
1289
1290impl Debug for NeverScrollableScrollPhysics {
1291    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1292        fmt_scroll_physics(f, "NeverScrollableScrollPhysics", self.parent.as_ref())
1293    }
1294}
1295
1296#[cfg(test)]
1297mod tests {
1298    use waft_painting::AxisDirection;
1299
1300    use super::*;
1301    use crate::widgets::scroll_metrics::FixedScrollMetrics;
1302
1303    /// `scroll_physics_test.dart`'s `TestScrollPhysics`: physics that name themselves so a
1304    /// chain of parents can be read back.
1305    struct TestScrollPhysics {
1306        name: &'static str,
1307        parent: Option<ScrollPhysicsRef>,
1308    }
1309
1310    impl TestScrollPhysics {
1311        fn new(name: &'static str) -> TestScrollPhysics {
1312            TestScrollPhysics { name, parent: None }
1313        }
1314    }
1315
1316    impl ScrollPhysics for TestScrollPhysics {
1317        fn as_any(&self) -> &dyn Any {
1318            self
1319        }
1320
1321        fn parent(&self) -> Option<&ScrollPhysicsRef> {
1322            self.parent.as_ref()
1323        }
1324
1325        fn apply_to(&self, ancestor: Option<ScrollPhysicsRef>) -> ScrollPhysicsRef {
1326            Rc::new(TestScrollPhysics {
1327                name: self.name,
1328                parent: ScrollPhysicsBase::build_parent(self, ancestor),
1329            })
1330        }
1331    }
1332
1333    impl Debug for TestScrollPhysics {
1334        fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1335            let name = format!("TestScrollPhysics({})", self.name);
1336            fmt_scroll_physics(f, &name, self.parent.as_ref())
1337        }
1338    }
1339
1340    fn metrics(pixels: f64) -> FixedScrollMetrics {
1341        FixedScrollMetrics::new(
1342            Some(0.0),
1343            Some(1000.0),
1344            Some(pixels),
1345            Some(100.0),
1346            AxisDirection::Down,
1347            3.0,
1348        )
1349    }
1350
1351    /// `scroll_physics_test.dart`: "ScrollPhysics applyTo()".
1352    #[test]
1353    fn apply_to_appends_the_ancestor_to_the_end_of_the_parent_chain() {
1354        let a = TestScrollPhysics::new("a");
1355        let b = TestScrollPhysics::new("b");
1356        let c = TestScrollPhysics::new("c");
1357        let d = TestScrollPhysics::new("d");
1358        let e = TestScrollPhysics::new("e");
1359
1360        assert!(a.parent().is_none());
1361        assert!(b.parent().is_none());
1362        assert!(c.parent().is_none());
1363
1364        let ab = a.apply_to(Some(Rc::new(b)));
1365        assert_eq!(
1366            format!("{ab:?}"),
1367            "TestScrollPhysics(a) -> TestScrollPhysics(b)"
1368        );
1369
1370        let abc = ab.apply_to(Some(Rc::new(c)));
1371        assert_eq!(
1372            format!("{abc:?}"),
1373            "TestScrollPhysics(a) -> TestScrollPhysics(b) -> TestScrollPhysics(c)"
1374        );
1375
1376        let de = d.apply_to(Some(Rc::new(e)));
1377        assert_eq!(
1378            format!("{de:?}"),
1379            "TestScrollPhysics(d) -> TestScrollPhysics(e)"
1380        );
1381
1382        let abcde = abc.apply_to(Some(de));
1383        assert_eq!(
1384            format!("{abcde:?}"),
1385            "TestScrollPhysics(a) -> TestScrollPhysics(b) -> TestScrollPhysics(c) \
1386             -> TestScrollPhysics(d) -> TestScrollPhysics(e)"
1387        );
1388    }
1389
1390    /// `scroll_physics_test.dart`: "ScrollPhysics subclasses applyTo()".
1391    #[test]
1392    fn apply_to_keeps_each_type_and_its_own_arguments() {
1393        let chain = BouncingScrollPhysics::new().apply_to(Some(
1394            ClampingScrollPhysics::new().apply_to(Some(
1395                NeverScrollableScrollPhysics::new()
1396                    .apply_to(Some(Rc::new(AlwaysScrollableScrollPhysics::new()))),
1397            )),
1398        ));
1399        assert_eq!(
1400            format!("{chain:?}"),
1401            "BouncingScrollPhysics -> ClampingScrollPhysics -> NeverScrollableScrollPhysics \
1402             -> AlwaysScrollableScrollPhysics"
1403        );
1404
1405        assert_eq!(format!("{:?}", PlainScrollPhysics::new()), "ScrollPhysics");
1406        assert_eq!(
1407            format!(
1408                "{:?}",
1409                RangeMaintainingScrollPhysics::new()
1410                    .apply_to(Some(Rc::new(ClampingScrollPhysics::new())))
1411            ),
1412            "RangeMaintainingScrollPhysics -> ClampingScrollPhysics"
1413        );
1414
1415        let desktop = BouncingScrollPhysics::new()
1416            .with_deceleration_rate(ScrollDecelerationRate::Fast)
1417            .apply_to(Some(Rc::new(AlwaysScrollableScrollPhysics::new())));
1418        // The `decelerationRate` survives the copy: only `fast` raises the fling ceiling.
1419        assert_eq!(desktop.max_fling_velocity(), K_MAX_FLING_VELOCITY * 8.0);
1420    }
1421
1422    /// `scroll_physics_test.dart`: "overscroll is progressively harder" and "no resistance
1423    /// when not overscrolled".
1424    #[test]
1425    fn bouncing_scroll_physics_applies_friction_only_past_the_edge() {
1426        let physics = BouncingScrollPhysics::new();
1427
1428        let inside = metrics(300.0);
1429        assert_eq!(physics.apply_physics_to_user_offset(&inside, 10.0), 10.0);
1430        assert_eq!(physics.apply_physics_to_user_offset(&inside, -10.0), -10.0);
1431
1432        let less = physics.apply_physics_to_user_offset(&metrics(-20.0), 10.0);
1433        let more = physics.apply_physics_to_user_offset(&metrics(-40.0), 10.0);
1434        assert!(less > 1.0 && less < 20.0);
1435        assert!(more > 1.0 && more < 20.0);
1436        // Scrolling from a more overscrolled position meets more resistance.
1437        assert!(less.abs() > more.abs());
1438
1439        // Easing an overscroll still has resistance, but less than tensioning it.
1440        let easing = physics.apply_physics_to_user_offset(&metrics(-20.0), -10.0);
1441        assert!(easing < -1.0 && easing > -10.0);
1442        assert!(easing.abs() > less.abs());
1443
1444        // `frictionFactor` starts at 0.52 (0.26 for the desktop deceleration rate).
1445        let desktop =
1446            BouncingScrollPhysics::new().with_deceleration_rate(ScrollDecelerationRate::Fast);
1447        assert_eq!(physics.friction_factor(0.0), 0.52);
1448        assert_eq!(desktop.friction_factor(0.0), 0.26);
1449        assert_eq!(
1450            desktop.apply_physics_to_user_offset(&metrics(-20.0), -10.0),
1451            -10.0
1452        );
1453
1454        // The boundary never clamps: overscroll is allowed unhindered.
1455        assert_eq!(
1456            physics.apply_boundary_conditions(&metrics(-20.0), -30.0),
1457            0.0
1458        );
1459    }
1460
1461    #[test]
1462    fn bouncing_scroll_physics_builds_a_simulation_that_bounces_back() {
1463        let physics = BouncingScrollPhysics::new();
1464        let overscrolled = metrics(-20.0);
1465        let simulation = physics
1466            .create_ballistic_simulation(&overscrolled, 0.0)
1467            .expect("an out-of-range position always gets a simulation");
1468        assert_eq!(simulation.x(0.0), -20.0);
1469
1470        let mut time = 0.0;
1471        while !simulation.is_done(time) {
1472            time += 1.0 / 60.0;
1473            assert!(time < 10.0, "the spring must settle");
1474        }
1475        assert!(
1476            simulation.x(time).abs() < 0.1,
1477            "settled at {}",
1478            simulation.x(time)
1479        );
1480
1481        // In range and at rest, there is nothing to simulate.
1482        assert!(
1483            physics
1484                .create_ballistic_simulation(&metrics(300.0), 0.0)
1485                .is_none()
1486        );
1487        // Creating the simulation does not alter the velocity at time zero.
1488        let flung = physics
1489            .create_ballistic_simulation(&metrics(20.0), 1000.0)
1490            .expect("a fling gets a simulation");
1491        assert!((flung.dx(0.0) - 1000.0).abs() < 1e-9);
1492    }
1493
1494    /// `scroll_physics_test.dart`: "ClampingScrollPhysics assertion test".
1495    #[test]
1496    fn clamping_scroll_physics_clamps_at_the_boundary() {
1497        let physics = ClampingScrollPhysics::new();
1498        let inside = metrics(500.0);
1499
1500        // Hitting an edge reports only the part beyond it.
1501        assert_eq!(physics.apply_boundary_conditions(&inside, 1500.0), 500.0);
1502        assert_eq!(physics.apply_boundary_conditions(&inside, -500.0), -500.0);
1503        // Movement that stays in range is not clamped at all.
1504        assert_eq!(physics.apply_boundary_conditions(&inside, 600.0), 0.0);
1505        assert_eq!(physics.apply_boundary_conditions(&inside, 400.0), 0.0);
1506
1507        // Already out of range: a further increase is reported, a decrease is allowed.
1508        let over = metrics(1200.0);
1509        assert_eq!(physics.apply_boundary_conditions(&over, 1300.0), 100.0);
1510        assert_eq!(physics.apply_boundary_conditions(&over, 1100.0), 0.0);
1511    }
1512
1513    #[test]
1514    fn clamping_scroll_physics_builds_a_simulation_that_stops_at_the_edge() {
1515        let physics = ClampingScrollPhysics::new();
1516
1517        let over = metrics(1200.0);
1518        let spring = physics
1519            .create_ballistic_simulation(&over, 0.0)
1520            .expect("an out-of-range position always gets a simulation");
1521        let mut time = 0.0;
1522        while !spring.is_done(time) {
1523            time += 1.0 / 60.0;
1524            assert!(time < 10.0, "the spring must settle");
1525        }
1526        assert!(
1527            (spring.x(time) - 1000.0).abs() < 0.1,
1528            "settled at {}",
1529            spring.x(time)
1530        );
1531
1532        // A fling inside the range decelerates and stops before the edge is passed.
1533        let fling = physics
1534            .create_ballistic_simulation(&metrics(20.0), 1000.0)
1535            .expect("a fling gets a simulation");
1536        assert!((fling.dx(0.0) - 1000.0).abs() < 1e-9);
1537        assert!(fling.is_done(1.0));
1538
1539        // Nothing to simulate when at rest, or when flung away from a reached edge.
1540        assert!(
1541            physics
1542                .create_ballistic_simulation(&metrics(300.0), 0.0)
1543                .is_none()
1544        );
1545        assert!(
1546            physics
1547                .create_ballistic_simulation(&metrics(1000.0), 1000.0)
1548                .is_none()
1549        );
1550        assert!(
1551            physics
1552                .create_ballistic_simulation(&metrics(0.0), -1000.0)
1553                .is_none()
1554        );
1555    }
1556
1557    #[test]
1558    fn always_and_never_scrollable_decide_whether_the_user_may_scroll() {
1559        let empty = FixedScrollMetrics::new(
1560            Some(0.0),
1561            Some(0.0),
1562            Some(0.0),
1563            Some(600.0),
1564            AxisDirection::Down,
1565            3.0,
1566        );
1567
1568        // The default: only when there is content outside the viewport to reveal.
1569        assert!(!PlainScrollPhysics::new().should_accept_user_offset(&empty));
1570        assert!(PlainScrollPhysics::new().should_accept_user_offset(&metrics(0.0)));
1571
1572        assert!(AlwaysScrollableScrollPhysics::new().should_accept_user_offset(&empty));
1573
1574        let never = NeverScrollableScrollPhysics::new();
1575        assert!(!never.should_accept_user_offset(&metrics(0.0)));
1576        assert!(!never.allow_user_scrolling());
1577        assert!(!never.allow_implicit_scrolling());
1578        // `allowUserScrolling` wins over an ancestor that always scrolls.
1579        let never_over_always = NeverScrollableScrollPhysics::new()
1580            .apply_to(Some(Rc::new(AlwaysScrollableScrollPhysics::new())));
1581        assert!(!never_over_always.should_accept_user_offset(&empty));
1582    }
1583
1584    #[test]
1585    fn a_parent_answers_what_this_physics_has_no_opinion_on() {
1586        let bouncing_over_always = BouncingScrollPhysics::new()
1587            .apply_to(Some(Rc::new(AlwaysScrollableScrollPhysics::new())));
1588        // `BouncingScrollPhysics` does not override `shouldAcceptUserOffset`.
1589        let empty = FixedScrollMetrics::new(
1590            Some(0.0),
1591            Some(0.0),
1592            Some(0.0),
1593            Some(600.0),
1594            AxisDirection::Down,
1595            3.0,
1596        );
1597        assert!(bouncing_over_always.should_accept_user_offset(&empty));
1598        // ...but it keeps its own fling floor and momentum.
1599        assert_eq!(
1600            bouncing_over_always.min_fling_velocity(),
1601            K_MIN_FLING_VELOCITY * 2.0
1602        );
1603        assert_eq!(
1604            bouncing_over_always.drag_start_distance_motion_threshold(),
1605            Some(3.5)
1606        );
1607        assert_eq!(PlainScrollPhysics::new().carried_momentum(1000.0), 0.0);
1608        assert!(BouncingScrollPhysics::new().carried_momentum(1000.0) > 0.0);
1609        assert_eq!(PlainScrollPhysics::new().min_fling_distance(), K_TOUCH_SLOP);
1610    }
1611
1612    #[test]
1613    fn range_maintaining_physics_keeps_the_overscroll_when_content_shrinks() {
1614        let physics = RangeMaintainingScrollPhysics::new();
1615        let old = FixedScrollMetrics::new(
1616            Some(0.0),
1617            Some(1000.0),
1618            Some(1100.0),
1619            Some(600.0),
1620            AxisDirection::Down,
1621            3.0,
1622        );
1623        let new = old.copy_with().with_max_scroll_extent(800.0);
1624        // The 100 pixels of overscroll survive the smaller extent.
1625        assert_eq!(
1626            physics.adjust_position_for_new_dimensions(&old, &new, false, 0.0),
1627            900.0
1628        );
1629
1630        // An in-range position is pushed back inside the new boundary.
1631        let old_inside = old.copy_with().with_pixels(900.0);
1632        let new_inside = old_inside.copy_with().with_max_scroll_extent(800.0);
1633        assert_eq!(
1634            physics.adjust_position_for_new_dimensions(&old_inside, &new_inside, false, 0.0),
1635            800.0
1636        );
1637
1638        // An animating position is left alone.
1639        assert_eq!(
1640            physics.adjust_position_for_new_dimensions(&old_inside, &new_inside, true, 10.0),
1641            900.0
1642        );
1643    }
1644}