Skip to main content

waft_widgets/widgets/
overscroll_indicator.rs

1//! Flutter counterpart: `widgets/overscroll_indicator.dart`.
2//!
3//! The glow and the stretch each answer an overscroll with a confirmation
4//! [`OverscrollIndicatorNotification`] dispatched on every `OverscrollNotification`: Dart's
5//! guards, `_lastNotificationType is! OverscrollNotification` and
6//! `_lastNotification.runtimeType is! OverscrollNotification`, test a `Type`, which is never
7//! an `OverscrollNotification`, so they always hold. Keep it so until Flutter changes it, or a
8//! listener's answers drift from Flutter's.
9
10use std::cell::Cell;
11use std::fmt::{self, Debug};
12use std::rc::Rc;
13use std::time::Duration;
14
15use waft_animation::{
16    Animation, AnimationBehavior, AnimationController, AnimationRef, AnimationStatus,
17    AnimationStatusListener, AnyAnimation, CurvedAnimation, Curves, Drive, Tween,
18};
19use waft_embedder::{Canvas, Clip, ClipOp, Color, Offset, Paint, Rect, Size, clamp_double};
20use waft_foundation::{
21    App, ChangeNotifier, ChangeNotifierData, DiagnosticPropertiesBuilder, EnumProperty, Handle,
22    Listenable, ListenableObject, Listener, MessageProperty, OptionRetained, Timer, ValueNotifier,
23};
24use waft_painting::{Axis, AxisDirection, ColorProperty, axis_direction_to_axis};
25use waft_physics::{Simulation, SpringDescription, SpringSimulation, Tolerance, near_equal};
26use waft_rendering::{
27    CustomPainter, GrowthDirection, TickerProviderRef, apply_growth_direction_to_axis_direction,
28};
29use waft_scheduler::{FrameCallback, Ticker, TickerCallback, TickerProvider, TickerProviderObject};
30
31use crate::framework::{
32    BuildContext, IntoWidget, KeyRef, Notification, State, StateData, StatefulWidget, WidgetRef,
33};
34use crate::widgets::basic::{ClipRect, CustomPaint, RepaintBoundary, SizedBox};
35use crate::widgets::media_query::MediaQuery;
36use crate::widgets::notification_listener::NotificationListener;
37use crate::widgets::scroll_notification::{
38    OverscrollNotification, ScrollEndNotification, ScrollNotification, ScrollNotificationPredicate,
39    ScrollStartNotification, ScrollUpdateNotification, ViewportNotificationData,
40    ViewportNotificationMixin, default_scroll_notification_predicate,
41};
42use crate::widgets::stretch_effect::StretchEffect;
43use crate::widgets::ticker_provider::{TickerProviderStateMixin, TickerProviderStateMixinData};
44use crate::widgets::transitions::AnimatedBuilder;
45use waft_foundation::Ref;
46
47/// A visual indication that a scroll view has overscrolled.
48///
49/// A [`GlowingOverscrollIndicator`] listens for [`ScrollNotification`]s in order
50/// to control the overscroll indication. These notifications are typically
51/// generated by a `ScrollView`, such as a `ListView` or a `GridView`.
52///
53/// [`GlowingOverscrollIndicator`] generates [`OverscrollIndicatorNotification`]
54/// before showing an overscroll indication. To prevent the indicator from
55/// showing the indication, call
56/// [`OverscrollIndicatorNotification::disallow_indicator`] on the notification.
57///
58/// Created automatically by `ScrollBehavior::build_overscroll_indicator` on platforms
59/// (e.g., Android) that commonly use this type of overscroll indication.
60///
61/// In a `MaterialApp`, the edge glow color is the overall theme's
62/// `ColorScheme.secondary` color.
63///
64/// ## Customizing the Glow Position for Advanced Scroll Views
65///
66/// When building a `CustomScrollView` with a [`GlowingOverscrollIndicator`], the
67/// indicator will apply to the entire scrollable area, regardless of what
68/// slivers the CustomScrollView contains.
69///
70/// For example, if your CustomScrollView contains a SliverAppBar in the first
71/// position, the GlowingOverscrollIndicator will overlay the SliverAppBar. To
72/// manipulate the position of the GlowingOverscrollIndicator in this case,
73/// you can either make use of a [`NotificationListener`] and provide a
74/// [`OverscrollIndicatorNotification::paint_offset`] to the
75/// notification, or use a `NestedScrollView`.
76///
77/// See also:
78///
79///  * [`OverscrollIndicatorNotification`], which can be used to manipulate the
80///    glow position or prevent the glow from being painted at all.
81///  * [`NotificationListener`], to listen for the
82///    [`OverscrollIndicatorNotification`].
83///  * [`StretchingOverscrollIndicator`], a Material Design overscroll indicator.
84pub struct GlowingOverscrollIndicator {
85    pub key: Option<KeyRef>,
86
87    /// Whether to show the overscroll glow on the side with negative scroll
88    /// offsets.
89    ///
90    /// For a vertical downwards viewport, this is the top side.
91    ///
92    /// Defaults to true.
93    ///
94    /// See [`show_trailing`](Self::show_trailing) for the corresponding control on the other
95    /// side of the viewport.
96    pub show_leading: bool,
97
98    /// Whether to show the overscroll glow on the side with positive scroll
99    /// offsets.
100    ///
101    /// For a vertical downwards viewport, this is the bottom side.
102    ///
103    /// Defaults to true.
104    ///
105    /// See [`show_leading`](Self::show_leading) for the corresponding control on the other
106    /// side of the viewport.
107    pub show_trailing: bool,
108
109    /// The direction of positive scroll offsets in the `Scrollable` whose
110    /// overscrolls are to be visualized.
111    pub axis_direction: AxisDirection,
112
113    /// The color of the glow. The alpha channel is ignored.
114    pub color: Color,
115
116    /// A check that specifies whether a [`ScrollNotification`] should be
117    /// handled by this widget.
118    ///
119    /// By default, checks whether `notification.depth() == 0`. Set it to something
120    /// else for more complicated layouts, such as nested `ScrollView`s.
121    pub notification_predicate: ScrollNotificationPredicate,
122
123    /// The widget below this widget in the tree.
124    ///
125    /// The overscroll indicator will paint on top of this child. This child (and its
126    /// subtree) should include a source of [`ScrollNotification`] notifications.
127    ///
128    /// Typically a [`GlowingOverscrollIndicator`] is created by a
129    /// `ScrollBehavior::build_overscroll_indicator` method, in which case
130    /// the child is usually the one provided as an argument to that method.
131    pub child: Option<WidgetRef>,
132}
133
134impl GlowingOverscrollIndicator {
135    /// Creates a visual indication that a scroll view has overscrolled.
136    ///
137    /// In order for this widget to display an overscroll indication, the [`child`](Self::child)
138    /// widget must contain a widget that generates a [`ScrollNotification`], such
139    /// as a `ListView` or a `GridView`.
140    pub fn new(axis_direction: AxisDirection, color: Color) -> GlowingOverscrollIndicator {
141        GlowingOverscrollIndicator {
142            key: None,
143            show_leading: true,
144            show_trailing: true,
145            axis_direction,
146            color,
147            notification_predicate: Rc::new(default_scroll_notification_predicate),
148            child: None,
149        }
150    }
151
152    /// Dart `GlowingOverscrollIndicator(key:)`.
153    pub fn key(mut self, key: KeyRef) -> GlowingOverscrollIndicator {
154        self.key = Some(key);
155        self
156    }
157
158    /// Dart `GlowingOverscrollIndicator(showLeading:)`.
159    pub fn show_leading(mut self, show_leading: bool) -> GlowingOverscrollIndicator {
160        self.show_leading = show_leading;
161        self
162    }
163
164    /// Dart `GlowingOverscrollIndicator(showTrailing:)`.
165    pub fn show_trailing(mut self, show_trailing: bool) -> GlowingOverscrollIndicator {
166        self.show_trailing = show_trailing;
167        self
168    }
169
170    /// Dart `GlowingOverscrollIndicator(notificationPredicate:)`.
171    pub fn notification_predicate(
172        mut self,
173        notification_predicate: ScrollNotificationPredicate,
174    ) -> GlowingOverscrollIndicator {
175        self.notification_predicate = notification_predicate;
176        self
177    }
178
179    /// Dart `GlowingOverscrollIndicator(child:)`.
180    #[cfg_attr(debug_assertions, track_caller)]
181    pub fn child<K>(mut self, child: impl IntoWidget<K>) -> GlowingOverscrollIndicator {
182        self.child = Some(child.into_widget());
183        self
184    }
185
186    /// The axis along which scrolling occurs in the `Scrollable` whose
187    /// overscrolls are to be visualized.
188    pub fn axis(&self) -> Axis {
189        axis_direction_to_axis(self.axis_direction)
190    }
191}
192
193impl Debug for GlowingOverscrollIndicator {
194    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
195        let show_description = match (self.show_leading, self.show_trailing) {
196            (true, true) => "both sides",
197            (true, false) => "leading side only",
198            (false, true) => "trailing side only",
199            (false, false) => "neither side (!)",
200        };
201        f.debug_struct("GlowingOverscrollIndicator")
202            .field("axisDirection", &self.axis_direction)
203            .field("show", &show_description)
204            .field("color", &self.color)
205            .finish_non_exhaustive()
206    }
207}
208
209impl StatefulWidget for GlowingOverscrollIndicator {
210    type State = GlowingOverscrollIndicatorState;
211
212    fn key(&self) -> Option<&KeyRef> {
213        self.key.as_ref()
214    }
215
216    fn debug_fill_properties(&self, _app: &App, properties: &mut DiagnosticPropertiesBuilder) {
217        properties.add(EnumProperty::new("axisDirection", self.axis_direction));
218        let show_description = match (self.show_leading, self.show_trailing) {
219            (true, true) => "both sides",
220            (true, false) => "leading side only",
221            (false, true) => "trailing side only",
222            (false, false) => "neither side (!)",
223        };
224        properties.add(MessageProperty::new("show", show_description));
225        properties.add(ColorProperty::new("color", self.color).with_show_name(false));
226    }
227
228    fn create_state(&self) -> GlowingOverscrollIndicatorState {
229        GlowingOverscrollIndicatorState {
230            state: StateData::new(),
231            ticker_provider: TickerProviderStateMixinData::new(),
232            leading_controller: None,
233            trailing_controller: None,
234            leading_and_trailing_listener: None,
235            accepted: [true, true],
236        }
237    }
238}
239
240/// Dart's `_GlowingOverscrollIndicatorState`.
241pub struct GlowingOverscrollIndicatorState {
242    state: StateData<GlowingOverscrollIndicator>,
243    ticker_provider: TickerProviderStateMixinData,
244    leading_controller: Option<Ref<GlowController>>,
245    trailing_controller: Option<Ref<GlowController>>,
246    leading_and_trailing_listener: Option<Rc<dyn Listenable>>,
247    /// Dart's `Map<bool, bool> _accepted`, indexed by `is_leading as usize`.
248    accepted: [bool; 2],
249}
250
251impl GlowingOverscrollIndicatorState {
252    fn leading_controller(self: Handle<Self>, app: &App) -> Handle<GlowController> {
253        app.get(self)
254            .leading_controller
255            .handle()
256            .expect("the controllers are made in init_state")
257    }
258
259    fn trailing_controller(self: Handle<Self>, app: &App) -> Handle<GlowController> {
260        app.get(self)
261            .trailing_controller
262            .handle()
263            .expect("the controllers are made in init_state")
264    }
265
266    fn handle_scroll_notification(
267        self: Handle<Self>,
268        app: &mut App,
269        notification: &dyn ScrollNotification,
270    ) -> bool {
271        let widget = self.widget(app);
272        let notification_predicate = Rc::clone(&widget.notification_predicate);
273        let axis = widget.axis();
274        if !notification_predicate(notification) {
275            return false;
276        }
277        let metrics = Rc::clone(notification.metrics());
278        if metrics.axis() != axis {
279            // This widget is explicitly configured to one axis. If a notification
280            // from a different axis bubbles up, do nothing.
281            return false;
282        }
283
284        let leading_controller = self.leading_controller(app);
285        let trailing_controller = self.trailing_controller(app);
286
287        // Update the paint offset with the current scroll position. This makes
288        // sure that the glow effect correctly scrolls in line with the current
289        // scroll, e.g. when scrolling in the opposite direction again to hide
290        // the glow. Otherwise, the glow would always stay in a fixed position,
291        // even if the top of the content already scrolled away.
292        // For example (CustomScrollView with sliver before center), the scroll
293        // extent is [-200.0, 300.0], scroll in the opposite direction with 10.0 pixels
294        // before glow disappears, so the current pixels is -190.0,
295        // in this case, we should move the glow up 10.0 pixels and should not
296        // overflow the scrollable widget's edge. https://github.com/flutter/flutter/issues/64149.
297        let leading = app.get_mut(leading_controller);
298        leading.paint_offset_scroll_pixels = -f64::min(
299            metrics.pixels() - metrics.min_scroll_extent(),
300            leading.paint_offset,
301        );
302        let trailing = app.get_mut(trailing_controller);
303        trailing.paint_offset_scroll_pixels = -f64::min(
304            metrics.max_scroll_extent() - metrics.pixels(),
305            trailing.paint_offset,
306        );
307
308        let any = notification.as_any();
309        if let Some(notification) = any.downcast_ref::<OverscrollNotification>() {
310            let controller = if notification.overscroll < 0.0 {
311                Some(leading_controller)
312            } else if notification.overscroll > 0.0 {
313                Some(trailing_controller)
314            } else {
315                debug_assert!(false);
316                None
317            };
318            let is_leading = controller == Some(leading_controller);
319            // Dart's `_lastNotificationType is! OverscrollNotification` (see the module doc).
320            let confirmation_notification = OverscrollIndicatorNotification::new(is_leading);
321            confirmation_notification.dispatch(app, Some(self.context(app)));
322            let accepted = confirmation_notification.accepted.get();
323            app.get_mut(self).accepted[is_leading as usize] = accepted;
324            if accepted {
325                let controller = controller.expect("an overscroll is on one side");
326                app.get_mut(controller).paint_offset = confirmation_notification.paint_offset.get();
327            }
328            debug_assert!(controller.is_some());
329            if app.get(self).accepted[is_leading as usize] {
330                let controller = controller.expect("an overscroll is on one side");
331                if notification.velocity != 0.0 {
332                    debug_assert!(notification.drag_details.is_none());
333                    controller.absorb_impact(app, notification.velocity.abs());
334                } else {
335                    debug_assert!(notification.overscroll != 0.0);
336                    if let Some(drag_details) = &notification.drag_details {
337                        let renderer = notification
338                            .context()
339                            .expect("a scroll notification carries the scrollable's context")
340                            .find_render_object(app)
341                            .expect("the scrollable has a render object")
342                            .as_box()
343                            .expect("the scrollable's render object is a box");
344                        debug_assert!(renderer.has_size(app));
345                        let size = renderer.size(app);
346                        let position =
347                            renderer.global_to_local(app, drag_details.global_position, None);
348                        match notification.metrics().axis() {
349                            Axis::Horizontal => controller.pull(
350                                app,
351                                notification.overscroll.abs(),
352                                size.width(),
353                                clamp_double(position.dy(), 0.0, size.height()),
354                                size.height(),
355                            ),
356                            Axis::Vertical => controller.pull(
357                                app,
358                                notification.overscroll.abs(),
359                                size.height(),
360                                clamp_double(position.dx(), 0.0, size.width()),
361                                size.width(),
362                            ),
363                        }
364                    }
365                }
366            }
367        } else if any
368            .downcast_ref::<ScrollEndNotification>()
369            .is_some_and(|notification| notification.drag_details.is_some())
370            || any
371                .downcast_ref::<ScrollUpdateNotification>()
372                .is_some_and(|notification| notification.drag_details.is_some())
373        {
374            leading_controller.scroll_end(app);
375            trailing_controller.scroll_end(app);
376        }
377        false
378    }
379}
380
381impl Debug for GlowingOverscrollIndicatorState {
382    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
383        f.debug_struct("GlowingOverscrollIndicatorState")
384            .finish_non_exhaustive()
385    }
386}
387
388impl TickerProviderStateMixin for GlowingOverscrollIndicatorState {
389    fn ticker_provider_data(self: Handle<Self>, app: &App) -> &TickerProviderStateMixinData {
390        &app.get(self).ticker_provider
391    }
392
393    fn ticker_provider_data_mut(
394        self: Handle<Self>,
395        app: &mut App,
396    ) -> &mut TickerProviderStateMixinData {
397        &mut app.get_mut(self).ticker_provider
398    }
399}
400
401impl TickerProviderObject for GlowingOverscrollIndicatorState {
402    fn create_ticker(self: Handle<Self>, app: &mut App, on_tick: TickerCallback) -> Ref<Ticker> {
403        TickerProviderStateMixin::create_ticker(self, app, on_tick)
404    }
405}
406
407impl State for GlowingOverscrollIndicatorState {
408    type Widget = GlowingOverscrollIndicator;
409    crate::state_accessors!();
410
411    fn init_state(self: Handle<Self>, app: &mut App) {
412        let widget = self.widget(app);
413        let (color, axis) = (widget.color, widget.axis());
414        let leading_controller =
415            GlowController::new(app, TickerProviderRef::new(self), color, axis);
416        let trailing_controller =
417            GlowController::new(app, TickerProviderRef::new(self), color, axis);
418        let listener: Rc<dyn Listenable> = Rc::new(waft_foundation::MergingListenable::new(vec![
419            Some(Rc::new(leading_controller.clone())),
420            Some(Rc::new(trailing_controller.clone())),
421        ]));
422        let state = app.get_mut(self);
423        state.leading_controller = Some(leading_controller);
424        state.trailing_controller = Some(trailing_controller);
425        state.leading_and_trailing_listener = Some(listener);
426    }
427
428    fn did_update_widget(
429        self: Handle<Self>,
430        app: &mut App,
431        old_widget: &GlowingOverscrollIndicator,
432    ) {
433        let widget = self.widget(app);
434        let (color, axis) = (widget.color, widget.axis());
435        if old_widget.color != color || old_widget.axis() != axis {
436            let leading_controller = self.leading_controller(app);
437            let trailing_controller = self.trailing_controller(app);
438            leading_controller.set_color(app, color);
439            leading_controller.set_axis(app, axis);
440            trailing_controller.set_color(app, color);
441            trailing_controller.set_axis(app, axis);
442        }
443    }
444
445    fn activate(self: Handle<Self>, app: &mut App) {
446        TickerProviderStateMixin::activate(self, app);
447    }
448
449    fn dispose(self: Handle<Self>, app: &mut App) {
450        self.leading_controller(app).dispose(app);
451        self.trailing_controller(app).dispose(app);
452        TickerProviderStateMixin::dispose(self, app);
453    }
454
455    fn build(self: Handle<Self>, app: &mut App, _context: BuildContext) -> WidgetRef {
456        let widget = self.widget(app);
457        let state = app.get(self);
458        let painter = GlowingOverscrollIndicatorPainter {
459            leading_controller: if widget.show_leading {
460                state.leading_controller.clone()
461            } else {
462                None
463            },
464            trailing_controller: if widget.show_trailing {
465                state.trailing_controller.clone()
466            } else {
467                None
468            },
469            axis_direction: widget.axis_direction,
470            repaint: state.leading_and_trailing_listener.clone(),
471        };
472        let mut child_boundary = RepaintBoundary::new();
473        if let Some(child) = widget.child.clone() {
474            child_boundary = child_boundary.child(child);
475        }
476        NotificationListener::<dyn ScrollNotification>::new(
477            RepaintBoundary::new().child(
478                CustomPaint::new()
479                    .foreground_painter(painter)
480                    .child(child_boundary),
481            ),
482        )
483        .on_notification(
484            move |app: &mut App, notification: &dyn ScrollNotification| {
485                self.handle_scroll_notification(app, notification)
486            },
487        )
488        .into_widget()
489    }
490}
491
492// The Glow logic is a port of the logic in the following file:
493// https://android.googlesource.com/platform/frameworks/base/+/main/core/java/android/widget/EdgeEffect.java
494// as of December 2016.
495
496#[derive(Clone, Copy, Debug, PartialEq, Eq)]
497enum GlowState {
498    Idle,
499    Absorb,
500    Pull,
501    Recede,
502}
503
504/// Dart's `_GlowController`.
505///
506/// The fields Dart declares `late final` and builds after its status listener is on the glow
507/// controller are `Option`s here, set in [`new`](Self::new) in Dart's order, so the status
508/// listeners run in Dart's order.
509struct GlowController {
510    change_notifier: ChangeNotifierData,
511
512    // animation of the main axis direction
513    state: GlowState,
514    glow_controller: Ref<AnimationController>,
515    pull_recede_timer: Option<Timer>,
516    paint_offset: f64,
517    paint_offset_scroll_pixels: f64,
518
519    // animation values
520    decelerator: Option<Ref<CurvedAnimation>>,
521    glow_opacity_tween: Ref<Tween<f64>>,
522    glow_opacity: Option<AnimationRef<f64>>,
523    glow_size_tween: Ref<Tween<f64>>,
524    glow_size: Option<AnimationRef<f64>>,
525
526    // animation of the cross axis position
527    displacement_ticker: Option<Ref<Ticker>>,
528    displacement_ticker_last_elapsed: Option<Duration>,
529    displacement_target: f64,
530    displacement: f64,
531
532    // tracking the pull distance
533    pull_distance: f64,
534
535    color: Color,
536    axis: Axis,
537}
538
539impl GlowController {
540    const RECEDE_TIME: Duration = Duration::from_millis(600);
541    const PULL_TIME: Duration = Duration::from_millis(167);
542    const PULL_HOLD_TIME: Duration = Duration::from_millis(167);
543    const PULL_DECAY_TIME: Duration = Duration::from_millis(2000);
544
545    const MAX_OPACITY: f64 = 0.5;
546    const PULL_OPACITY_GLOW_FACTOR: f64 = 0.8;
547    const VELOCITY_GLOW_FACTOR: f64 = 0.00006;
548    const SQRT3: f64 = 1.73205080757; // const math.sqrt(3)
549    const WIDTH_TO_HEIGHT_FACTOR: f64 = (3.0 / 4.0) * (2.0 - GlowController::SQRT3);
550
551    // absorbed velocities are clamped to the range MIN_VELOCITY..MAX_VELOCITY
552    const MIN_VELOCITY: f64 = 100.0; // logical pixels per second
553    const MAX_VELOCITY: f64 = 10000.0; // logical pixels per second
554
555    /// Dart's `static final _crossAxisHalfTime`, a sixtieth of a second rounded to the
556    /// microsecond.
557    fn cross_axis_half_time() -> Duration {
558        Duration::from_micros((1_000_000.0_f64 / 60.0).round() as u64)
559    }
560
561    fn new(
562        app: &mut App,
563        vsync: TickerProviderRef,
564        color: Color,
565        axis: Axis,
566    ) -> Ref<GlowController> {
567        let glow_controller = AnimationController::new(
568            app,
569            None,
570            None,
571            None,
572            0.0,
573            1.0,
574            AnimationBehavior::Normal,
575            vsync.clone(),
576        );
577        let glow_opacity_tween = Tween::new(app, Some(0.0), Some(0.0));
578        let glow_size_tween = Tween::new(app, Some(0.0), Some(0.0));
579        let this = app.create(GlowController {
580            change_notifier: ChangeNotifierData::new(),
581            state: GlowState::Idle,
582            glow_controller: glow_controller.clone(),
583            pull_recede_timer: None,
584            paint_offset: 0.0,
585            paint_offset_scroll_pixels: 0.0,
586            decelerator: None,
587            glow_opacity_tween: glow_opacity_tween.clone(),
588            glow_opacity: None,
589            glow_size_tween: glow_size_tween.clone(),
590            glow_size: None,
591            displacement_ticker: None,
592            displacement_ticker_last_elapsed: None,
593            displacement_target: 0.5,
594            displacement: 0.5,
595            pull_distance: 0.0,
596            color,
597            axis,
598        });
599        let handle = this.handle();
600        glow_controller.view().add_status_listener(
601            app,
602            AnimationStatusListener::handle_method(handle, GlowController::change_phase),
603        );
604        let decelerator =
605            CurvedAnimation::new(app, glow_controller.erase(), Curves::decelerate(), None);
606        decelerator.add_listener(
607            app,
608            Listener::handle_method(handle, Handle::<GlowController>::notify_listeners),
609        );
610        let glow_opacity = decelerator.drive(app, glow_opacity_tween);
611        let glow_size = decelerator.drive(app, glow_size_tween);
612        let displacement_ticker = vsync.create_ticker(
613            app,
614            FrameCallback::handle_method(handle, GlowController::tick_displacement),
615        );
616        let controller = app.get_mut(&this);
617        controller.decelerator = Some(decelerator);
618        controller.glow_opacity = Some(glow_opacity);
619        controller.glow_size = Some(glow_size);
620        controller.displacement_ticker = Some(displacement_ticker);
621        this
622    }
623
624    fn decelerator(self: Handle<Self>, app: &App) -> Handle<CurvedAnimation> {
625        app.get(self)
626            .decelerator
627            .handle()
628            .expect("set by the constructor")
629    }
630
631    fn glow_opacity(self: Handle<Self>, app: &App) -> AnyAnimation<f64> {
632        app.get(self)
633            .glow_opacity
634            .handle()
635            .expect("set by the constructor")
636    }
637
638    fn glow_size(self: Handle<Self>, app: &App) -> AnyAnimation<f64> {
639        app.get(self)
640            .glow_size
641            .handle()
642            .expect("set by the constructor")
643    }
644
645    fn displacement_ticker(self: Handle<Self>, app: &App) -> Handle<Ticker> {
646        app.get(self)
647            .displacement_ticker
648            .handle()
649            .expect("set by the constructor")
650    }
651
652    fn color(self: Handle<Self>, app: &App) -> Color {
653        app.get(self).color
654    }
655
656    fn set_color(self: Handle<Self>, app: &mut App, value: Color) {
657        if self.color(app) == value {
658            return;
659        }
660        app.get_mut(self).color = value;
661        self.notify_listeners(app);
662    }
663
664    fn axis(self: Handle<Self>, app: &App) -> Axis {
665        app.get(self).axis
666    }
667
668    fn set_axis(self: Handle<Self>, app: &mut App, value: Axis) {
669        if self.axis(app) == value {
670            return;
671        }
672        app.get_mut(self).axis = value;
673        self.notify_listeners(app);
674    }
675
676    fn cancel_pull_recede_timer(self: Handle<Self>, app: &mut App) {
677        if let Some(timer) = app.get(self).pull_recede_timer {
678            timer.cancel(app);
679        }
680    }
681
682    fn dispose(self: Handle<Self>, app: &mut App) {
683        app.get(self).glow_controller.dispose(app);
684        self.decelerator(app).dispose(app);
685        self.displacement_ticker(app).dispose(app);
686        self.cancel_pull_recede_timer(app);
687        ChangeNotifierData::dispose(app, self);
688    }
689
690    /// Handle a scroll slamming into the edge at a particular velocity.
691    ///
692    /// The velocity must be positive.
693    fn absorb_impact(self: Handle<Self>, app: &mut App, velocity: f64) {
694        debug_assert!(velocity >= 0.0);
695        self.cancel_pull_recede_timer(app);
696        app.get_mut(self).pull_recede_timer = None;
697        let velocity = clamp_double(velocity, Self::MIN_VELOCITY, Self::MAX_VELOCITY);
698        let glow_opacity_begin = if app.get(self).state == GlowState::Idle {
699            0.3
700        } else {
701            self.glow_opacity(app).value(app)
702        };
703        let glow_opacity_tween = app.get(self).glow_opacity_tween.handle();
704        glow_opacity_tween.set_begin(app, Some(glow_opacity_begin));
705        glow_opacity_tween.set_end(
706            app,
707            Some(clamp_double(
708                velocity * Self::VELOCITY_GLOW_FACTOR,
709                glow_opacity_begin,
710                Self::MAX_OPACITY,
711            )),
712        );
713        let glow_size_tween = app.get(self).glow_size_tween.handle();
714        let glow_size = self.glow_size(app).value(app);
715        glow_size_tween.set_begin(app, Some(glow_size));
716        glow_size_tween.set_end(
717            app,
718            Some(f64::min(0.025 + 7.5e-7 * velocity * velocity, 1.0)),
719        );
720        let glow_controller = app.get(self).glow_controller.handle();
721        app.get_mut(glow_controller).duration = Some(Duration::from_millis(
722            (0.15 + velocity * 0.02).round() as u64,
723        ));
724        glow_controller.forward(app, Some(0.0));
725        let controller = app.get_mut(self);
726        controller.displacement = 0.5;
727        controller.state = GlowState::Absorb;
728    }
729
730    /// Handle a user-driven overscroll.
731    ///
732    /// The `overscroll` argument should be the scroll distance in logical pixels,
733    /// the `extent` argument should be the total dimension of the viewport in the
734    /// main axis in logical pixels, the `cross_axis_offset` argument should be the
735    /// distance from the leading (left or top) edge of the cross axis of the
736    /// viewport, and the `cross_extent` should be the size of the cross axis. For
737    /// example, a pull of 50 pixels up the middle of a 200 pixel high and 100
738    /// pixel wide vertical viewport should result in a call of `pull(50.0, 200.0,
739    /// 50.0, 100.0)`. The `overscroll` value should be positive regardless of the
740    /// direction.
741    fn pull(
742        self: Handle<Self>,
743        app: &mut App,
744        overscroll: f64,
745        extent: f64,
746        cross_axis_offset: f64,
747        cross_extent: f64,
748    ) {
749        self.cancel_pull_recede_timer(app);
750        // This factor is magic. Not clear why we need it to match Android.
751        app.get_mut(self).pull_distance += overscroll / 200.0;
752        // Dart reads each animation's value again once its tween's `begin` is set, and the
753        // second read sees the new `begin`.
754        let glow_opacity_tween = app.get(self).glow_opacity_tween.handle();
755        let glow_opacity = self.glow_opacity(app).value(app);
756        glow_opacity_tween.set_begin(app, Some(glow_opacity));
757        let glow_opacity = self.glow_opacity(app).value(app);
758        glow_opacity_tween.set_end(
759            app,
760            Some(f64::min(
761                glow_opacity + overscroll / extent * Self::PULL_OPACITY_GLOW_FACTOR,
762                Self::MAX_OPACITY,
763            )),
764        );
765        let height = f64::min(extent, cross_extent * Self::WIDTH_TO_HEIGHT_FACTOR);
766        let glow_size_tween = app.get(self).glow_size_tween.handle();
767        let glow_size = self.glow_size(app).value(app);
768        glow_size_tween.set_begin(app, Some(glow_size));
769        let pull_distance = app.get(self).pull_distance;
770        let glow_size = self.glow_size(app).value(app);
771        glow_size_tween.set_end(
772            app,
773            Some(f64::max(
774                1.0 - 1.0 / (0.7 * (pull_distance * height).sqrt()),
775                glow_size,
776            )),
777        );
778        app.get_mut(self).displacement_target = cross_axis_offset / cross_extent;
779        let displacement_ticker = self.displacement_ticker(app);
780        let controller = app.get(self);
781        if controller.displacement_target != controller.displacement {
782            if !displacement_ticker.is_ticking(app) {
783                debug_assert!(app.get(self).displacement_ticker_last_elapsed.is_none());
784                displacement_ticker.start(app);
785            }
786        } else {
787            displacement_ticker.stop(app, false);
788            app.get_mut(self).displacement_ticker_last_elapsed = None;
789        }
790        let glow_controller = app.get(self).glow_controller.handle();
791        app.get_mut(glow_controller).duration = Some(Self::PULL_TIME);
792        if app.get(self).state != GlowState::Pull {
793            glow_controller.forward(app, Some(0.0));
794            app.get_mut(self).state = GlowState::Pull;
795        } else if !glow_controller.is_animating(app) {
796            debug_assert!(glow_controller.value(app) == 1.0);
797            self.notify_listeners(app);
798        }
799        let timer = Timer::new(
800            app,
801            Self::PULL_HOLD_TIME,
802            Listener::new(move |app: &mut App| self.recede(app, Self::PULL_DECAY_TIME)),
803        );
804        app.get_mut(self).pull_recede_timer = Some(timer);
805    }
806
807    fn scroll_end(self: Handle<Self>, app: &mut App) {
808        if app.get(self).state == GlowState::Pull {
809            self.recede(app, Self::RECEDE_TIME);
810        }
811    }
812
813    fn change_phase(self: Handle<Self>, app: &mut App, status: AnimationStatus) {
814        if !status.is_completed() {
815            return;
816        }
817        match app.get(self).state {
818            GlowState::Absorb => self.recede(app, Self::RECEDE_TIME),
819            GlowState::Recede => {
820                let controller = app.get_mut(self);
821                controller.state = GlowState::Idle;
822                controller.pull_distance = 0.0;
823            }
824            GlowState::Pull | GlowState::Idle => {}
825        }
826    }
827
828    fn recede(self: Handle<Self>, app: &mut App, duration: Duration) {
829        let state = app.get(self).state;
830        if state == GlowState::Recede || state == GlowState::Idle {
831            return;
832        }
833        self.cancel_pull_recede_timer(app);
834        app.get_mut(self).pull_recede_timer = None;
835        let glow_opacity = self.glow_opacity(app).value(app);
836        let glow_opacity_tween = app.get(self).glow_opacity_tween.handle();
837        glow_opacity_tween.set_begin(app, Some(glow_opacity));
838        glow_opacity_tween.set_end(app, Some(0.0));
839        let glow_size = self.glow_size(app).value(app);
840        let glow_size_tween = app.get(self).glow_size_tween.handle();
841        glow_size_tween.set_begin(app, Some(glow_size));
842        glow_size_tween.set_end(app, Some(0.0));
843        let glow_controller = app.get(self).glow_controller.handle();
844        app.get_mut(glow_controller).duration = Some(duration);
845        glow_controller.forward(app, Some(0.0));
846        app.get_mut(self).state = GlowState::Recede;
847    }
848
849    fn tick_displacement(self: Handle<Self>, app: &mut App, elapsed: Duration) {
850        if let Some(last_elapsed) = app.get(self).displacement_ticker_last_elapsed {
851            let t = (elapsed.as_micros() as i64 - last_elapsed.as_micros() as i64) as f64;
852            let controller = app.get_mut(self);
853            controller.displacement = controller.displacement_target
854                - (controller.displacement_target - controller.displacement)
855                    * 2.0_f64.powf(-t / Self::cross_axis_half_time().as_micros() as f64);
856            self.notify_listeners(app);
857        }
858        let controller = app.get(self);
859        if near_equal(
860            Some(controller.displacement_target),
861            Some(controller.displacement),
862            Tolerance::DEFAULT_TOLERANCE.distance,
863        ) {
864            self.displacement_ticker(app).stop(app, false);
865            app.get_mut(self).displacement_ticker_last_elapsed = None;
866        } else {
867            app.get_mut(self).displacement_ticker_last_elapsed = Some(elapsed);
868        }
869    }
870
871    fn paint(self: Handle<Self>, app: &App, canvas: &mut Canvas, size: Size) {
872        let glow_opacity = self.glow_opacity(app).value(app);
873        if glow_opacity == 0.0 {
874            return;
875        }
876        let controller = app.get(self);
877        let base_glow_scale = if size.width() > size.height() {
878            size.height() / size.width()
879        } else {
880            1.0
881        };
882        let radius = size.width() * 3.0 / 2.0;
883        let height = f64::min(size.height(), size.width() * Self::WIDTH_TO_HEIGHT_FACTOR);
884        let scale_y = self.glow_size(app).value(app) * base_glow_scale;
885        let rect = Rect::from_ltwh(0.0, 0.0, size.width(), height);
886        let center = Offset::new(
887            (size.width() / 2.0) * (0.5 + controller.displacement),
888            height - radius,
889        );
890        #[allow(deprecated)]
891        let paint = Paint::from_color(controller.color.with_opacity(glow_opacity).into());
892        canvas.save();
893        canvas.translate(
894            0.0,
895            (controller.paint_offset + controller.paint_offset_scroll_pixels) as f32,
896        );
897        canvas.scale(1.0, scale_y as f32);
898        canvas.clip_rect(rect, ClipOp::Intersect, true);
899        canvas.draw_circle(center, radius as f32, &paint);
900        canvas.restore();
901    }
902}
903
904impl ChangeNotifier for GlowController {
905    fn change_notifier_data(&self) -> &ChangeNotifierData {
906        &self.change_notifier
907    }
908
909    fn change_notifier_data_mut(&mut self) -> &mut ChangeNotifierData {
910        &mut self.change_notifier
911    }
912}
913
914impl Debug for GlowController {
915    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
916        write!(
917            f,
918            "_GlowController(color: {:?}, axis: {:?})",
919            self.color, self.axis
920        )
921    }
922}
923
924/// Dart's `_GlowingOverscrollIndicatorPainter`.
925struct GlowingOverscrollIndicatorPainter {
926    /// The controller for the overscroll glow on the side with negative scroll offsets.
927    ///
928    /// For a vertical downwards viewport, this is the top side.
929    leading_controller: Option<Ref<GlowController>>,
930
931    /// The controller for the overscroll glow on the side with positive scroll offsets.
932    ///
933    /// For a vertical downwards viewport, this is the bottom side.
934    trailing_controller: Option<Ref<GlowController>>,
935
936    /// The direction of the viewport.
937    axis_direction: AxisDirection,
938
939    /// Dart's `super.repaint`.
940    repaint: Option<Rc<dyn Listenable>>,
941}
942
943impl GlowingOverscrollIndicatorPainter {
944    const PI_OVER_2: f64 = std::f64::consts::PI / 2.0;
945
946    fn paint_side(
947        &self,
948        app: &App,
949        canvas: &mut Canvas,
950        size: Size,
951        controller: Option<Handle<GlowController>>,
952        axis_direction: AxisDirection,
953        growth_direction: GrowthDirection,
954    ) {
955        let Some(controller) = controller else {
956            return;
957        };
958        match apply_growth_direction_to_axis_direction(axis_direction, growth_direction) {
959            AxisDirection::Up => controller.paint(app, canvas, size),
960            AxisDirection::Down => {
961                canvas.save();
962                canvas.translate(0.0, size.height() as f32);
963                canvas.scale(1.0, -1.0);
964                controller.paint(app, canvas, size);
965                canvas.restore();
966            }
967            AxisDirection::Left => {
968                canvas.save();
969                canvas.rotate(Self::PI_OVER_2 as f32);
970                canvas.scale(1.0, -1.0);
971                controller.paint(app, canvas, Size::new(size.height(), size.width()));
972                canvas.restore();
973            }
974            AxisDirection::Right => {
975                canvas.save();
976                canvas.translate(size.width() as f32, 0.0);
977                canvas.rotate(Self::PI_OVER_2 as f32);
978                controller.paint(app, canvas, Size::new(size.height(), size.width()));
979                canvas.restore();
980            }
981        }
982    }
983}
984
985impl CustomPainter for GlowingOverscrollIndicatorPainter {
986    fn repaint(&self) -> Option<&Rc<dyn Listenable>> {
987        self.repaint.as_ref()
988    }
989
990    fn paint(&self, app: &mut App, canvas: &mut Canvas, size: Size) {
991        self.paint_side(
992            app,
993            canvas,
994            size,
995            self.leading_controller.handle(),
996            self.axis_direction,
997            GrowthDirection::Reverse,
998        );
999        self.paint_side(
1000            app,
1001            canvas,
1002            size,
1003            self.trailing_controller.handle(),
1004            self.axis_direction,
1005            GrowthDirection::Forward,
1006        );
1007    }
1008
1009    fn should_repaint(&self, _app: &App, old_delegate: &dyn CustomPainter) -> bool {
1010        let old_delegate = old_delegate
1011            .as_any()
1012            .downcast_ref::<GlowingOverscrollIndicatorPainter>()
1013            .expect("Dart's covariant parameter");
1014        old_delegate.leading_controller != self.leading_controller
1015            || old_delegate.trailing_controller != self.trailing_controller
1016    }
1017
1018    fn as_any(&self) -> &dyn std::any::Any {
1019        self
1020    }
1021}
1022
1023impl Debug for GlowingOverscrollIndicatorPainter {
1024    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1025        write!(
1026            f,
1027            "_GlowingOverscrollIndicatorPainter({:?}, {:?})",
1028            self.leading_controller, self.trailing_controller
1029        )
1030    }
1031}
1032
1033/// A Material Design visual indication that a scroll view has overscrolled.
1034///
1035/// A [`StretchingOverscrollIndicator`] listens for [`ScrollNotification`]s in order
1036/// to stretch the content of the `Scrollable`. These notifications are typically
1037/// generated by a `ScrollView`, such as a `ListView` or a `GridView`.
1038///
1039/// When triggered, the [`StretchingOverscrollIndicator`] generates an
1040/// [`OverscrollIndicatorNotification`] before showing an overscroll indication.
1041/// To prevent the indicator from showing the indication, call
1042/// [`OverscrollIndicatorNotification::disallow_indicator`] on the notification.
1043///
1044/// Created by `MaterialScrollBehavior::build_overscroll_indicator` on platforms
1045/// (e.g., Android) that commonly use this type of overscroll indication when
1046/// `ThemeData::use_material3` is true. Otherwise, when `ThemeData::use_material3`
1047/// is false, a [`GlowingOverscrollIndicator`] is used instead.
1048///
1049/// See also:
1050///
1051///  * [`OverscrollIndicatorNotification`], which can be used to prevent the
1052///    stretch effect from being applied at all.
1053///  * [`NotificationListener`], to listen for the
1054///    [`OverscrollIndicatorNotification`].
1055///  * [`GlowingOverscrollIndicator`], the default overscroll indicator for
1056///    `TargetPlatform::Android` and `TargetPlatform::Fuchsia`.
1057pub struct StretchingOverscrollIndicator {
1058    pub key: Option<KeyRef>,
1059
1060    /// The direction of positive scroll offsets in the `Scrollable` whose
1061    /// overscrolls are to be visualized.
1062    pub axis_direction: AxisDirection,
1063
1064    /// A check that specifies whether a [`ScrollNotification`] should be
1065    /// handled by this widget.
1066    ///
1067    /// By default, checks whether `notification.depth() == 0`. Set it to something
1068    /// else for more complicated layouts, such as nested `ScrollView`s.
1069    pub notification_predicate: ScrollNotificationPredicate,
1070
1071    /// The content will be clipped (or not) according to this option.
1072    ///
1073    /// Defaults to [`Clip::HardEdge`].
1074    pub clip_behavior: Clip,
1075
1076    /// The widget below this widget in the tree.
1077    ///
1078    /// The overscroll indicator will apply a stretch effect to this child. This
1079    /// child (and its subtree) should include a source of [`ScrollNotification`]
1080    /// notifications.
1081    pub child: Option<WidgetRef>,
1082}
1083
1084impl StretchingOverscrollIndicator {
1085    /// Creates a visual indication that a scroll view has overscrolled by
1086    /// applying a stretch transformation to the content.
1087    ///
1088    /// In order for this widget to display an overscroll indication, the [`child`](Self::child)
1089    /// widget must contain a widget that generates a [`ScrollNotification`], such
1090    /// as a `ListView` or a `GridView`.
1091    pub fn new(axis_direction: AxisDirection) -> StretchingOverscrollIndicator {
1092        StretchingOverscrollIndicator {
1093            key: None,
1094            axis_direction,
1095            notification_predicate: Rc::new(default_scroll_notification_predicate),
1096            clip_behavior: Clip::HardEdge,
1097            child: None,
1098        }
1099    }
1100
1101    /// Dart `StretchingOverscrollIndicator(key:)`.
1102    pub fn key(mut self, key: KeyRef) -> StretchingOverscrollIndicator {
1103        self.key = Some(key);
1104        self
1105    }
1106
1107    /// Dart `StretchingOverscrollIndicator(notificationPredicate:)`.
1108    pub fn notification_predicate(
1109        mut self,
1110        notification_predicate: ScrollNotificationPredicate,
1111    ) -> StretchingOverscrollIndicator {
1112        self.notification_predicate = notification_predicate;
1113        self
1114    }
1115
1116    /// Dart `StretchingOverscrollIndicator(clipBehavior:)`.
1117    pub fn clip_behavior(mut self, clip_behavior: Clip) -> StretchingOverscrollIndicator {
1118        self.clip_behavior = clip_behavior;
1119        self
1120    }
1121
1122    /// Dart `StretchingOverscrollIndicator(child:)`.
1123    #[cfg_attr(debug_assertions, track_caller)]
1124    pub fn child<K>(mut self, child: impl IntoWidget<K>) -> StretchingOverscrollIndicator {
1125        self.child = Some(child.into_widget());
1126        self
1127    }
1128
1129    /// The axis along which scrolling occurs in the `Scrollable` whose
1130    /// overscrolls are to be visualized.
1131    pub fn axis(&self) -> Axis {
1132        axis_direction_to_axis(self.axis_direction)
1133    }
1134}
1135
1136impl Debug for StretchingOverscrollIndicator {
1137    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1138        f.debug_struct("StretchingOverscrollIndicator")
1139            .field("axisDirection", &self.axis_direction)
1140            .finish_non_exhaustive()
1141    }
1142}
1143
1144impl StatefulWidget for StretchingOverscrollIndicator {
1145    type State = StretchingOverscrollIndicatorState;
1146
1147    fn key(&self) -> Option<&KeyRef> {
1148        self.key.as_ref()
1149    }
1150
1151    fn debug_fill_properties(&self, _app: &App, properties: &mut DiagnosticPropertiesBuilder) {
1152        properties.add(EnumProperty::new("axisDirection", self.axis_direction));
1153    }
1154
1155    fn create_state(&self) -> StretchingOverscrollIndicatorState {
1156        StretchingOverscrollIndicatorState {
1157            state: StateData::new(),
1158            ticker_provider: TickerProviderStateMixinData::new(),
1159            stretch_controller: None,
1160            last_overscroll_notification_metrics: None,
1161            total_overscroll: 0.0,
1162            accepted: true,
1163        }
1164    }
1165}
1166
1167/// Dart's `_StretchingOverscrollIndicatorState`.
1168pub struct StretchingOverscrollIndicatorState {
1169    state: StateData<StretchingOverscrollIndicator>,
1170    ticker_provider: TickerProviderStateMixinData,
1171    /// Dart's `late final _stretchController`, made on first use, with the `Listenable` the
1172    /// builder listens to, made once so a rebuild hands the builder the same one.
1173    stretch_controller: Option<(Ref<StretchController>, Rc<dyn Listenable>)>,
1174    /// The metrics of Dart's `_lastOverscrollNotification`, the one member of it `build`
1175    /// reads.
1176    last_overscroll_notification_metrics:
1177        Option<Rc<dyn crate::widgets::scroll_metrics::ScrollMetrics>>,
1178    total_overscroll: f64,
1179    accepted: bool,
1180}
1181
1182impl StretchingOverscrollIndicatorState {
1183    fn stretch_controller(self: Handle<Self>, app: &mut App) -> Handle<StretchController> {
1184        self.stretch_listenable_controller(app).0
1185    }
1186
1187    fn stretch_listenable_controller(
1188        self: Handle<Self>,
1189        app: &mut App,
1190    ) -> (Handle<StretchController>, Rc<dyn Listenable>) {
1191        if let Some((controller, listenable)) = &app.get(self).stretch_controller {
1192            return (controller.handle(), Rc::clone(listenable));
1193        }
1194        let controller = StretchController::new(app, TickerProviderRef::new(self));
1195        let handle = controller.handle();
1196        let listenable: Rc<dyn Listenable> = Rc::new(controller.clone());
1197        app.get_mut(self).stretch_controller = Some((controller, Rc::clone(&listenable)));
1198        (handle, listenable)
1199    }
1200
1201    fn handle_scroll_notification(
1202        self: Handle<Self>,
1203        app: &mut App,
1204        notification: &dyn ScrollNotification,
1205    ) -> bool {
1206        let widget = self.widget(app);
1207        let notification_predicate = Rc::clone(&widget.notification_predicate);
1208        let axis = widget.axis();
1209        if !notification_predicate(notification) {
1210            return false;
1211        }
1212        if notification.metrics().axis() != axis {
1213            // This widget is explicitly configured to one axis. If a notification
1214            // from a different axis bubbles up, do nothing.
1215            return false;
1216        }
1217        let any = notification.as_any();
1218        if any.is::<ScrollStartNotification>() {
1219            let state = app.get_mut(self);
1220            state.accepted = true;
1221            state.total_overscroll = 0.0;
1222        } else if let Some(notification) = any.downcast_ref::<OverscrollNotification>() {
1223            app.get_mut(self).last_overscroll_notification_metrics =
1224                Some(Rc::clone(notification.metrics()));
1225            // Dart's `_lastNotification.runtimeType is! OverscrollNotification` (see the
1226            // module doc).
1227            let confirmation_notification =
1228                OverscrollIndicatorNotification::new(notification.overscroll < 0.0);
1229            confirmation_notification.dispatch(app, Some(self.context(app)));
1230            app.get_mut(self).accepted = confirmation_notification.accepted.get();
1231
1232            if app.get(self).accepted {
1233                app.get_mut(self).total_overscroll += notification.overscroll;
1234
1235                if notification.velocity != 0.0 {
1236                    debug_assert!(notification.drag_details.is_none());
1237                    self.stretch_controller(app)
1238                        .absorb_impact(app, notification.velocity);
1239                } else {
1240                    debug_assert!(notification.overscroll != 0.0);
1241                    if notification.drag_details.is_some() {
1242                        // We clamp the overscroll amount relative to the length of the viewport,
1243                        // which is the furthest distance a single pointer could pull on the
1244                        // screen. This is because more than one pointer will multiply the
1245                        // amount of overscroll - https://github.com/flutter/flutter/issues/11884
1246
1247                        let viewport_dimension = notification.metrics().viewport_dimension();
1248                        let distance_for_pull = app.get(self).total_overscroll / viewport_dimension;
1249                        let clamped_overscroll = clamp_double(distance_for_pull, -1.0, 1.0);
1250                        self.stretch_controller(app).pull(app, clamped_overscroll);
1251                    }
1252                }
1253            }
1254        } else if let Some(notification) = any.downcast_ref::<ScrollEndNotification>() {
1255            let mut velocity = match axis {
1256                Axis::Vertical => notification
1257                    .drag_details
1258                    .as_ref()
1259                    .map_or(0.0, |details| details.velocity.pixels_per_second.dy()),
1260                Axis::Horizontal => notification
1261                    .drag_details
1262                    .as_ref()
1263                    .map_or(0.0, |details| details.velocity.pixels_per_second.dx()),
1264            };
1265
1266            // Reverse axis directions report dragDetails velocity in
1267            // the opposite screen coordinate, so the value must be inverted.
1268            if matches!(
1269                notification.metrics().axis_direction(),
1270                AxisDirection::Left | AxisDirection::Up
1271            ) {
1272                velocity = -velocity;
1273            }
1274
1275            // Since the overscrolling ended, we reset the total overscroll amount.
1276            app.get_mut(self).total_overscroll = 0.0;
1277            if app.get(self).accepted {
1278                self.stretch_controller(app).scroll_end(app, velocity);
1279            }
1280        } else if any.is::<ScrollUpdateNotification>() {
1281            app.get_mut(self).total_overscroll = 0.0;
1282            self.stretch_controller(app).scroll_end(app, 0.0);
1283        }
1284        false
1285    }
1286
1287    /// The body of the `AnimatedBuilder` Dart's `build` returns.
1288    fn build_stretch(self: Handle<Self>, app: &mut App, context: BuildContext) -> WidgetRef {
1289        let stretch = self.stretch_controller(app).overscroll(app);
1290        let widget = self.widget(app);
1291        let (axis, axis_direction, clip_behavior) =
1292            (widget.axis(), widget.axis_direction, widget.clip_behavior);
1293        let child = widget
1294            .child
1295            .clone()
1296            .unwrap_or_else(|| SizedBox::shrink().into_widget());
1297
1298        let main_axis_size = match axis {
1299            Axis::Horizontal => MediaQuery::width_of(app, context),
1300            Axis::Vertical => MediaQuery::height_of(app, context),
1301        };
1302
1303        let viewport_dimension = app
1304            .get(self)
1305            .last_overscroll_notification_metrics
1306            .as_ref()
1307            .map_or(main_axis_size, |metrics| metrics.viewport_dimension());
1308
1309        let mut overscroll = -stretch;
1310
1311        // Adjust overscroll for reverse scroll directions.
1312        if axis_direction == AxisDirection::Up || axis_direction == AxisDirection::Left {
1313            overscroll = -overscroll;
1314        }
1315
1316        let transform = StretchEffect::new(axis, child).stretch_strength(overscroll);
1317
1318        // Only clip if the viewport dimension is smaller than that of the
1319        // screen size in the main axis. If the viewport takes up the whole
1320        // screen, overflow from transforming the viewport is irrelevant.
1321        ClipRect::new()
1322            .clip_behavior(if stretch != 0.0 && viewport_dimension != main_axis_size {
1323                clip_behavior
1324            } else {
1325                Clip::None
1326            })
1327            .child(transform)
1328            .into_widget()
1329    }
1330}
1331
1332impl Debug for StretchingOverscrollIndicatorState {
1333    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1334        f.debug_struct("StretchingOverscrollIndicatorState")
1335            .finish_non_exhaustive()
1336    }
1337}
1338
1339impl TickerProviderStateMixin for StretchingOverscrollIndicatorState {
1340    fn ticker_provider_data(self: Handle<Self>, app: &App) -> &TickerProviderStateMixinData {
1341        &app.get(self).ticker_provider
1342    }
1343
1344    fn ticker_provider_data_mut(
1345        self: Handle<Self>,
1346        app: &mut App,
1347    ) -> &mut TickerProviderStateMixinData {
1348        &mut app.get_mut(self).ticker_provider
1349    }
1350}
1351
1352impl TickerProviderObject for StretchingOverscrollIndicatorState {
1353    fn create_ticker(self: Handle<Self>, app: &mut App, on_tick: TickerCallback) -> Ref<Ticker> {
1354        TickerProviderStateMixin::create_ticker(self, app, on_tick)
1355    }
1356}
1357
1358impl State for StretchingOverscrollIndicatorState {
1359    type Widget = StretchingOverscrollIndicator;
1360    crate::state_accessors!();
1361
1362    fn activate(self: Handle<Self>, app: &mut App) {
1363        TickerProviderStateMixin::activate(self, app);
1364    }
1365
1366    fn dispose(self: Handle<Self>, app: &mut App) {
1367        self.stretch_controller(app).dispose(app);
1368        TickerProviderStateMixin::dispose(self, app);
1369    }
1370
1371    fn build(self: Handle<Self>, app: &mut App, _context: BuildContext) -> WidgetRef {
1372        let (_, stretch_listenable) = self.stretch_listenable_controller(app);
1373        NotificationListener::<dyn ScrollNotification>::new(
1374            AnimatedBuilder::new(
1375                stretch_listenable,
1376                move |app: &mut App, context: BuildContext, _child: Option<&WidgetRef>| {
1377                    self.build_stretch(app, context)
1378                },
1379            )
1380            .into_widget(),
1381        )
1382        .on_notification(
1383            move |app: &mut App, notification: &dyn ScrollNotification| {
1384                self.handle_scroll_notification(app, notification)
1385            },
1386        )
1387        .into_widget()
1388    }
1389}
1390
1391/// Dart's `_StretchController`, a `Listenable` that forwards its listeners to the notifier
1392/// of its [`overscroll`](Self::overscroll).
1393struct StretchController {
1394    vsync: TickerProviderRef,
1395    controller: Option<Ref<AnimationController>>,
1396
1397    /// Manages and notifies changes to the current [`overscroll`](Self::overscroll) value.
1398    overscroll_notifier: Ref<ValueNotifier<f64>>,
1399
1400    /// Stores the `overscroll` value from an ongoing animation at the precise
1401    /// moment it is interrupted by a new `pull()` gesture.
1402    ///
1403    /// When `pull()` is called while an animation (triggered by `absorb_impact`
1404    /// or `scroll_end`) is active, this field captures the animation's current
1405    /// `controller.value` (which represents the overscroll amount) immediately
1406    /// before the animation controller is disposed.
1407    ///
1408    /// This captured value is then added to the overscroll amount calculated
1409    /// by the `pull()` method. The primary purpose is to create a smoother
1410    /// visual transition from an animated overscroll state to a direct,
1411    /// user-driven pull, minimizing any abrupt visual "jumps" in the
1412    /// stretch effect.
1413    ///
1414    /// It is reset to `0.0` when an animation completes naturally via `animate()`
1415    /// or when a new pull starts without a preceding active animation.
1416    interrupted_overscroll: f64,
1417}
1418
1419impl StretchController {
1420    // Constants from Android.
1421    const EXPONENTIAL_SCALAR: f64 = std::f64::consts::E / 0.33;
1422    const STRETCH_INTENSITY: f64 = 0.016;
1423
1424    const MIN_OVERSCROLL: f64 = -1.0;
1425    const MAX_OVERSCROLL: f64 = 1.0;
1426
1427    /// A fraction used to adjust the input velocity, measured in pixels,
1428    /// to a value between -1 and 1 when gesture fling.
1429    const FLING_VELOCITY_FRICTION: f64 = 1.0 / 6000.0;
1430
1431    /// A fraction used to scale the absorbed impact velocity,
1432    /// converting raw velocity into a normalized value for simulation.
1433    const ABSORB_IMPACT_VELOCITY_FRICTION: f64 = 1.0 / 3000.0;
1434
1435    /// The maximum velocity allowed for a fling after scaling
1436    /// to prevent applying an excessive stretch effect.
1437    const MAX_FLING_VELOCITY: f64 = 0.5;
1438
1439    /// The maximum velocity allowed when absorbing an impact,
1440    /// ensuring the stretch effect does not exceed a reasonable limit.
1441    const MAX_ABSORB_IMPACT_VELOCITY: f64 = 1.25;
1442
1443    // Physical constants ported directly from Android's EdgeEffect.java.
1444    //
1445    // Android's EdgeEffect.java:
1446    // https://cs.android.com/android/platform/superproject/main/+/main:frameworks/base/core/java/android/widget/EdgeEffect.java
1447    const K_NATURAL_FREQUENCY: f64 = 24.657;
1448    const K_DAMPING_RATIO: f64 = 0.98;
1449
1450    /// A correction factor applied to the simulation time.
1451    ///
1452    /// The physical constants `K_NATURAL_FREQUENCY` and `K_DAMPING_RATIO` were ported
1453    /// directly from Android's `EdgeEffect.java` source. However, using these
1454    /// constants as-is resulted in an animation that was noticeably faster than
1455    /// the native Android behavior. The underlying reason for this discrepancy is
1456    /// unknown.
1457    ///
1458    /// This factor, determined by visual comparison ("eyeballing") to match the
1459    /// platform's timing, is applied to the elapsed time `t` to slow down the
1460    /// simulation.
1461    ///
1462    /// Based on the damped harmonic oscillator equations, an alternative,
1463    /// mathematically equivalent, approach would be to multiply both the
1464    /// `K_NATURAL_FREQUENCY` and the initial velocity by this same factor,
1465    /// rather than scaling the time input.
1466    const K_TIME_CORRECTION_FACTOR: f64 = 0.8;
1467
1468    /// Stiffness coefficient for the spring, derived from the natural frequency.
1469    ///
1470    /// Calculated as `K_STIFFNESS = K_NATURAL_FREQUENCY^2`, this is the baseline
1471    /// spring constant used in the damped harmonic oscillator model.
1472    const K_STIFFNESS: f64 = Self::K_NATURAL_FREQUENCY * Self::K_NATURAL_FREQUENCY;
1473
1474    /// Spring description representing the stretch behavior of the edge effect.
1475    ///
1476    /// This [`SpringDescription`] is used to simulate the overscroll stretch.
1477    /// The spring has a mass of 1, a stiffness adjusted by the
1478    /// [`K_TIME_CORRECTION_FACTOR`](Self::K_TIME_CORRECTION_FACTOR) squared to match
1479    /// platform timing, and a damping ratio corresponding to Android's native `EdgeEffect`.
1480    fn stretch_spring_description() -> SpringDescription {
1481        SpringDescription::with_damping_ratio_value(
1482            1.0,
1483            Self::K_STIFFNESS * Self::K_TIME_CORRECTION_FACTOR * Self::K_TIME_CORRECTION_FACTOR,
1484            Self::K_DAMPING_RATIO,
1485        )
1486    }
1487
1488    fn new(app: &mut App, vsync: TickerProviderRef) -> Ref<StretchController> {
1489        let overscroll_notifier = app.create(ValueNotifier::new(0.0));
1490        app.create(StretchController {
1491            vsync,
1492            controller: None,
1493            overscroll_notifier,
1494            interrupted_overscroll: 0.0,
1495        })
1496    }
1497
1498    fn overscroll(self: Handle<Self>, app: &App) -> f64 {
1499        *app.get(&app.get(self).overscroll_notifier).value()
1500    }
1501
1502    fn set_overscroll(self: Handle<Self>, app: &mut App, new_value: f64) {
1503        let notifier = app.get(self).overscroll_notifier.handle();
1504        notifier.set_value(
1505            app,
1506            clamp_double(new_value, Self::MIN_OVERSCROLL, Self::MAX_OVERSCROLL),
1507        );
1508    }
1509
1510    /// Creates a stretching-only [`Simulation`] ported from Android 12.
1511    fn create_stretch_simulation(self: Handle<Self>, app: &App, velocity: f64) -> SpringSimulation {
1512        SpringSimulation::new(
1513            Self::stretch_spring_description(),
1514            self.overscroll(app),
1515            0.0,
1516            velocity * Self::K_TIME_CORRECTION_FACTOR,
1517        )
1518    }
1519
1520    /// Handle a fling to the edge of the viewport at a particular velocity.
1521    ///
1522    /// The velocity must be positive.
1523    fn absorb_impact(self: Handle<Self>, app: &mut App, velocity: f64) {
1524        if velocity == 0.0 {
1525            return;
1526        }
1527        let scaled_velocity = clamp_double(
1528            velocity * Self::ABSORB_IMPACT_VELOCITY_FRICTION,
1529            -Self::MAX_ABSORB_IMPACT_VELOCITY,
1530            Self::MAX_ABSORB_IMPACT_VELOCITY,
1531        );
1532
1533        let simulation = self.create_stretch_simulation(app, scaled_velocity);
1534        self.animate(app, Box::new(simulation));
1535    }
1536
1537    /// Called when the overscroll ends to trigger a fling animation if needed.
1538    fn scroll_end(self: Handle<Self>, app: &mut App, velocity: f64) {
1539        if velocity == 0.0 && self.overscroll(app) == 0.0 {
1540            return;
1541        }
1542        let scaled_velocity = clamp_double(
1543            -(velocity * Self::FLING_VELOCITY_FRICTION),
1544            -Self::MAX_FLING_VELOCITY,
1545            Self::MAX_FLING_VELOCITY,
1546        );
1547
1548        if app.get(self).controller.is_none() {
1549            let simulation = self.create_stretch_simulation(app, scaled_velocity);
1550            self.animate(app, Box::new(simulation));
1551        }
1552    }
1553
1554    /// Starts a new animation using the given `simulation`.
1555    ///
1556    /// Disposes any existing animation controller before starting a new one.
1557    /// Updates the [`overscroll`](Self::overscroll) value on each animation frame.
1558    /// Automatically disposes the controller when the animation completes.
1559    fn animate(self: Handle<Self>, app: &mut App, simulation: Box<dyn Simulation>) {
1560        let vsync = app.get(self).vsync.clone();
1561        let controller = AnimationController::unbounded(
1562            app,
1563            0.0,
1564            None,
1565            None,
1566            AnimationBehavior::Preserve,
1567            vsync,
1568        );
1569        controller.view().add_listener(
1570            app,
1571            Listener::new(move |app: &mut App| {
1572                let new_overscroll = app
1573                    .get(self)
1574                    .controller
1575                    .handle()
1576                    .map_or(0.0, |controller| controller.value(app));
1577                self.set_overscroll(app, new_overscroll);
1578            }),
1579        );
1580        // The completion is the controller's own: it names the controller without keeping it.
1581        let handle = controller.handle();
1582        controller.animate_with(app, simulation).when_complete(
1583            app,
1584            Listener::new(move |app: &mut App| {
1585                let controller = handle;
1586                // Only clean up if this controller is still the active one. A later
1587                // pull(), animate(), or dispose() may have already replaced and disposed
1588                // it, in which case that path owns the cleanup and this stale completion
1589                // callback must not touch the shared state (or double dispose the
1590                // controller).
1591                if app.get(self).controller.handle() == Some(controller) {
1592                    self.set_overscroll(app, 0.0);
1593                    app.get_mut(self).interrupted_overscroll = 0.0;
1594                    controller.dispose(app);
1595                    app.get_mut(self).controller = None;
1596                }
1597            }),
1598        );
1599
1600        if let Some(old_controller) = app.get(self).controller.handle() {
1601            old_controller.dispose(app);
1602        }
1603        app.get_mut(self).controller = Some(controller);
1604    }
1605
1606    /// Handle a user-driven overscroll.
1607    ///
1608    /// The `normalized_overscroll` argument should be the scroll distance in
1609    /// logical pixels, divided by the extent of the viewport in the main axis.
1610    fn pull(self: Handle<Self>, app: &mut App, normalized_overscroll: f64) {
1611        if let Some(controller) = app.get(self).controller.handle() {
1612            app.get_mut(self).interrupted_overscroll = controller.value(app);
1613            controller.dispose(app);
1614            app.get_mut(self).controller = None;
1615        }
1616
1617        let pull_distance = normalized_overscroll;
1618        let abs_distance = pull_distance.abs();
1619        let linear_intensity = Self::STRETCH_INTENSITY * abs_distance;
1620        let exponential_intensity =
1621            Self::STRETCH_INTENSITY * (1.0 - (-abs_distance * Self::EXPONENTIAL_SCALAR).exp());
1622
1623        // Maintain sign of overscroll for direction; Dart's `double.sign` is zero for zero,
1624        // where `f64::signum` is one.
1625        let direction_sign = if pull_distance > 0.0 {
1626            1.0
1627        } else if pull_distance < 0.0 {
1628            -1.0
1629        } else {
1630            pull_distance
1631        };
1632        let new_overscroll = direction_sign * (linear_intensity + exponential_intensity);
1633        let interrupted_overscroll = app.get(self).interrupted_overscroll;
1634        self.set_overscroll(app, new_overscroll + interrupted_overscroll);
1635    }
1636
1637    fn dispose(self: Handle<Self>, app: &mut App) {
1638        if let Some(controller) = app.get_mut(self).controller.take() {
1639            controller.dispose(app);
1640        }
1641        let notifier = app.get(self).overscroll_notifier.handle();
1642        notifier.dispose(app);
1643    }
1644}
1645
1646impl ListenableObject for StretchController {
1647    fn add_listener(self: Handle<Self>, app: &mut App, listener: Listener) {
1648        let notifier = app.get(self).overscroll_notifier.handle();
1649        notifier.add_listener(app, listener);
1650    }
1651
1652    fn remove_listener(self: Handle<Self>, app: &mut App, listener: &Listener) {
1653        let notifier = app.get(self).overscroll_notifier.handle();
1654        notifier.remove_listener(app, listener);
1655    }
1656}
1657
1658impl Debug for StretchController {
1659    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1660        f.write_str("_StretchController()")
1661    }
1662}
1663
1664/// A notification that either a [`GlowingOverscrollIndicator`] or a
1665/// [`StretchingOverscrollIndicator`] will start showing an overscroll indication.
1666///
1667/// To prevent the indicator from showing the indication, call
1668/// [`disallow_indicator`](Self::disallow_indicator) on the notification.
1669///
1670/// A listener writes [`paint_offset`](Self::paint_offset) and
1671/// [`accepted`](Self::accepted) through a shared reference, as the notification bubbles as
1672/// `&dyn Notification`; the indicator reads them back once the dispatch returns.
1673///
1674/// See also:
1675///
1676///  * [`GlowingOverscrollIndicator`], which generates this type of notification
1677///    by painting an indicator over the child content.
1678///  * [`StretchingOverscrollIndicator`], which generates this type of
1679///    notification by applying a stretch transformation to the child content.
1680pub struct OverscrollIndicatorNotification {
1681    viewport_notification: ViewportNotificationData,
1682
1683    /// Whether the indication will be shown on the leading edge of the scroll
1684    /// view.
1685    pub leading: bool,
1686
1687    /// Controls at which offset a [`GlowingOverscrollIndicator`] draws.
1688    ///
1689    /// A positive offset will move the glow away from its edge,
1690    /// i.e. for a vertical, [`leading`](Self::leading) indicator, a
1691    /// [`paint_offset`](Self::paint_offset) of 100.0 will draw the indicator 100.0 pixels
1692    /// from the top of the edge. For a vertical indicator with [`leading`](Self::leading)
1693    /// set to `false`, a [`paint_offset`](Self::paint_offset) of 100.0 will draw the indicator
1694    /// 100.0 pixels from the bottom instead.
1695    ///
1696    /// A negative [`paint_offset`](Self::paint_offset) is generally not useful, since the
1697    /// glow will be clipped.
1698    ///
1699    /// This has no effect on a [`StretchingOverscrollIndicator`].
1700    pub paint_offset: Cell<f64>,
1701
1702    /// Whether the current overscroll event will allow for the indicator to be
1703    /// shown.
1704    ///
1705    /// Calling [`disallow_indicator`](Self::disallow_indicator) sets this to false,
1706    /// preventing the over scroll indicator from showing.
1707    ///
1708    /// Defaults to true.
1709    pub accepted: Cell<bool>,
1710}
1711
1712impl OverscrollIndicatorNotification {
1713    /// Creates a notification that an [`GlowingOverscrollIndicator`] or a
1714    /// [`StretchingOverscrollIndicator`] will start showing an overscroll indication.
1715    pub fn new(leading: bool) -> OverscrollIndicatorNotification {
1716        OverscrollIndicatorNotification {
1717            viewport_notification: ViewportNotificationData::new(),
1718            leading,
1719            paint_offset: Cell::new(0.0),
1720            accepted: Cell::new(true),
1721        }
1722    }
1723
1724    /// Call this method if the overscroll indicator should be prevented.
1725    pub fn disallow_indicator(&self) {
1726        self.accepted.set(false);
1727    }
1728}
1729
1730impl Notification for OverscrollIndicatorNotification {
1731    fn as_any(&self) -> &dyn std::any::Any {
1732        self
1733    }
1734
1735    fn viewport_depth(&self) -> Option<&Cell<u32>> {
1736        Some(self.viewport_notification.depth_cell())
1737    }
1738}
1739
1740impl ViewportNotificationMixin for OverscrollIndicatorNotification {
1741    fn viewport_notification_data(&self) -> &ViewportNotificationData {
1742        &self.viewport_notification
1743    }
1744}
1745
1746impl Debug for OverscrollIndicatorNotification {
1747    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1748        let mut description = Vec::new();
1749        ViewportNotificationMixin::debug_fill_description(self, &mut description);
1750        description.push(format!(
1751            "side: {}",
1752            if self.leading {
1753                "leading edge"
1754            } else {
1755                "trailing edge"
1756            }
1757        ));
1758        write!(
1759            f,
1760            "OverscrollIndicatorNotification({})",
1761            description.join(", ")
1762        )
1763    }
1764}
1765
1766#[cfg(test)]
1767mod tests {
1768    use waft_foundation::OptionRetained;
1769
1770    use waft_embedder::TextDirection;
1771    use waft_embedder::valo::Op;
1772    use waft_foundation::UniqueKey;
1773    use waft_gestures::{DragEndDetails, DragStartDetails, DragUpdateDetails, Velocity};
1774    use waft_painting::EdgeInsetsGeometry;
1775    use waft_physics::Simulation;
1776    use waft_rendering::{
1777        RenderBox, RenderClipRect, RenderCustomClip, RenderCustomPaint, RenderHandle,
1778    };
1779
1780    use super::*;
1781    use crate::binding::WidgetsBinding;
1782    use crate::framework::GlobalKey;
1783    use crate::testing::{TestPointer, WidgetTester, test_widgets};
1784    use crate::testing::{assert_f32_equals, expect, find, finds_nothing, finds_one_widget};
1785    use crate::widgets::basic::{
1786        Center, Column, Directionality, Opacity, Padding, SliverToBoxAdapter,
1787    };
1788    use crate::widgets::container::Container;
1789    use crate::widgets::media_query::MediaQueryData;
1790    use crate::widgets::page_view::PageView;
1791    use crate::widgets::scroll_configuration::{
1792        ScrollBehavior, ScrollBehaviorRef, ScrollConfiguration,
1793    };
1794    use crate::widgets::scroll_controller::{ScrollController, ScrollControllerLeaf};
1795    use crate::widgets::scroll_metrics::ScrollMetrics;
1796    use crate::widgets::scroll_physics::{
1797        AlwaysScrollableScrollPhysics, ScrollPhysics, ScrollPhysicsBase, ScrollPhysicsRef,
1798    };
1799    use crate::widgets::scroll_simulation::ClampingScrollSimulation;
1800    use crate::widgets::scroll_view::{CustomScrollView, ListView};
1801    use crate::widgets::scrollable_helpers::ScrollableDetails;
1802    use crate::widgets::single_child_scroll_view::SingleChildScrollView;
1803    use crate::widgets::sliver::SliverList;
1804    use crate::widgets::text::Text;
1805    use waft_rendering::testing::{PaintCall, RecordedCall, assert_paints, paints};
1806
1807    // ---- what these tests read from a `WidgetTester` ----
1808
1809    /// `tester.getCenter(find.byType(CustomScrollView))` for a scroll view that fills the view.
1810    const VIEW_CENTER: Offset = Offset::new(
1811        WidgetTester::SIZE.width() / 2.0,
1812        WidgetTester::SIZE.height() / 2.0,
1813    );
1814
1815    /// The glow tests' `slowDrag`: ten moves by `offset`, 20ms apart, of the touch `pointer`.
1816    fn slow_drag(tester: &mut WidgetTester, start: Offset, offset: Offset, pointer: i64) {
1817        let mut gesture = TestPointer::touch(pointer);
1818        tester.down(&mut gesture, start);
1819        for _ in 0..10 {
1820            tester.move_by(&mut gesture, offset, true);
1821            tester.pump_by(Duration::from_millis(20));
1822        }
1823        tester.up(&gesture);
1824    }
1825
1826    /// `tester.layers.contains(isA<ImageFilterLayer>())`.
1827    fn has_image_filter_layer(tester: &WidgetTester) -> bool {
1828        let root = tester
1829            .update(|app| WidgetsBinding::instance(app).root_element(app))
1830            .expect("a mounted tree");
1831        let layers = tester.layer_list_of(root);
1832        let app = tester.cell.borrow();
1833        layers.into_iter().any(|layer| {
1834            app.handle::<waft_rendering::ImageFilterLayer>(layer.id())
1835                .is_some()
1836        })
1837    }
1838
1839    /// The mounted `StretchEffect`'s strength: `findStretchEffect(tester).stretchStrength`.
1840    fn stretch_strength(tester: &WidgetTester) -> f64 {
1841        tester.widget(
1842            find::by_type::<StretchEffect>(),
1843            |effect: &StretchEffect| effect.stretch_strength,
1844        )
1845    }
1846
1847    /// `tester.renderObject(find.byType(CustomPaint))`, first to last.
1848    fn custom_paints(tester: &WidgetTester) -> Vec<RenderHandle<RenderCustomPaint>> {
1849        tester.all::<RenderCustomPaint>()
1850    }
1851
1852    /// The one `RenderCustomPaint`: `tester.renderObject(find.byType(CustomPaint))`.
1853    fn custom_paint(tester: &WidgetTester) -> RenderHandle<RenderCustomPaint> {
1854        let paints = custom_paints(tester);
1855        assert_eq!(paints.len(), 1, "one CustomPaint");
1856        paints[0]
1857    }
1858
1859    /// The global rect the first `RenderClipRect` clips its child to: its own box, as the
1860    /// stretch's `ClipRect` has no clipper.
1861    fn first_clip_rect(tester: &WidgetTester) -> Rect {
1862        let clip = tester.first::<RenderClipRect>();
1863        tester.get_rect(clip.as_box())
1864    }
1865
1866    /// `tester.allRenderObjects.whereType<RenderClipRect>().first.clipBehavior`.
1867    fn first_clip_behavior(tester: &WidgetTester) -> Clip {
1868        let clip = tester.first::<RenderClipRect>();
1869        clip.clip_behavior(&tester.cell.borrow())
1870    }
1871
1872    /// The calls `custom_paint` makes for its foreground painter when it paints at offset
1873    /// zero, the recording Flutter's `paints` matcher walks; the child's own calls, which
1874    /// these patterns skip over, are left out.
1875    fn painted(tester: &WidgetTester, custom_paint: RenderHandle<RenderCustomPaint>) -> Vec<Op> {
1876        let mut app = tester.cell.borrow_mut();
1877        let painter = custom_paint
1878            .foreground_painter(&app)
1879            .expect("the indicator paints in the foreground");
1880        let size = custom_paint.size(&app);
1881        let mut canvas = Canvas::new();
1882        canvas.save();
1883        painter.paint(&mut app, &mut canvas, size);
1884        canvas.restore();
1885        canvas.build().ops().to_vec()
1886    }
1887
1888    /// `box.localToGlobal(Offset.zero)` for the box under `key`.
1889    fn origin_of(tester: &WidgetTester, key: &GlobalKey) -> Offset {
1890        let render_box = tester.render_object(key).as_box().expect("a render box");
1891        render_box.local_to_global(&tester.cell.borrow(), Offset::ZERO, None)
1892    }
1893
1894    /// The glow tests' `doesNotOverscroll`: `isNot(paints..circle())`.
1895    fn does_not_overscroll(ops: &[Op]) -> bool {
1896        paints(ops, &[circle()]).is_err()
1897    }
1898
1899    fn circle() -> PaintCall {
1900        PaintCall::circle(None)
1901    }
1902
1903    /// `..circle(x:, color:)`.
1904    fn circle_with(x: Option<f64>, color: Option<u32>) -> PaintCall {
1905        PaintCall::Circle {
1906            x,
1907            y: None,
1908            radius: None,
1909            color: color.map(Color::new),
1910            style: None,
1911        }
1912    }
1913
1914    // ---- the trees the tests build ----
1915
1916    fn ltr<K>(child: impl IntoWidget<K>) -> WidgetRef {
1917        Directionality::new(TextDirection::Ltr, child).into_widget()
1918    }
1919
1920    /// `CustomScrollView(slivers: [SliverToBoxAdapter(child: SizedBox(height: height))])`.
1921    fn sized_scroll_view(height: f64) -> CustomScrollView {
1922        CustomScrollView::new().slivers([SliverToBoxAdapter::new()
1923            .child(SizedBox::new().height(height))
1924            .into_widget()])
1925    }
1926
1927    fn always_scrollable() -> ScrollPhysicsRef {
1928        Rc::new(AlwaysScrollableScrollPhysics::new())
1929    }
1930
1931    /// `overscroll_indicator_test.dart`'s `TestScrollBehavior1` (`COLOR` green),
1932    /// `TestScrollBehavior2` (blue) and `TestScrollBehaviorNoGlow` (zero): a glow of `COLOR`,
1933    /// or none. Each is a type of its own, as Dart's three classes are, so swapping one for
1934    /// another rebuilds the scrollables under it.
1935    #[derive(Debug)]
1936    struct TestScrollBehavior<const COLOR: u32>;
1937
1938    impl<const COLOR: u32> ScrollBehavior for TestScrollBehavior<COLOR> {
1939        fn as_any(&self) -> &dyn std::any::Any {
1940            self
1941        }
1942
1943        fn build_overscroll_indicator(
1944            &self,
1945            _app: &mut App,
1946            _context: BuildContext,
1947            child: WidgetRef,
1948            details: &ScrollableDetails,
1949        ) -> WidgetRef {
1950            if COLOR == 0 {
1951                return child;
1952            }
1953            GlowingOverscrollIndicator::new(details.direction, Color::new(COLOR))
1954                .child(child)
1955                .into_widget()
1956        }
1957    }
1958
1959    fn behavior<const COLOR: u32>() -> ScrollBehaviorRef {
1960        ScrollBehaviorRef::new(TestScrollBehavior::<COLOR>)
1961    }
1962
1963    /// A listener that sets `paint_offset` on the confirmations `side` picks.
1964    fn paint_offset_listener(
1965        child: WidgetRef,
1966        side: impl Fn(bool) -> bool + 'static,
1967        paint_offset: f64,
1968    ) -> WidgetRef {
1969        NotificationListener::<OverscrollIndicatorNotification>::new(child)
1970            .on_notification(move |_app, notification| {
1971                if side(notification.leading) {
1972                    notification.paint_offset.set(paint_offset);
1973                }
1974                false
1975            })
1976            .into_widget()
1977    }
1978
1979    // ---- overscroll_indicator_test.dart ----
1980
1981    /// "Overscroll indicator color".
1982    #[test]
1983    fn the_default_glow_is_white_and_shows_only_for_a_slow_drag() {
1984        test_widgets(|tester| {
1985            tester.pump_widget(ltr(sized_scroll_view(2000.0)));
1986            let painter = custom_paint(tester);
1987
1988            assert!(does_not_overscroll(&painted(tester, painter)));
1989
1990            // the scroll gesture from tester.scroll happens in zero time, so nothing should appear:
1991            tester.drag_from(VIEW_CENTER, Offset::new(0.0, 100.0), 1);
1992            assert!(does_not_overscroll(&painted(tester, painter)));
1993            tester.pump(); // allow the ticker to register itself
1994            assert!(does_not_overscroll(&painted(tester, painter)));
1995            tester.pump_by(Duration::from_millis(100)); // animate
1996            assert!(does_not_overscroll(&painted(tester, painter)));
1997
1998            let mut gesture = TestPointer::touch(2);
1999            tester.down(&mut gesture, Offset::new(200.0, 200.0));
2000            tester.pump_by(Duration::from_millis(100)); // animate
2001            assert!(does_not_overscroll(&painted(tester, painter)));
2002            tester.up(&gesture);
2003            assert!(does_not_overscroll(&painted(tester, painter)));
2004
2005            slow_drag(tester, Offset::new(200.0, 200.0), Offset::new(0.0, 5.0), 3);
2006            assert_paints(
2007                &painted(tester, painter),
2008                &[circle_with(None, Some(0x0DFFFFFF))],
2009            );
2010
2011            tester.pump_and_settle_by(Duration::from_secs(1));
2012            assert!(does_not_overscroll(&painted(tester, painter)));
2013        });
2014    }
2015
2016    /// "Nested scrollable".
2017    #[test]
2018    fn a_predicate_lets_the_outer_indicator_glow_for_the_inner_scrollable() {
2019        test_widgets(|tester| {
2020            tester.pump_widget(ltr(GlowingOverscrollIndicator::new(
2021                AxisDirection::Down,
2022                Color::new(0x0DFFFFFF),
2023            )
2024            .notification_predicate(Rc::new(|notification| notification.depth() == 1))
2025            .child(
2026                SingleChildScrollView::new()
2027                    .scroll_direction(Axis::Horizontal)
2028                    .child(
2029                        SizedBox::new()
2030                            .width(600.0)
2031                            .child(sized_scroll_view(2000.0)),
2032                    ),
2033            )));
2034
2035            let paints_found = custom_paints(tester);
2036            let outer_painter = paints_found[0];
2037            let inner_painter = *paints_found.last().expect("two CustomPaints");
2038
2039            slow_drag(tester, Offset::new(200.0, 200.0), Offset::new(0.0, 5.0), 1);
2040            assert_paints(&painted(tester, outer_painter), &[circle()]);
2041            assert_paints(&painted(tester, inner_painter), &[circle()]);
2042        });
2043    }
2044
2045    /// "Overscroll indicator changes side when you drag on the other side".
2046    #[test]
2047    fn the_glow_centers_on_the_side_the_drag_is_on() {
2048        test_widgets(|tester| {
2049            tester.pump_widget(ltr(sized_scroll_view(2000.0)));
2050            let painter = custom_paint(tester);
2051
2052            slow_drag(tester, Offset::new(400.0, 200.0), Offset::new(0.0, 10.0), 1);
2053            assert_paints(&painted(tester, painter), &[circle_with(Some(400.0), None)]);
2054            slow_drag(tester, Offset::new(100.0, 200.0), Offset::new(0.0, 10.0), 2);
2055            assert_paints(
2056                &painted(tester, painter),
2057                &[PaintCall::something(|call| match call {
2058                    RecordedCall::Circle { center, .. } if center.dx() < 400.0 => Ok(true),
2059                    RecordedCall::Circle { .. } => Err(
2060                        "Dragging on left hand side did not overscroll on left hand side.".into(),
2061                    ),
2062                    _ => Ok(false),
2063                })],
2064            );
2065            slow_drag(tester, Offset::new(700.0, 200.0), Offset::new(0.0, 10.0), 3);
2066            assert_paints(
2067                &painted(tester, painter),
2068                &[PaintCall::something(|call| match call {
2069                    RecordedCall::Circle { center, .. } if center.dx() > 400.0 => Ok(true),
2070                    RecordedCall::Circle { .. } => Err(
2071                        "Dragging on right hand side did not overscroll on right hand side.".into(),
2072                    ),
2073                    _ => Ok(false),
2074                })],
2075            );
2076
2077            tester.pump_and_settle_by(Duration::from_secs(1));
2078            assert!(does_not_overscroll(&painted(tester, painter)));
2079        });
2080    }
2081
2082    /// "Overscroll indicator changes side when you shift sides".
2083    #[test]
2084    fn the_glow_follows_a_drag_that_slides_sideways() {
2085        test_widgets(|tester| {
2086            tester.pump_widget(ltr(sized_scroll_view(2000.0)));
2087            let painter = custom_paint(tester);
2088            let mut gesture = TestPointer::touch(1);
2089            tester.down(&mut gesture, Offset::new(300.0, 200.0));
2090            tester.move_by(&mut gesture, Offset::new(0.0, 10.0), true);
2091            tester.pump_by(Duration::from_millis(20));
2092            let old_x = Rc::new(std::cell::Cell::new(0.0));
2093            for _ in 0..10 {
2094                tester.move_by(&mut gesture, Offset::new(50.0, 50.0), true);
2095                tester.pump_by(Duration::from_millis(20));
2096                assert_paints(
2097                    &painted(tester, painter),
2098                    &[PaintCall::something({
2099                        let old_x = Rc::clone(&old_x);
2100                        move |call| match call {
2101                            RecordedCall::Circle { center, .. } => {
2102                                if center.dx() <= old_x.get() {
2103                                    return Err("Sliding to the right did not make the center of \
2104                                                the radius slide to the right."
2105                                        .into());
2106                                }
2107                                old_x.set(center.dx());
2108                                Ok(true)
2109                            }
2110                            _ => Ok(false),
2111                        }
2112                    })],
2113                );
2114            }
2115            tester.up(&gesture);
2116
2117            tester.pump_and_settle_by(Duration::from_secs(1));
2118            assert!(does_not_overscroll(&painted(tester, painter)));
2119        });
2120    }
2121
2122    /// "Flipping direction of scrollable doesn't change overscroll behavior": "down".
2123    #[test]
2124    fn a_downward_scroll_view_glows_at_the_top_when_pulled_down() {
2125        test_widgets(|tester| {
2126            tester.pump_widget(ltr(sized_scroll_view(20.0).physics(always_scrollable())));
2127            let painter = custom_paint(tester);
2128            slow_drag(tester, Offset::new(200.0, 200.0), Offset::new(0.0, 5.0), 1);
2129            assert_paints(
2130                &painted(tester, painter),
2131                &[
2132                    PaintCall::Save,
2133                    circle(),
2134                    PaintCall::Restore,
2135                    PaintCall::Save,
2136                    PaintCall::scale(None, Some(-1.0)),
2137                    PaintCall::Restore,
2138                    PaintCall::Restore,
2139                ],
2140            );
2141
2142            tester.pump_and_settle_by(Duration::from_secs(1));
2143            assert!(does_not_overscroll(&painted(tester, painter)));
2144        });
2145    }
2146
2147    /// "Flipping direction of scrollable doesn't change overscroll behavior": "up".
2148    #[test]
2149    fn a_reversed_scroll_view_glows_at_the_top_when_pulled_down() {
2150        test_widgets(|tester| {
2151            tester.pump_widget(ltr(sized_scroll_view(20.0)
2152                .reverse(true)
2153                .physics(always_scrollable())));
2154            let painter = custom_paint(tester);
2155            slow_drag(tester, Offset::new(200.0, 200.0), Offset::new(0.0, 5.0), 1);
2156            assert_paints(
2157                &painted(tester, painter),
2158                &[
2159                    PaintCall::Save,
2160                    PaintCall::scale(None, Some(-1.0)),
2161                    PaintCall::Restore,
2162                    PaintCall::Save,
2163                    circle(),
2164                    PaintCall::Restore,
2165                    PaintCall::Restore,
2166                ],
2167            );
2168
2169            tester.pump_and_settle_by(Duration::from_secs(1));
2170            assert!(does_not_overscroll(&painted(tester, painter)));
2171        });
2172    }
2173
2174    /// "Overscroll in both directions".
2175    #[test]
2176    fn pulling_one_way_then_the_other_glows_at_both_ends() {
2177        test_widgets(|tester| {
2178            tester.pump_widget(ltr(sized_scroll_view(20.0).physics(always_scrollable())));
2179            let painter = custom_paint(tester);
2180            slow_drag(tester, Offset::new(200.0, 200.0), Offset::new(0.0, 5.0), 1);
2181            assert_paints(&painted(tester, painter), &[circle()]);
2182            assert!(paints(&painted(tester, painter), &[circle(), circle()]).is_err());
2183            slow_drag(tester, Offset::new(200.0, 200.0), Offset::new(0.0, -5.0), 2);
2184            assert_paints(&painted(tester, painter), &[circle(), circle()]);
2185
2186            tester.pump_and_settle_by(Duration::from_secs(1));
2187            assert!(does_not_overscroll(&painted(tester, painter)));
2188        });
2189    }
2190
2191    /// "Overscroll ignored from alternate axis".
2192    #[test]
2193    fn an_indicator_ignores_overscrolls_along_the_other_axis() {
2194        test_widgets(|tester| {
2195            tester.pump_widget(ltr(ScrollConfiguration::new(
2196                behavior::<0>(),
2197                GlowingOverscrollIndicator::new(AxisDirection::Right, Color::new(0xFF0000FF))
2198                    .child(sized_scroll_view(20.0).physics(always_scrollable())),
2199            )));
2200            let painter = custom_paint(tester);
2201            slow_drag(tester, Offset::new(200.0, 200.0), Offset::new(0.0, 5.0), 1);
2202            assert!(does_not_overscroll(&painted(tester, painter)));
2203            slow_drag(tester, Offset::new(200.0, 200.0), Offset::new(0.0, -5.0), 2);
2204            assert!(does_not_overscroll(&painted(tester, painter)));
2205
2206            tester.pump_and_settle_by(Duration::from_secs(1));
2207            assert!(does_not_overscroll(&painted(tester, painter)));
2208        });
2209    }
2210
2211    /// "Overscroll horizontally".
2212    #[test]
2213    fn a_horizontal_glow_is_rotated_a_quarter_turn() {
2214        test_widgets(|tester| {
2215            tester.pump_widget(ltr(sized_scroll_view(20.0)
2216                .scroll_direction(Axis::Horizontal)
2217                .physics(always_scrollable())));
2218            let painter = custom_paint(tester);
2219            let quarter = std::f64::consts::PI / 2.0;
2220            slow_drag(tester, Offset::new(200.0, 200.0), Offset::new(5.0, 0.0), 1);
2221            assert_paints(
2222                &painted(tester, painter),
2223                &[
2224                    PaintCall::rotate(Some(quarter)),
2225                    circle(),
2226                    PaintCall::SaveRestore,
2227                ],
2228            );
2229            assert!(paints(&painted(tester, painter), &[circle(), circle()]).is_err());
2230            slow_drag(tester, Offset::new(200.0, 200.0), Offset::new(-5.0, 0.0), 2);
2231            assert_paints(
2232                &painted(tester, painter),
2233                &[
2234                    PaintCall::rotate(Some(quarter)),
2235                    circle(),
2236                    PaintCall::rotate(Some(quarter)),
2237                    circle(),
2238                ],
2239            );
2240
2241            tester.pump_and_settle_by(Duration::from_secs(1));
2242            assert!(does_not_overscroll(&painted(tester, painter)));
2243        });
2244    }
2245
2246    /// "Nested overscrolls do not throw exceptions".
2247    #[test]
2248    fn nested_overscrolls_do_not_throw_exceptions() {
2249        test_widgets(|tester| {
2250            tester.pump_widget(ltr(PageView::new().children([ListView::new()
2251                .children([Container::new()
2252                    .width(2000.0)
2253                    .height(2000.0)
2254                    .color(Color::new(0xFF00FF00))
2255                    .into_widget()])
2256                .into_widget()])));
2257
2258            tester.drag_from(Offset::new(100.0, 100.0), Offset::new(0.0, 2000.0), 1);
2259            tester.pump_and_settle();
2260        });
2261    }
2262
2263    /// "Changing settings".
2264    #[test]
2265    fn a_new_behavior_glows_in_its_own_color() {
2266        test_widgets(|tester| {
2267            let quarter = std::f64::consts::PI / 2.0;
2268            tester.pump_widget(ltr(ScrollConfiguration::new(
2269                behavior::<0xFF00FF00>(),
2270                sized_scroll_view(20.0)
2271                    .scroll_direction(Axis::Horizontal)
2272                    .physics(always_scrollable())
2273                    .reverse(true),
2274            )));
2275            let painter = custom_paint(tester);
2276            slow_drag(tester, Offset::new(200.0, 200.0), Offset::new(5.0, 0.0), 1);
2277            assert_paints(
2278                &painted(tester, painter),
2279                &[
2280                    PaintCall::rotate(Some(quarter)),
2281                    circle_with(None, Some(0x0A00FF00)),
2282                ],
2283            );
2284            assert!(paints(&painted(tester, painter), &[circle(), circle()]).is_err());
2285
2286            tester.pump_and_settle_by(Duration::from_secs(1));
2287            tester.pump_widget(ltr(ScrollConfiguration::new(
2288                behavior::<0xFF0000FF>(),
2289                sized_scroll_view(20.0)
2290                    .scroll_direction(Axis::Horizontal)
2291                    .physics(always_scrollable()),
2292            )));
2293            let painter = custom_paint(tester);
2294            slow_drag(tester, Offset::new(200.0, 200.0), Offset::new(5.0, 0.0), 2);
2295            assert_paints(
2296                &painted(tester, painter),
2297                &[
2298                    PaintCall::rotate(Some(quarter)),
2299                    circle_with(None, Some(0x0A0000FF)),
2300                    PaintCall::SaveRestore,
2301                ],
2302            );
2303            assert!(paints(&painted(tester, painter), &[circle(), circle()]).is_err());
2304        });
2305    }
2306
2307    /// A `CustomScrollView` centered on its second sliver of `Text`s: the first sliver's second
2308    /// item, `First sliver 1`, under `first_sliver_1`, which the tests' `find.text` reads.
2309    fn centered_scroll_view(first_sliver_1: &GlobalKey) -> WidgetRef {
2310        let center_key: KeyRef = UniqueKey::new().into();
2311        let first_sliver_1 = first_sliver_1.clone();
2312        CustomScrollView::new()
2313            .center(center_key.clone())
2314            .physics(always_scrollable())
2315            .slivers([
2316                SliverList::builder(move |_app, _context, index| {
2317                    let item = Text::new(format!("First sliver {index}"));
2318                    Some(if index == 1 {
2319                        item.key(first_sliver_1.clone().into()).into_widget()
2320                    } else {
2321                        item.into_widget()
2322                    })
2323                })
2324                .item_count(2)
2325                .into_widget(),
2326                SliverList::builder(|_app, _context, index| {
2327                    Some(Text::new(format!("Second sliver {index}")).into_widget())
2328                })
2329                .key(center_key)
2330                .item_count(5)
2331                .into_widget(),
2332            ])
2333            .into_widget()
2334    }
2335
2336    /// "CustomScrollView overscroll indicator works if there is sliver before center".
2337    #[test]
2338    fn a_glow_over_slivers_before_the_center_starts_at_the_edge() {
2339        test_widgets(|tester| {
2340            let first_sliver_1 = GlobalKey::new();
2341            tester.pump_widget(ltr(ScrollConfiguration::new(
2342                behavior::<0xFF0000FF>(),
2343                centered_scroll_view(&first_sliver_1),
2344            )));
2345
2346            expect(
2347                tester,
2348                &find::by_global_key(&first_sliver_1),
2349                finds_nothing(),
2350            );
2351
2352            slow_drag(
2353                tester,
2354                Offset::new(200.0, 200.0),
2355                Offset::new(0.0, 300.0),
2356                1,
2357            );
2358            expect(
2359                tester,
2360                &find::by_global_key(&first_sliver_1),
2361                finds_one_widget(),
2362            );
2363            let painter = custom_paint(tester);
2364            // The scroll offset and paint extend should cancel out each other.
2365            assert_paints(
2366                &painted(tester, painter),
2367                &[
2368                    PaintCall::Save,
2369                    PaintCall::translate(None, Some(0.0)),
2370                    PaintCall::scale(None, None),
2371                    circle(),
2372                ],
2373            );
2374        });
2375    }
2376
2377    /// "CustomScrollView overscroll indicator works well with [CustomScrollView.center] and
2378    /// [OverscrollIndicatorNotification.paintOffset]".
2379    #[test]
2380    fn a_glow_over_slivers_before_the_center_honors_the_paint_offset() {
2381        test_widgets(|tester| {
2382            let first_sliver_1 = GlobalKey::new();
2383            tester.pump_widget(ltr(ScrollConfiguration::new(
2384                behavior::<0xFF0000FF>(),
2385                paint_offset_listener(
2386                    centered_scroll_view(&first_sliver_1),
2387                    |leading| leading,
2388                    50.0,
2389                ),
2390            )));
2391
2392            expect(
2393                tester,
2394                &find::by_global_key(&first_sliver_1),
2395                finds_nothing(),
2396            );
2397
2398            // offset will be magnified ten times
2399            slow_drag(tester, Offset::new(200.0, 200.0), Offset::new(0.0, 5.0), 1);
2400            expect(
2401                tester,
2402                &find::by_global_key(&first_sliver_1),
2403                finds_one_widget(),
2404            );
2405            let painter = custom_paint(tester);
2406            // The OverscrollIndicator should respect the [OverscrollIndicatorNotification.paintOffset] setting.
2407            assert_paints(
2408                &painted(tester, painter),
2409                &[
2410                    PaintCall::Save,
2411                    PaintCall::translate(None, Some(50.0)),
2412                    PaintCall::scale(None, None),
2413                    circle(),
2414                ],
2415            );
2416        });
2417    }
2418
2419    fn translated_glow(y: f64) -> Vec<PaintCall> {
2420        vec![
2421            PaintCall::Save,
2422            PaintCall::translate(None, Some(y)),
2423            PaintCall::scale(None, None),
2424            circle(),
2425        ]
2426    }
2427
2428    fn flipped_translated_glow(y: f64) -> Vec<PaintCall> {
2429        vec![
2430            PaintCall::scale(None, Some(-1.0)),
2431            PaintCall::Save,
2432            PaintCall::translate(None, Some(y)),
2433            PaintCall::scale(None, None),
2434            circle(),
2435        ]
2436    }
2437
2438    /// "The OverscrollIndicator should not overflow the scrollable view edge".
2439    #[test]
2440    fn a_glow_moves_with_the_content_but_never_past_the_edge() {
2441        test_widgets(|tester| {
2442            tester.pump_widget(ltr(paint_offset_listener(
2443                sized_scroll_view(2000.0).into_widget(),
2444                // both the leading and trailing indicator have a 50.0 pixels offset.
2445                |_leading| true,
2446                50.0,
2447            )));
2448            let painter = custom_paint(tester);
2449            let start = Offset::new(200.0, 200.0);
2450            slow_drag(tester, start, Offset::new(0.0, 5.0), 1);
2451            assert_paints(&painted(tester, painter), &translated_glow(50.0));
2452            // Reverse scroll (30 pixels), and the offset < notification.paintOffset.
2453            tester.drag_from(start, Offset::new(0.0, -30.0), 2);
2454            tester.pump();
2455            // The OverscrollIndicator should move with the CustomScrollView.
2456            assert_paints(&painted(tester, painter), &translated_glow(50.0 - 30.0));
2457
2458            // Reverse scroll (30+20 pixels) and offset == notification.paintOffset.
2459            tester.drag_from(start, Offset::new(0.0, -20.0), 3);
2460            tester.pump();
2461            assert_paints(&painted(tester, painter), &translated_glow(50.0 - 50.0));
2462
2463            // Reverse scroll (30+20+10 pixels) and offset > notification.paintOffset.
2464            tester.drag_from(start, Offset::new(0.0, -10.0), 4);
2465            tester.pump();
2466            // The OverscrollIndicator should not overflow the CustomScrollView's edge.
2467            assert_paints(&painted(tester, painter), &translated_glow(50.0 - 50.0));
2468
2469            tester.pump_and_settle(); // Finish the leading indicator.
2470
2471            // trigger the trailing indicator
2472            slow_drag(tester, start, Offset::new(0.0, -200.0), 5);
2473            assert_paints(&painted(tester, painter), &flipped_translated_glow(50.0));
2474
2475            // Reverse scroll (30 pixels), and the offset < notification.paintOffset.
2476            tester.drag_from(start, Offset::new(0.0, 30.0), 6);
2477            tester.pump();
2478            // The OverscrollIndicator should move with the CustomScrollView.
2479            assert_paints(
2480                &painted(tester, painter),
2481                &flipped_translated_glow(50.0 - 30.0),
2482            );
2483
2484            // Reverse scroll (30+20 pixels) and offset == notification.paintOffset.
2485            tester.drag_from(start, Offset::new(0.0, 20.0), 7);
2486            tester.pump();
2487            assert_paints(
2488                &painted(tester, painter),
2489                &flipped_translated_glow(50.0 - 50.0),
2490            );
2491
2492            // Reverse scroll (30+20+10 pixels) and offset > notification.paintOffset.
2493            tester.drag_from(start, Offset::new(0.0, 10.0), 8);
2494            tester.pump();
2495            // The OverscrollIndicator should not overflow the CustomScrollView's edge.
2496            assert_paints(
2497                &painted(tester, painter),
2498                &flipped_translated_glow(50.0 - 50.0),
2499            );
2500        });
2501    }
2502
2503    /// "[OverscrollIndicatorNotification.paintOffset] test": "Leading".
2504    #[test]
2505    fn the_leading_glow_draws_at_the_paint_offset_a_listener_sets() {
2506        test_widgets(|tester| {
2507            tester.pump_widget(ltr(paint_offset_listener(
2508                sized_scroll_view(2000.0).into_widget(),
2509                |leading| leading,
2510                50.0,
2511            )));
2512            let painter = custom_paint(tester);
2513            slow_drag(tester, Offset::new(200.0, 200.0), Offset::new(0.0, 5.0), 1);
2514            // The OverscrollIndicator should respect the [OverscrollIndicatorNotification.paintOffset] setting.
2515            assert_paints(&painted(tester, painter), &translated_glow(50.0));
2516            // Reverse scroll direction.
2517            tester.drag_from(Offset::new(200.0, 200.0), Offset::new(0.0, -30.0), 2);
2518            tester.pump();
2519            // The OverscrollIndicator should move with the CustomScrollView.
2520            assert_paints(&painted(tester, painter), &translated_glow(50.0 - 30.0));
2521        });
2522    }
2523
2524    /// "[OverscrollIndicatorNotification.paintOffset] test": "Trailing".
2525    #[test]
2526    fn the_trailing_glow_draws_at_the_paint_offset_a_listener_sets() {
2527        test_widgets(|tester| {
2528            tester.pump_widget(ltr(paint_offset_listener(
2529                sized_scroll_view(2000.0).into_widget(),
2530                |leading| !leading,
2531                50.0,
2532            )));
2533            let painter = custom_paint(tester);
2534            tester.drag_from(Offset::new(200.0, 200.0), Offset::new(200.0, -10000.0), 1);
2535            tester.pump();
2536            slow_drag(tester, Offset::new(200.0, 200.0), Offset::new(0.0, -5.0), 2);
2537            // The OverscrollIndicator should respect the [OverscrollIndicatorNotification.paintOffset] setting.
2538            assert_paints(&painted(tester, painter), &flipped_translated_glow(50.0));
2539            // Reverse scroll direction.
2540            tester.drag_from(Offset::new(200.0, 200.0), Offset::new(0.0, 30.0), 3);
2541            tester.pump();
2542            // The OverscrollIndicator should move with the CustomScrollView.
2543            assert_paints(
2544                &painted(tester, painter),
2545                &flipped_translated_glow(50.0 - 30.0),
2546            );
2547        });
2548    }
2549
2550    /// "StretchingOverscrollIndicator does not crash when child is null".
2551    #[test]
2552    fn a_stretching_indicator_with_no_child_builds() {
2553        test_widgets(|tester| {
2554            tester.pump_widget(ltr(StretchingOverscrollIndicator::new(AxisDirection::Down)));
2555            expect(
2556                tester,
2557                &find::by_type::<StretchEffect>(),
2558                finds_one_widget(),
2559            );
2560        });
2561    }
2562
2563    fn list_of_items(count: i32, height: f64) -> WidgetRef {
2564        ListView::builder(move |_app, _context, _index| {
2565            Some(SizedBox::new().height(height).into_widget())
2566        })
2567        .item_count(count)
2568        .build()
2569        .physics(always_scrollable())
2570        .into_widget()
2571    }
2572
2573    /// "StretchingOverscrollIndicator does not crash when disposed mid stretch animation".
2574    #[test]
2575    fn a_stretching_indicator_disposed_mid_animation_leaves_nothing_running() {
2576        test_widgets(|tester| {
2577            tester.pump_widget(ltr(StretchingOverscrollIndicator::new(AxisDirection::Down)
2578                .child(list_of_items(20, 100.0))));
2579
2580            // Fling at the top edge to overscroll, which starts the stretch
2581            // animation via `StretchController::animate`.
2582            tester.fling_from(VIEW_CENTER, Offset::new(0.0, 300.0), 1000.0, 1);
2583            tester.pump(); // Start the fling.
2584            tester.pump_by(Duration::from_millis(100)); // Let the animation begin.
2585            assert_ne!(
2586                stretch_strength(tester),
2587                0.0,
2588                "the fling stretches the list"
2589            );
2590
2591            // Tear down the widget before the animation completes. This disposes the
2592            // stretch controller (and its AnimationController) while the animation's
2593            // completion callback is still pending.
2594            tester.pump_widget(SizedBox::new().into_widget());
2595            tester.pump_and_settle();
2596            expect(tester, &find::by_type::<StretchEffect>(), finds_nothing());
2597        });
2598    }
2599
2600    /// The `AnimationController` each stretch release animates with is freed once the next
2601    /// release or the animation's end replaces it, as Dart's collector frees it.
2602    #[test]
2603    fn a_stretch_controller_frees_each_release_animation_it_replaces() {
2604        test_widgets(|tester| {
2605            tester.pump_widget(ltr(StretchingOverscrollIndicator::new(AxisDirection::Down)
2606                .child(list_of_items(20, 100.0))));
2607            let release_controller = |tester: &WidgetTester| {
2608                let element = tester.element(find::by_type::<StretchingOverscrollIndicator>());
2609                let mut app = tester.cell.borrow_mut();
2610                let state = element
2611                    .state_handle::<StretchingOverscrollIndicatorState>(&app)
2612                    .expect("a mounted StretchingOverscrollIndicator");
2613                let stretch = state.stretch_controller(&mut app);
2614                app.get(stretch).controller.handle()
2615            };
2616
2617            tester.fling_from(VIEW_CENTER, Offset::new(0.0, 300.0), 1000.0, 1);
2618            tester.pump();
2619            tester.pump_by(Duration::from_millis(100));
2620            let first = release_controller(tester).expect("the fling animates the release");
2621
2622            // A second fling replaces the release animation before it ends.
2623            tester.fling_from(VIEW_CENTER, Offset::new(0.0, 300.0), 1000.0, 2);
2624            tester.pump();
2625            tester.pump_by(Duration::from_millis(100));
2626            let second = release_controller(tester).expect("the fling animates the release");
2627            assert_ne!(first, second);
2628            tester.cell.checkpoint();
2629            assert!(
2630                !tester.cell.borrow().contains(first),
2631                "the replaced release's"
2632            );
2633
2634            tester.pump_and_settle();
2635            assert!(release_controller(tester).is_none());
2636            tester.cell.checkpoint();
2637            assert!(
2638                !tester.cell.borrow().contains(second),
2639                "the finished release's"
2640            );
2641        });
2642    }
2643
2644    /// "GlowingOverscrollIndicator does not crash at zero area".
2645    #[test]
2646    fn a_glowing_indicator_lays_out_at_zero_area() {
2647        test_widgets(|tester| {
2648            let key = GlobalKey::new();
2649            tester.pump_widget(ltr(Center::new().child(
2650                SizedBox::shrink().child(
2651                    GlowingOverscrollIndicator::new(AxisDirection::Down, Color::new(0xFF112233))
2652                        .key(key.clone().into()),
2653                ),
2654            )));
2655            let app = tester.cell.borrow();
2656            let size = key
2657                .current_context(&app)
2658                .and_then(|context| context.find_render_object(&app))
2659                .and_then(|object| object.as_box())
2660                .expect("the indicator is laid out")
2661                .size(&app);
2662            assert_eq!(size, Size::ZERO);
2663        });
2664    }
2665
2666    /// "StretchingOverscrollIndicator does not crash at zero area".
2667    #[test]
2668    fn a_stretching_indicator_lays_out_at_zero_area() {
2669        test_widgets(|tester| {
2670            let key = GlobalKey::new();
2671            tester.pump_widget(ltr(Center::new().child(
2672                SizedBox::shrink().child(
2673                    StretchingOverscrollIndicator::new(AxisDirection::Down)
2674                        .key(key.clone().into())
2675                        .child(ListView::new()),
2676                ),
2677            )));
2678            let app = tester.cell.borrow();
2679            let size = key
2680                .current_context(&app)
2681                .and_then(|context| context.find_render_object(&app))
2682                .and_then(|object| object.as_box())
2683                .expect("the indicator is laid out")
2684                .size(&app);
2685            assert_eq!(size, Size::ZERO);
2686        });
2687    }
2688
2689    // ---- overscroll_stretch_indicator_test.dart ----
2690
2691    struct Boxes {
2692        box1: GlobalKey,
2693        box2: GlobalKey,
2694        box3: GlobalKey,
2695        controller: Ref<ScrollController>,
2696    }
2697
2698    impl Boxes {
2699        fn new(tester: &WidgetTester) -> Boxes {
2700            Boxes {
2701                box1: GlobalKey::new(),
2702                box2: GlobalKey::new(),
2703                box3: GlobalKey::new(),
2704                controller: ScrollController::default(&mut tester.cell.borrow_mut()),
2705            }
2706        }
2707
2708        fn origins(&self, tester: &WidgetTester) -> [Offset; 3] {
2709            [
2710                origin_of(tester, &self.box1),
2711                origin_of(tester, &self.box2),
2712                origin_of(tester, &self.box3),
2713            ]
2714        }
2715
2716        fn offset(&self, tester: &WidgetTester) -> f64 {
2717            self.controller
2718                .as_controller()
2719                .offset(&tester.cell.borrow())
2720        }
2721
2722        fn jump_to_max(&self, tester: &WidgetTester) {
2723            let mut app = tester.cell.borrow_mut();
2724            let controller = self.controller.as_controller();
2725            let max = controller.position(&app).max_scroll_extent(&app);
2726            controller.jump_to(&mut app, max);
2727        }
2728    }
2729
2730    /// The stretch tests' `buildTest` arguments past the keys and the controller.
2731    struct BuildTest {
2732        axis: Axis,
2733        reverse: bool,
2734        text_direction: TextDirection,
2735        box_height: f64,
2736        box_width: f64,
2737        physics: Option<ScrollPhysicsRef>,
2738    }
2739
2740    impl Default for BuildTest {
2741        fn default() -> BuildTest {
2742            BuildTest {
2743                axis: Axis::Vertical,
2744                reverse: false,
2745                text_direction: TextDirection::Ltr,
2746                box_height: 250.0,
2747                box_width: 300.0,
2748                physics: None,
2749            }
2750        }
2751    }
2752
2753    fn no_overscroll_behavior() -> ScrollBehaviorRef {
2754        ScrollBehaviorRef::new(ScrollBehaviorRef::plain().copy_with().overscroll(false))
2755    }
2756
2757    /// The stretch tests' `buildTest`.
2758    fn build_test(boxes: &Boxes, options: BuildTest) -> WidgetRef {
2759        let axis_direction = match options.axis {
2760            Axis::Horizontal => match options.text_direction {
2761                TextDirection::Rtl => {
2762                    if options.reverse {
2763                        AxisDirection::Right
2764                    } else {
2765                        AxisDirection::Left
2766                    }
2767                }
2768                TextDirection::Ltr => {
2769                    if options.reverse {
2770                        AxisDirection::Left
2771                    } else {
2772                        AxisDirection::Right
2773                    }
2774                }
2775            },
2776            Axis::Vertical => {
2777                if options.reverse {
2778                    AxisDirection::Up
2779                } else {
2780                    AxisDirection::Down
2781                }
2782            }
2783        };
2784        let tile = |color: u32, key: &GlobalKey| {
2785            SliverToBoxAdapter::new()
2786                .child(
2787                    Container::new()
2788                        .color(Color::new(color))
2789                        .key(key.clone().into())
2790                        .height(options.box_height)
2791                        .width(options.box_width),
2792                )
2793                .into_widget()
2794        };
2795        let mut scroll_view = CustomScrollView::new()
2796            .reverse(options.reverse)
2797            .scroll_direction(options.axis)
2798            .controller(boxes.controller.erase())
2799            .slivers([
2800                tile(0xD0FF0000, &boxes.box1),
2801                tile(0xFFFFFF00, &boxes.box2),
2802                tile(0xFF6200EA, &boxes.box3),
2803            ]);
2804        if let Some(physics) = options.physics {
2805            scroll_view = scroll_view.physics(physics);
2806        }
2807        Directionality::new(
2808            options.text_direction,
2809            MediaQuery::new(
2810                MediaQueryData::new().size(WidgetTester::SIZE),
2811                ScrollConfiguration::new(
2812                    no_overscroll_behavior(),
2813                    StretchingOverscrollIndicator::new(axis_direction).child(scroll_view),
2814                )
2815                .into_widget(),
2816            )
2817            .into_widget(),
2818        )
2819        .into_widget()
2820    }
2821
2822    fn assert_one_stretching_indicator(tester: &WidgetTester) {
2823        expect(
2824            tester,
2825            &find::by_type::<StretchingOverscrollIndicator>(),
2826            finds_one_widget(),
2827        );
2828        expect(
2829            tester,
2830            &find::by_type::<GlowingOverscrollIndicator>(),
2831            finds_nothing(),
2832        );
2833    }
2834
2835    /// "Stretch overscroll will do nothing when axes do not match".
2836    #[test]
2837    fn a_stretch_on_the_other_axis_does_nothing() {
2838        test_widgets(|tester| {
2839            let boxes = Boxes::new(tester);
2840            tester.pump_widget(ltr(MediaQuery::new(
2841                MediaQueryData::new().size(WidgetTester::SIZE),
2842                ScrollConfiguration::new(
2843                    no_overscroll_behavior(),
2844                    StretchingOverscrollIndicator::new(AxisDirection::Right).child(
2845                        CustomScrollView::new()
2846                            .controller(boxes.controller.erase())
2847                            .slivers([
2848                                SliverToBoxAdapter::new()
2849                                    .child(
2850                                        Container::new()
2851                                            .color(Color::new(0xD0FF0000))
2852                                            .key(boxes.box1.clone().into())
2853                                            .height(250.0),
2854                                    )
2855                                    .into_widget(),
2856                                SliverToBoxAdapter::new()
2857                                    .child(
2858                                        Container::new()
2859                                            .color(Color::new(0xFFFFFF00))
2860                                            .key(boxes.box2.clone().into())
2861                                            .height(250.0)
2862                                            .width(300.0),
2863                                    )
2864                                    .into_widget(),
2865                            ]),
2866                    ),
2867                )
2868                .into_widget(),
2869            )
2870            .into_widget()));
2871
2872            assert_one_stretching_indicator(tester);
2873            assert_eq!(boxes.offset(tester), 0.0);
2874            assert_eq!(origin_of(tester, &boxes.box1), Offset::ZERO);
2875            assert_eq!(origin_of(tester, &boxes.box2), Offset::new(0.0, 250.0));
2876
2877            let mut gesture = TestPointer::touch(1);
2878            tester.down(&mut gesture, VIEW_CENTER);
2879            // Overscroll the start, no stretching occurs.
2880            tester.move_by(&mut gesture, Offset::new(0.0, 200.0), true);
2881            tester.pump_and_settle();
2882            assert_eq!(origin_of(tester, &boxes.box1), Offset::ZERO);
2883            assert_eq!(origin_of(tester, &boxes.box2).dy(), 250.0);
2884
2885            tester.up(&gesture);
2886            tester.pump_and_settle();
2887
2888            // Overscroll released
2889            assert_eq!(origin_of(tester, &boxes.box1), Offset::ZERO);
2890            assert_eq!(origin_of(tester, &boxes.box2), Offset::new(0.0, 250.0));
2891        });
2892    }
2893
2894    /// "Stretch overscroll vertically".
2895    #[test]
2896    fn a_vertical_stretch_pulls_the_boxes_apart_at_either_end_and_releases() {
2897        test_widgets(|tester| {
2898            let boxes = Boxes::new(tester);
2899            tester.pump_widget(build_test(&boxes, BuildTest::default()));
2900
2901            assert_one_stretching_indicator(tester);
2902            assert_eq!(boxes.offset(tester), 0.0);
2903            assert_eq!(
2904                boxes.origins(tester),
2905                [
2906                    Offset::ZERO,
2907                    Offset::new(0.0, 250.0),
2908                    Offset::new(0.0, 500.0)
2909                ]
2910            );
2911
2912            let mut gesture = TestPointer::touch(1);
2913            tester.down(&mut gesture, VIEW_CENTER);
2914            // Overscroll the start
2915            tester.move_by(&mut gesture, Offset::new(0.0, 200.0), true);
2916            tester.pump_and_settle();
2917            let [box1, box2, box3] = boxes.origins(tester);
2918            assert_eq!(box1, Offset::ZERO);
2919            assert!(box2.dy() > 255.0, "{box2:?}");
2920            assert!(box3.dy() > 510.0, "{box3:?}");
2921
2922            tester.up(&gesture);
2923            tester.pump_and_settle();
2924
2925            // Stretch released back to the start
2926            assert_eq!(
2927                boxes.origins(tester),
2928                [
2929                    Offset::ZERO,
2930                    Offset::new(0.0, 250.0),
2931                    Offset::new(0.0, 500.0)
2932                ]
2933            );
2934
2935            // Jump to end of the list
2936            boxes.jump_to_max(tester);
2937            tester.pump_and_settle();
2938            assert_eq!(boxes.offset(tester), 150.0);
2939            let [box1, box2, box3] = boxes.origins(tester);
2940            assert_eq!(box1.dy(), -150.0);
2941            assert_eq!(box2.dy(), 100.0);
2942            assert_eq!(box3.dy(), 350.0);
2943
2944            let mut gesture = TestPointer::touch(2);
2945            tester.down(&mut gesture, VIEW_CENTER);
2946            // Overscroll the end
2947            tester.move_by(&mut gesture, Offset::new(0.0, -200.0), true);
2948            tester.pump_and_settle();
2949            let [box1, box2, box3] = boxes.origins(tester);
2950            assert!(box1.dy() < -165.0, "{box1:?}");
2951            assert!(box2.dy() < 90.0, "{box2:?}");
2952            assert!(box3.dy() < 350.0, "{box3:?}");
2953
2954            tester.up(&gesture);
2955            tester.pump_and_settle();
2956
2957            // Stretch released back
2958            let [box1, box2, box3] = boxes.origins(tester);
2959            assert_eq!(box1.dy(), -150.0);
2960            assert_eq!(box2.dy(), 100.0);
2961            assert_eq!(box3.dy(), 350.0);
2962        });
2963    }
2964
2965    /// "Stretch overscroll works in reverse - vertical".
2966    #[test]
2967    fn a_reversed_vertical_stretch_pulls_the_boxes_up() {
2968        test_widgets(|tester| {
2969            let boxes = Boxes::new(tester);
2970            tester.pump_widget(build_test(
2971                &boxes,
2972                BuildTest {
2973                    reverse: true,
2974                    ..BuildTest::default()
2975                },
2976            ));
2977
2978            assert_one_stretching_indicator(tester);
2979            assert_eq!(boxes.offset(tester), 0.0);
2980            assert_eq!(
2981                boxes.origins(tester),
2982                [
2983                    Offset::new(0.0, 350.0),
2984                    Offset::new(0.0, 100.0),
2985                    Offset::new(0.0, -150.0)
2986                ]
2987            );
2988
2989            let mut gesture = TestPointer::touch(1);
2990            tester.down(&mut gesture, VIEW_CENTER);
2991            // Overscroll
2992            tester.move_by(&mut gesture, Offset::new(0.0, -200.0), true);
2993            tester.pump_and_settle();
2994            let [box1, box2, box3] = boxes.origins(tester);
2995            assert!(box1.dy() < 350.0, "{box1:?}");
2996            assert!(box2.dy() < 100.0, "{box2:?}");
2997            assert!(box3.dy() < -150.0, "{box3:?}");
2998        });
2999    }
3000
3001    /// "Stretch overscroll works in reverse - horizontal".
3002    #[test]
3003    fn a_reversed_horizontal_stretch_pulls_the_boxes_left() {
3004        test_widgets(|tester| {
3005            let boxes = Boxes::new(tester);
3006            tester.pump_widget(build_test(
3007                &boxes,
3008                BuildTest {
3009                    axis: Axis::Horizontal,
3010                    reverse: true,
3011                    ..BuildTest::default()
3012                },
3013            ));
3014
3015            assert_one_stretching_indicator(tester);
3016            assert_eq!(boxes.offset(tester), 0.0);
3017            assert_eq!(
3018                boxes.origins(tester),
3019                [
3020                    Offset::new(500.0, 0.0),
3021                    Offset::new(200.0, 0.0),
3022                    Offset::new(-100.0, 0.0)
3023                ]
3024            );
3025
3026            let mut gesture = TestPointer::touch(1);
3027            tester.down(&mut gesture, VIEW_CENTER);
3028            // Overscroll
3029            tester.move_by(&mut gesture, Offset::new(-200.0, 0.0), true);
3030            tester.pump_and_settle();
3031            let [box1, box2, box3] = boxes.origins(tester);
3032            assert!(box1.dx() < 500.0, "{box1:?}");
3033            assert!(box2.dx() < 200.0, "{box2:?}");
3034            assert!(box3.dx() < -100.0, "{box3:?}");
3035        });
3036    }
3037
3038    /// The horizontal stretch at both ends that "Stretch overscroll horizontally" and
3039    /// "Stretch overscroll works in reverse - horizontal - RTL" share.
3040    fn horizontal_stretch_at_both_ends(tester: &mut WidgetTester, options: BuildTest) {
3041        let boxes = Boxes::new(tester);
3042        tester.pump_widget(build_test(&boxes, options));
3043
3044        assert_one_stretching_indicator(tester);
3045        assert_eq!(boxes.offset(tester), 0.0);
3046        assert_eq!(
3047            boxes.origins(tester),
3048            [
3049                Offset::ZERO,
3050                Offset::new(300.0, 0.0),
3051                Offset::new(600.0, 0.0)
3052            ]
3053        );
3054
3055        let mut gesture = TestPointer::touch(2);
3056        tester.down(&mut gesture, VIEW_CENTER);
3057        // Overscroll the start
3058        tester.move_by(&mut gesture, Offset::new(200.0, 0.0), true);
3059        tester.pump_and_settle();
3060        let [box1, box2, box3] = boxes.origins(tester);
3061        assert_eq!(box1, Offset::ZERO);
3062        assert!(box2.dx() > 305.0, "{box2:?}");
3063        assert!(box3.dx() > 610.0, "{box3:?}");
3064
3065        tester.up(&gesture);
3066        tester.pump_and_settle();
3067
3068        // Stretch released back to the start
3069        assert_eq!(
3070            boxes.origins(tester),
3071            [
3072                Offset::ZERO,
3073                Offset::new(300.0, 0.0),
3074                Offset::new(600.0, 0.0)
3075            ]
3076        );
3077
3078        // Jump to end of the list
3079        boxes.jump_to_max(tester);
3080        tester.pump_and_settle();
3081        assert_eq!(boxes.offset(tester), 100.0);
3082        let [box1, box2, box3] = boxes.origins(tester);
3083        assert_eq!(box1.dx(), -100.0);
3084        assert_eq!(box2.dx(), 200.0);
3085        assert_eq!(box3.dx(), 500.0);
3086
3087        let mut gesture = TestPointer::touch(3);
3088        tester.down(&mut gesture, VIEW_CENTER);
3089        // Overscroll the end
3090        tester.move_by(&mut gesture, Offset::new(-200.0, 0.0), true);
3091        tester.pump_and_settle();
3092        let [box1, box2, box3] = boxes.origins(tester);
3093        assert!(box1.dx() < -116.0, "{box1:?}");
3094        assert!(box2.dx() < 190.0, "{box2:?}");
3095        assert!(box3.dx() < 500.0, "{box3:?}");
3096
3097        tester.up(&gesture);
3098        tester.pump_and_settle();
3099
3100        // Stretch released back
3101        let [box1, box2, box3] = boxes.origins(tester);
3102        assert_eq!(box1.dx(), -100.0);
3103        assert_eq!(box2.dx(), 200.0);
3104        assert_eq!(box3.dx(), 500.0);
3105    }
3106
3107    /// "Stretch overscroll works in reverse - horizontal - RTL".
3108    #[test]
3109    fn a_reversed_right_to_left_stretch_pulls_the_boxes_apart_at_either_end() {
3110        test_widgets(|tester| {
3111            horizontal_stretch_at_both_ends(
3112                tester,
3113                BuildTest {
3114                    axis: Axis::Horizontal,
3115                    reverse: true,
3116                    text_direction: TextDirection::Rtl,
3117                    ..BuildTest::default()
3118                },
3119            )
3120        });
3121    }
3122
3123    /// "Stretch overscroll horizontally".
3124    #[test]
3125    fn a_horizontal_stretch_pulls_the_boxes_apart_at_either_end_and_releases() {
3126        test_widgets(|tester| {
3127            horizontal_stretch_at_both_ends(
3128                tester,
3129                BuildTest {
3130                    axis: Axis::Horizontal,
3131                    ..BuildTest::default()
3132                },
3133            )
3134        });
3135    }
3136
3137    /// "Stretch overscroll only uses image filter during stretch effect".
3138    #[test]
3139    fn a_stretch_filters_its_child_only_while_it_stretches() {
3140        test_widgets(|tester| {
3141            let boxes = Boxes::new(tester);
3142            tester.pump_widget(build_test(
3143                &boxes,
3144                BuildTest {
3145                    axis: Axis::Horizontal,
3146                    ..BuildTest::default()
3147                },
3148            ));
3149
3150            assert!(!has_image_filter_layer(tester));
3151
3152            let mut gesture = TestPointer::touch(1);
3153            tester.down(&mut gesture, VIEW_CENTER);
3154            // Overscroll
3155            tester.move_by(&mut gesture, Offset::new(200.0, 0.0), true);
3156            tester.pump_and_settle();
3157
3158            assert!(has_image_filter_layer(tester));
3159        });
3160    }
3161
3162    /// "Stretch overscroll horizontally RTL".
3163    #[test]
3164    fn a_right_to_left_stretch_pulls_the_boxes_left() {
3165        test_widgets(|tester| {
3166            let boxes = Boxes::new(tester);
3167            tester.pump_widget(build_test(
3168                &boxes,
3169                BuildTest {
3170                    axis: Axis::Horizontal,
3171                    text_direction: TextDirection::Rtl,
3172                    ..BuildTest::default()
3173                },
3174            ));
3175
3176            assert_one_stretching_indicator(tester);
3177            assert_eq!(boxes.offset(tester), 0.0);
3178            assert_eq!(
3179                boxes.origins(tester),
3180                [
3181                    Offset::new(500.0, 0.0),
3182                    Offset::new(200.0, 0.0),
3183                    Offset::new(-100.0, 0.0)
3184                ]
3185            );
3186
3187            let mut gesture = TestPointer::touch(1);
3188            tester.down(&mut gesture, VIEW_CENTER);
3189            // Overscroll
3190            tester.move_by(&mut gesture, Offset::new(-200.0, 0.0), true);
3191            tester.pump_and_settle();
3192            let [box1, box2, box3] = boxes.origins(tester);
3193            assert!(box1.dx() < 500.0, "{box1:?}");
3194            assert!(box2.dx() < 200.0, "{box2:?}");
3195            assert!(box3.dx() < -100.0, "{box3:?}");
3196        });
3197    }
3198
3199    /// A listener that counts the confirmations and disallows them while `disallow` is set.
3200    fn counting_listener(
3201        child: WidgetRef,
3202        count: &Rc<Cell<u32>>,
3203        disallow: &Rc<Cell<bool>>,
3204    ) -> WidgetRef {
3205        let count = Rc::clone(count);
3206        let disallow = Rc::clone(disallow);
3207        NotificationListener::<OverscrollIndicatorNotification>::new(child)
3208            .on_notification(move |_app, notification| {
3209                if disallow.get() {
3210                    notification.disallow_indicator();
3211                }
3212                count.set(count.get() + 1);
3213                false
3214            })
3215            .into_widget()
3216    }
3217
3218    /// "Disallow stretching overscroll".
3219    #[test]
3220    fn a_disallowed_stretch_leaves_the_boxes_in_place() {
3221        test_widgets(|tester| {
3222            let boxes = Boxes::new(tester);
3223            let indicator_notification = Rc::new(Cell::new(0));
3224            tester.pump_widget(counting_listener(
3225                build_test(&boxes, BuildTest::default()),
3226                &indicator_notification,
3227                &Rc::new(Cell::new(true)),
3228            ));
3229
3230            assert_one_stretching_indicator(tester);
3231            assert_eq!(indicator_notification.get(), 0);
3232            assert_eq!(boxes.offset(tester), 0.0);
3233            assert_eq!(
3234                boxes.origins(tester),
3235                [
3236                    Offset::ZERO,
3237                    Offset::new(0.0, 250.0),
3238                    Offset::new(0.0, 500.0)
3239                ]
3240            );
3241
3242            let mut gesture = TestPointer::touch(1);
3243            tester.down(&mut gesture, VIEW_CENTER);
3244            // Overscroll the start, should not stretch
3245            tester.move_by(&mut gesture, Offset::new(0.0, 200.0), true);
3246            tester.pump_and_settle();
3247            assert_eq!(indicator_notification.get(), 1);
3248            assert_eq!(
3249                boxes.origins(tester),
3250                [
3251                    Offset::ZERO,
3252                    Offset::new(0.0, 250.0),
3253                    Offset::new(0.0, 500.0)
3254                ]
3255            );
3256
3257            tester.up(&gesture);
3258            tester.pump_and_settle();
3259        });
3260    }
3261
3262    /// "Disallow stretching overscroll during a fling".
3263    #[test]
3264    fn a_disallowed_stretch_does_not_absorb_a_fling() {
3265        test_widgets(|tester| {
3266            let boxes = Boxes::new(tester);
3267            let indicator_notification = Rc::new(Cell::new(0));
3268            tester.pump_widget(counting_listener(
3269                build_test(&boxes, BuildTest::default()),
3270                &indicator_notification,
3271                &Rc::new(Cell::new(true)),
3272            ));
3273
3274            assert_one_stretching_indicator(tester);
3275            assert_eq!(indicator_notification.get(), 0);
3276
3277            boxes.jump_to_max(tester);
3278            tester.pump();
3279
3280            {
3281                let mut app = tester.cell.borrow_mut();
3282                let position = boxes.controller.as_controller().position(&app);
3283                let drag =
3284                    position.drag(&mut app, DragStartDetails::default(), Listener::new(|_| {}));
3285                drag.update(
3286                    &mut app,
3287                    DragUpdateDetails::new(
3288                        Offset::ZERO,
3289                        None,
3290                        None,
3291                        Offset::new(0.0, -5000.0),
3292                        Some(-5000.0),
3293                        None,
3294                    ),
3295                );
3296                drag.end(
3297                    &mut app,
3298                    DragEndDetails::new(
3299                        Offset::ZERO,
3300                        None,
3301                        Velocity {
3302                            pixels_per_second: Offset::new(0.0, -5000.0),
3303                        },
3304                        Some(-5000.0),
3305                    ),
3306                );
3307            }
3308            tester.pump();
3309            tester.pump_by(Duration::from_millis(16));
3310
3311            assert_eq!(indicator_notification.get(), 1);
3312            assert_eq!(stretch_strength(tester), 0.0);
3313        });
3314    }
3315
3316    /// "Disallowed stretch does not persist into a new scroll sequence".
3317    #[test]
3318    fn a_disallowed_stretch_is_allowed_again_in_the_next_scroll() {
3319        test_widgets(|tester| {
3320            let boxes = Boxes::new(tester);
3321            let indicator_notification = Rc::new(Cell::new(0));
3322            let disallow_stretch = Rc::new(Cell::new(true));
3323            tester.pump_widget(counting_listener(
3324                build_test(&boxes, BuildTest::default()),
3325                &indicator_notification,
3326                &disallow_stretch,
3327            ));
3328
3329            assert_one_stretching_indicator(tester);
3330            assert_eq!(indicator_notification.get(), 0);
3331
3332            let mut disallowed_gesture = TestPointer::touch(1);
3333            tester.down(&mut disallowed_gesture, VIEW_CENTER);
3334            tester.move_by(&mut disallowed_gesture, Offset::new(0.0, 200.0), true);
3335            tester.pump_and_settle();
3336            tester.up(&disallowed_gesture);
3337            tester.pump_and_settle();
3338
3339            assert_eq!(indicator_notification.get(), 1);
3340            assert_eq!(stretch_strength(tester), 0.0);
3341
3342            disallow_stretch.set(false);
3343            {
3344                let mut app = tester.cell.borrow_mut();
3345                let controller = boxes.controller.as_controller();
3346                let max = controller.position(&app).max_scroll_extent(&app);
3347                controller.jump_to(&mut app, max / 2.0);
3348            }
3349            tester.pump();
3350
3351            tester.fling_from(VIEW_CENTER, Offset::new(0.0, -50.0), 10000.0, 2);
3352            tester.pump_by(Duration::from_millis(100));
3353            tester.pump_by(Duration::from_millis(100));
3354            tester.pump_by(Duration::from_millis(100));
3355
3356            assert_eq!(indicator_notification.get(), 2);
3357            assert_ne!(stretch_strength(tester), 0.0);
3358        });
3359    }
3360
3361    /// The `Text('Index $index')` items the bounds tests list.
3362    fn padded_items() -> WidgetRef {
3363        ListView::builder(|_app, _context, index| {
3364            Some(
3365                Padding::new(EdgeInsetsGeometry::all(10.0))
3366                    .child(Text::new(format!("Index {index}")))
3367                    .into_widget(),
3368            )
3369        })
3370        .item_count(20)
3371        .into_widget()
3372    }
3373
3374    /// The column of the bounds tests: a 300-pixel list over a half-transparent box.
3375    fn list_over_box(clip_behavior: Option<Clip>) -> WidgetRef {
3376        let mut indicator = StretchingOverscrollIndicator::new(AxisDirection::Down)
3377            .child(SizedBox::new().height(300.0).child(padded_items()));
3378        if let Some(clip_behavior) = clip_behavior {
3379            indicator = indicator.clip_behavior(clip_behavior);
3380        }
3381        ltr(MediaQuery::new(
3382            MediaQueryData::new().size(WidgetTester::SIZE),
3383            ScrollConfiguration::new(
3384                no_overscroll_behavior(),
3385                Column::new().children([
3386                    indicator.into_widget(),
3387                    Opacity::new(0.5)
3388                        .child(Container::new().color(Color::new(0xD0FF0000)).height(100.0))
3389                        .into_widget(),
3390                ]),
3391            )
3392            .into_widget(),
3393        )
3394        .into_widget())
3395    }
3396
3397    /// "Stretch does not overflow bounds of container".
3398    #[test]
3399    fn a_stretched_list_stays_in_its_container() {
3400        test_widgets(|tester| {
3401            tester.pump_widget(list_over_box(None));
3402
3403            expect(tester, &find::text("Index 1"), finds_one_widget());
3404            assert_eq!(tester.get_center(find::text("Index 1")).dy(), 51.0);
3405
3406            let mut gesture = TestPointer::touch(1);
3407            tester.down(&mut gesture, tester.get_center(find::text("Index 1")));
3408            // Overscroll the start.
3409            tester.move_by(&mut gesture, Offset::new(0.0, 200.0), true);
3410            tester.pump_and_settle();
3411            expect(tester, &find::text("Index 1"), finds_one_widget());
3412            assert!(tester.get_center(find::text("Index 1")).dy() > 0.0);
3413            // In place of Flutter's golden, which shows the text not overlapping the red area below
3414            // the list: the stretch clips to the list's 300 pixels.
3415            assert_eq!(
3416                first_clip_rect(tester),
3417                Rect::from_ltwh(0.0, 0.0, 800.0, 300.0)
3418            );
3419            assert_eq!(first_clip_behavior(tester), Clip::HardEdge);
3420
3421            tester.up(&gesture);
3422            tester.pump_and_settle();
3423        });
3424    }
3425
3426    /// "Clip behavior is updated as needed".
3427    #[test]
3428    fn a_stretch_clips_only_while_it_stretches_a_viewport_smaller_than_the_screen() {
3429        test_widgets(|tester| {
3430            tester.pump_widget(list_over_box(None));
3431
3432            expect(tester, &find::text("Index 1"), finds_one_widget());
3433            assert_eq!(tester.get_center(find::text("Index 1")).dy(), 51.0);
3434            // Currently not clipping
3435            assert_eq!(first_clip_behavior(tester), Clip::None);
3436
3437            let mut gesture = TestPointer::touch(1);
3438            tester.down(&mut gesture, tester.get_center(find::text("Index 1")));
3439            // Overscroll the start.
3440            tester.move_by(&mut gesture, Offset::new(0.0, 200.0), true);
3441            tester.pump_and_settle();
3442            expect(tester, &find::text("Index 1"), finds_one_widget());
3443            assert!(tester.get_center(find::text("Index 1")).dy() > 0.0);
3444            // Now clipping
3445            assert_eq!(first_clip_behavior(tester), Clip::HardEdge);
3446
3447            tester.up(&gesture);
3448            tester.pump_and_settle();
3449        });
3450    }
3451
3452    /// "clipBehavior parameter updates overscroll clipping behavior".
3453    #[test]
3454    fn a_stretch_clips_with_the_clip_behavior_it_is_given() {
3455        test_widgets(|tester| {
3456            tester.pump_widget(list_over_box(Some(Clip::None)));
3457
3458            expect(tester, &find::text("Index 1"), finds_one_widget());
3459            assert_eq!(tester.get_center(find::text("Index 1")).dy(), 51.0);
3460            // Currently not clipping
3461            assert_eq!(first_clip_behavior(tester), Clip::None);
3462
3463            let mut gesture = TestPointer::touch(1);
3464            tester.down(&mut gesture, tester.get_center(find::text("Index 1")));
3465            // Overscroll the start.
3466            tester.move_by(&mut gesture, Offset::new(0.0, 200.0), true);
3467            tester.pump_and_settle();
3468            expect(tester, &find::text("Index 1"), finds_one_widget());
3469            assert!(tester.get_center(find::text("Index 1")).dy() > 0.0);
3470            // Now clipping
3471            assert_eq!(first_clip_behavior(tester), Clip::None);
3472
3473            tester.up(&gesture);
3474            tester.pump_and_settle();
3475        });
3476    }
3477
3478    /// The stretch limit tests' tree: the 300-pixel list alone, under a default
3479    /// `MediaQueryData`.
3480    fn list_alone() -> WidgetRef {
3481        ltr(MediaQuery::new(
3482            MediaQueryData::new(),
3483            ScrollConfiguration::new(
3484                no_overscroll_behavior(),
3485                StretchingOverscrollIndicator::new(AxisDirection::Down)
3486                    .child(SizedBox::new().height(300.0).child(padded_items())),
3487            )
3488            .into_widget(),
3489        )
3490        .into_widget())
3491    }
3492
3493    /// "Stretch limit".
3494    #[test]
3495    fn a_stretch_stops_at_its_limit() {
3496        test_widgets(|tester| {
3497            tester.pump_widget(list_alone());
3498            const MAX_STRETCH_LOCATION: f64 = 52.63178407049861;
3499
3500            expect(tester, &find::text("Index 1"), finds_one_widget());
3501            assert_eq!(tester.get_center(find::text("Index 1")).dy(), 51.0);
3502
3503            let mut pointer = TestPointer::touch(1);
3504            tester.down(&mut pointer, tester.get_center(find::text("Index 1")));
3505            // Overscroll beyond the limit (the viewport is 600.0).
3506            tester.move_by(&mut pointer, Offset::new(0.0, 610.0), true);
3507            tester.pump_and_settle();
3508            expect(tester, &find::text("Index 1"), finds_one_widget());
3509            // Within f32: the stretch is an f32 `Matrix4`, where Dart compares exactly.
3510            assert_f32_equals(
3511                tester.get_center(find::text("Index 1")).dy(),
3512                MAX_STRETCH_LOCATION,
3513            );
3514
3515            let mut pointer = TestPointer::touch(2);
3516            tester.down(&mut pointer, tester.get_center(find::text("Index 1")));
3517            // Overscroll way way beyond the limit
3518            tester.move_by(&mut pointer, Offset::new(0.0, 1000.0), true);
3519            tester.pump_and_settle();
3520            expect(tester, &find::text("Index 1"), finds_one_widget());
3521            // Within f32: the stretch is an f32 `Matrix4`, where Dart compares exactly.
3522            assert_f32_equals(
3523                tester.get_center(find::text("Index 1")).dy(),
3524                MAX_STRETCH_LOCATION,
3525            );
3526
3527            tester.up(&pointer);
3528            tester.pump_and_settle();
3529        });
3530    }
3531
3532    /// "Multiple pointers will not exceed stretch limit".
3533    #[test]
3534    fn more_pointers_do_not_stretch_past_the_limit() {
3535        test_widgets(|tester| {
3536            tester.pump_widget(list_alone());
3537            expect(tester, &find::text("Index 1"), finds_one_widget());
3538            assert_eq!(tester.get_center(find::text("Index 1")).dy(), 51.0);
3539
3540            let mut pointer1 = TestPointer::touch(1);
3541            tester.down(&mut pointer1, tester.get_center(find::text("Index 1")));
3542            // Overscroll the start.
3543            tester.move_by(&mut pointer1, Offset::new(0.0, 210.0), true);
3544            tester.pump_and_settle();
3545            expect(tester, &find::text("Index 1"), finds_one_widget());
3546            let mut last_stretched_location = tester.get_center(find::text("Index 1")).dy();
3547            assert!(last_stretched_location > 51.0);
3548
3549            let mut pointer2 = TestPointer::touch(2);
3550            tester.down(&mut pointer2, tester.get_center(find::text("Index 1")));
3551            // Add overscroll from an additional pointer
3552            tester.move_by(&mut pointer2, Offset::new(0.0, 210.0), true);
3553            tester.pump_and_settle();
3554            expect(tester, &find::text("Index 1"), finds_one_widget());
3555            assert!(tester.get_center(find::text("Index 1")).dy() > last_stretched_location);
3556            last_stretched_location = tester.get_center(find::text("Index 1")).dy();
3557
3558            let mut pointer3 = TestPointer::touch(3);
3559            tester.down(&mut pointer3, tester.get_center(find::text("Index 1")));
3560            // Add overscroll from an additional pointer, exceeding the max stretch (600)
3561            tester.move_by(&mut pointer3, Offset::new(0.0, 210.0), true);
3562            tester.pump_and_settle();
3563            expect(tester, &find::text("Index 1"), finds_one_widget());
3564            assert!(tester.get_center(find::text("Index 1")).dy() > last_stretched_location);
3565            last_stretched_location = tester.get_center(find::text("Index 1")).dy();
3566
3567            let mut pointer4 = TestPointer::touch(4);
3568            tester.down(&mut pointer4, tester.get_center(find::text("Index 1")));
3569            // Since we have maxed out the overscroll, it should not have stretched
3570            // further, regardless of the number of pointers.
3571            tester.move_by(&mut pointer4, Offset::new(0.0, 210.0), true);
3572            tester.pump_and_settle();
3573            expect(tester, &find::text("Index 1"), finds_one_widget());
3574            assert_eq!(
3575                tester.get_center(find::text("Index 1")).dy(),
3576                last_stretched_location
3577            );
3578
3579            tester.up(&pointer1);
3580            tester.up(&pointer2);
3581            tester.up(&pointer3);
3582            tester.up(&pointer4);
3583            tester.pump_and_settle();
3584        });
3585    }
3586
3587    /// "Stretch overscroll vertically, change direction mid scroll".
3588    #[test]
3589    fn a_vertical_stretch_turns_to_the_other_end_when_the_drag_does() {
3590        test_widgets(|tester| {
3591            let boxes = Boxes::new(tester);
3592            tester.pump_widget(build_test(
3593                &boxes,
3594                BuildTest {
3595                    // Setting the `box_height` to 100.0 will make the boxes fit in the
3596                    // scrollable viewport.
3597                    box_height: 100.0,
3598                    // To make the scroll view in the test still scrollable, we need to add
3599                    // the `AlwaysScrollableScrollPhysics`.
3600                    physics: Some(always_scrollable()),
3601                    ..BuildTest::default()
3602                },
3603            ));
3604
3605            assert_one_stretching_indicator(tester);
3606            assert_eq!(boxes.offset(tester), 0.0);
3607            assert_eq!(
3608                boxes.origins(tester),
3609                [
3610                    Offset::ZERO,
3611                    Offset::new(0.0, 100.0),
3612                    Offset::new(0.0, 200.0)
3613                ]
3614            );
3615
3616            let mut gesture = TestPointer::touch(1);
3617            tester.down(&mut gesture, VIEW_CENTER);
3618            // Overscroll the start
3619            tester.move_by(&mut gesture, Offset::new(0.0, 600.0), true);
3620            tester.pump_and_settle();
3621
3622            // The boxes should now be at different locations because of the scaling.
3623            let [box1, box2, box3] = boxes.origins(tester);
3624            assert_eq!(box1, Offset::ZERO);
3625            assert!(box2.dy() > 103.0, "{box2:?}");
3626            assert!(box3.dy() > 206.0, "{box3:?}");
3627
3628            // Move the pointer up a miniscule amount to trigger a directional change.
3629            tester.move_by(&mut gesture, Offset::new(0.0, -20.0), true);
3630            tester.pump_and_settle();
3631
3632            // The boxes should remain roughly at the same locations, since the pointer
3633            // didn't move far.
3634            let [box1, box2, box3] = boxes.origins(tester);
3635            assert_eq!(box1, Offset::ZERO);
3636            assert!(box2.dy() > 103.0, "{box2:?}");
3637            assert!(box3.dy() > 206.0, "{box3:?}");
3638
3639            // Now make the pointer overscroll to the end
3640            tester.move_by(&mut gesture, Offset::new(0.0, -1200.0), true);
3641            tester.pump_and_settle();
3642
3643            let [box1, box2, box3] = boxes.origins(tester);
3644            assert!(box1.dy() < -19.0, "{box1:?}");
3645            assert!(box2.dy() < 85.0, "{box2:?}");
3646            assert!(box3.dy() < 188.0, "{box3:?}");
3647
3648            // Release the pointer
3649            tester.up(&gesture);
3650            tester.pump_and_settle();
3651
3652            // Now the boxes should be back to their original locations.
3653            assert_eq!(
3654                boxes.origins(tester),
3655                [
3656                    Offset::ZERO,
3657                    Offset::new(0.0, 100.0),
3658                    Offset::new(0.0, 200.0)
3659                ]
3660            );
3661        });
3662    }
3663
3664    /// "Stretch overscroll horizontally, change direction mid scroll".
3665    #[test]
3666    fn a_horizontal_stretch_turns_to_the_other_end_when_the_drag_does() {
3667        test_widgets(|tester| {
3668            let boxes = Boxes::new(tester);
3669            tester.pump_widget(build_test(
3670                &boxes,
3671                BuildTest {
3672                    // Setting the `box_width` to 100.0 will make the boxes fit in the
3673                    // scrollable viewport.
3674                    box_width: 100.0,
3675                    // To make the scroll view in the test still scrollable, we need to add
3676                    // the `AlwaysScrollableScrollPhysics`.
3677                    physics: Some(always_scrollable()),
3678                    axis: Axis::Horizontal,
3679                    ..BuildTest::default()
3680                },
3681            ));
3682
3683            assert_one_stretching_indicator(tester);
3684            assert_eq!(boxes.offset(tester), 0.0);
3685            assert_eq!(
3686                boxes.origins(tester),
3687                [
3688                    Offset::ZERO,
3689                    Offset::new(100.0, 0.0),
3690                    Offset::new(200.0, 0.0)
3691                ]
3692            );
3693
3694            let mut gesture = TestPointer::touch(1);
3695            tester.down(&mut gesture, VIEW_CENTER);
3696            // Overscroll the start
3697            tester.move_by(&mut gesture, Offset::new(600.0, 0.0), true);
3698            tester.pump_and_settle();
3699
3700            // The boxes should now be at different locations because of the scaling.
3701            let [box1, box2, box3] = boxes.origins(tester);
3702            assert_eq!(box1, Offset::ZERO);
3703            assert!(box2.dx() > 102.0, "{box2:?}");
3704            assert!(box3.dx() > 205.0, "{box3:?}");
3705
3706            // Move the pointer up a miniscule amount to trigger a directional change.
3707            tester.move_by(&mut gesture, Offset::new(-20.0, 0.0), true);
3708            tester.pump_and_settle();
3709
3710            // The boxes should remain roughly at the same locations, since the pointer
3711            // didn't move far.
3712            let [box1, box2, box3] = boxes.origins(tester);
3713            assert_eq!(box1, Offset::ZERO);
3714            assert!(box2.dx() > 102.0, "{box2:?}");
3715            assert!(box3.dx() > 205.0, "{box3:?}");
3716
3717            // Now make the pointer overscroll to the end
3718            tester.move_by(&mut gesture, Offset::new(-1200.0, 0.0), true);
3719            tester.pump_and_settle();
3720
3721            let [box1, box2, box3] = boxes.origins(tester);
3722            assert!(box1.dx() < -19.0, "{box1:?}");
3723            assert!(box2.dx() < 85.0, "{box2:?}");
3724            assert!(box3.dx() < 188.0, "{box3:?}");
3725
3726            // Release the pointer
3727            tester.up(&gesture);
3728            tester.pump_and_settle();
3729
3730            // Now the boxes should be back to their original locations.
3731            assert_eq!(
3732                boxes.origins(tester),
3733                [
3734                    Offset::ZERO,
3735                    Offset::new(100.0, 0.0),
3736                    Offset::new(200.0, 0.0)
3737                ]
3738            );
3739        });
3740    }
3741
3742    /// "Fling toward the trailing edge causes stretch toward the leading edge".
3743    #[test]
3744    fn a_fling_into_the_trailing_edge_stretches_toward_the_leading_edge() {
3745        test_widgets(|tester| {
3746            let boxes = Boxes::new(tester);
3747            tester.pump_widget(build_test(&boxes, BuildTest::default()));
3748
3749            assert_one_stretching_indicator(tester);
3750            assert_eq!(boxes.offset(tester), 0.0);
3751            assert_eq!(
3752                boxes.origins(tester),
3753                [
3754                    Offset::ZERO,
3755                    Offset::new(0.0, 250.0),
3756                    Offset::new(0.0, 500.0)
3757                ]
3758            );
3759
3760            tester.fling_from(VIEW_CENTER, Offset::new(0.0, -50.0), 10000.0, 1);
3761            tester.pump_by(Duration::from_millis(100));
3762            tester.pump_by(Duration::from_millis(100));
3763            tester.pump_by(Duration::from_millis(100));
3764
3765            // The boxes should now be at different locations because of the scaling.
3766            assert_eq!(boxes.offset(tester), 150.0);
3767            let [box1, box2, box3] = boxes.origins(tester);
3768            assert!(box1.dy() < -160.0, "{box1:?}");
3769            assert!(box2.dy() < 93.0, "{box2:?}");
3770            assert!(box3.dy() < 347.0, "{box3:?}");
3771
3772            tester.pump_and_settle();
3773
3774            // The boxes should now be at their final position.
3775            assert_eq!(boxes.offset(tester), 150.0);
3776            let [box1, box2, box3] = boxes.origins(tester);
3777            assert_eq!(box1.dy(), -150.0);
3778            assert_eq!(box2.dy(), 100.0);
3779            assert_eq!(box3.dy(), 350.0);
3780        });
3781    }
3782
3783    /// "Fling toward the leading edge causes stretch toward the trailing edge".
3784    #[test]
3785    fn a_fling_into_the_leading_edge_stretches_toward_the_trailing_edge() {
3786        test_widgets(|tester| {
3787            let boxes = Boxes::new(tester);
3788            tester.pump_widget(build_test(&boxes, BuildTest::default()));
3789
3790            assert_one_stretching_indicator(tester);
3791            assert_eq!(boxes.offset(tester), 0.0);
3792            assert_eq!(
3793                boxes.origins(tester),
3794                [
3795                    Offset::ZERO,
3796                    Offset::new(0.0, 250.0),
3797                    Offset::new(0.0, 500.0)
3798                ]
3799            );
3800
3801            // We fling to the trailing edge and let it settle.
3802            tester.fling_from(VIEW_CENTER, Offset::new(0.0, -50.0), 10000.0, 1);
3803            tester.pump_and_settle();
3804
3805            // We are now at the trailing edge
3806            assert_eq!(boxes.offset(tester), 150.0);
3807            let [box1, box2, box3] = boxes.origins(tester);
3808            assert_eq!(box1.dy(), -150.0);
3809            assert_eq!(box2.dy(), 100.0);
3810            assert_eq!(box3.dy(), 350.0);
3811
3812            // Now fling to the leading edge
3813            tester.fling_from(VIEW_CENTER, Offset::new(0.0, 50.0), 10000.0, 2);
3814            tester.pump_by(Duration::from_millis(100));
3815            tester.pump_by(Duration::from_millis(100));
3816            tester.pump_by(Duration::from_millis(100));
3817            tester.pump_by(Duration::from_millis(100));
3818
3819            // The boxes should now be at different locations because of the scaling.
3820            assert_eq!(boxes.offset(tester), 0.0);
3821            let [box1, box2, box3] = boxes.origins(tester);
3822            assert_eq!(box1.dy(), 0.0);
3823            assert!(box2.dy() > 250.9, "{box2:?}");
3824            assert!(box3.dy() > 500.9, "{box3:?}");
3825
3826            tester.pump_and_settle();
3827
3828            // The boxes should now be at their final position.
3829            assert_eq!(boxes.offset(tester), 0.0);
3830            let [box1, box2, box3] = boxes.origins(tester);
3831            assert_eq!(box1.dy(), 0.0);
3832            assert_eq!(box2.dy(), 250.0);
3833            assert_eq!(box3.dy(), 500.0);
3834        });
3835    }
3836
3837    /// "changing scroll direction during recede animation will not change the stretch
3838    /// direction".
3839    #[test]
3840    fn turning_the_drag_while_the_stretch_recedes_keeps_its_direction() {
3841        test_widgets(|tester| {
3842            let boxes = Boxes::new(tester);
3843            tester.pump_widget(build_test(
3844                &boxes,
3845                BuildTest {
3846                    box_height: 205.0,
3847                    ..BuildTest::default()
3848                },
3849            ));
3850
3851            assert_one_stretching_indicator(tester);
3852
3853            // Fling to the trailing edge
3854            tester.fling_from(VIEW_CENTER, Offset::new(0.0, -50.0), 10000.0, 1);
3855            tester.pump_and_settle();
3856
3857            let [box1, box2, box3] = boxes.origins(tester);
3858            assert_eq!(box1.dy(), -15.0);
3859            assert_eq!(box2.dy(), 190.0);
3860            assert_eq!(box3.dy(), 395.0);
3861
3862            let mut gesture = TestPointer::touch(2);
3863            tester.down(&mut gesture, VIEW_CENTER);
3864            // Overscroll to the trailing edge
3865            tester.move_by(&mut gesture, Offset::new(0.0, -200.0), true);
3866            tester.pump_and_settle();
3867
3868            let [box1, box2, box3] = boxes.origins(tester);
3869            assert!(box1.dy() < -25.0, "{box1:?}");
3870            assert!(box2.dy() < 185.0, "{box2:?}");
3871            assert!(box3.dy() < 392.0, "{box3:?}");
3872
3873            // This will trigger the recede animation
3874            // The y offset of the boxes should be increasing, since the boxes were stretched
3875            // toward the leading edge.
3876            tester.move_by(&mut gesture, Offset::new(0.0, 150.0), true);
3877            tester.pump_by(Duration::from_millis(100));
3878
3879            // Explicitly check that the stretch strength is not 0.0, since this would probably
3880            // mean that the stretch direction is wrong.
3881            assert_ne!(stretch_strength(tester), 0.0);
3882
3883            tester.up(&gesture);
3884            tester.pump_by(Duration::from_millis(100));
3885
3886            // At this point, the stretchStrength should be close to 0.
3887            assert!(stretch_strength(tester).abs() < 0.01);
3888
3889            tester.pump_and_settle();
3890
3891            // The recede animation is done now, we should now be at the leading edge.
3892            let [box1, box2, box3] = boxes.origins(tester);
3893            assert_eq!(box1.dy(), 0.0);
3894            assert_eq!(box2.dy(), 205.0);
3895            assert_eq!(box3.dy(), 410.0);
3896        });
3897    }
3898
3899    /// The overscroll stretch tests' `_HighFrictionClampingScrollPhysics`.
3900    #[derive(Debug)]
3901    struct HighFrictionClampingScrollPhysics {
3902        parent: Option<ScrollPhysicsRef>,
3903    }
3904
3905    impl ScrollPhysics for HighFrictionClampingScrollPhysics {
3906        fn as_any(&self) -> &dyn std::any::Any {
3907            self
3908        }
3909
3910        fn parent(&self) -> Option<&ScrollPhysicsRef> {
3911            self.parent.as_ref()
3912        }
3913
3914        fn apply_to(&self, ancestor: Option<ScrollPhysicsRef>) -> ScrollPhysicsRef {
3915            Rc::new(HighFrictionClampingScrollPhysics {
3916                parent: ScrollPhysicsBase::build_parent(self, ancestor),
3917            })
3918        }
3919
3920        fn create_ballistic_simulation(
3921            &self,
3922            position: &dyn ScrollMetrics,
3923            velocity: f64,
3924        ) -> Option<Box<dyn Simulation>> {
3925            Some(Box::new(ClampingScrollSimulation::with_options(
3926                position.pixels(),
3927                velocity,
3928                0.94,
3929                self.tolerance_for(position),
3930            )))
3931        }
3932    }
3933
3934    /// "Stretching animation completes after fling under scroll physics with high friction".
3935    #[test]
3936    fn a_stretch_settles_after_a_fling_under_high_friction() {
3937        test_widgets(|tester| {
3938            let boxes = Boxes::new(tester);
3939            let overscroll_velocity: Rc<Cell<Option<f64>>> = Rc::default();
3940            let tree = NotificationListener::<OverscrollNotification>::new(build_test(
3941                &boxes,
3942                BuildTest {
3943                    physics: Some(Rc::new(HighFrictionClampingScrollPhysics { parent: None })),
3944                    ..BuildTest::default()
3945                },
3946            ))
3947            .on_notification({
3948                let overscroll_velocity = Rc::clone(&overscroll_velocity);
3949                move |_app, notification| {
3950                    overscroll_velocity.set(Some(notification.velocity));
3951                    false
3952                }
3953            })
3954            .into_widget();
3955            tester.pump_widget(tree);
3956
3957            assert_one_stretching_indicator(tester);
3958            assert_eq!(boxes.offset(tester), 0.0);
3959            assert_eq!(
3960                boxes.origins(tester),
3961                [
3962                    Offset::ZERO,
3963                    Offset::new(0.0, 250.0),
3964                    Offset::new(0.0, 500.0)
3965                ]
3966            );
3967
3968            // We fling to the trailing edge and let it settle.
3969            tester.fling_from(VIEW_CENTER, Offset::new(0.0, -50.0), 10000.0, 1);
3970            tester.pump_and_settle_by(Duration::from_millis(300));
3971
3972            // We are now at the trailing edge
3973            assert!(overscroll_velocity.get().expect("an overscroll") < 25.0);
3974            assert_eq!(boxes.offset(tester), 150.0);
3975            let [box1, box2, box3] = boxes.origins(tester);
3976            assert_eq!(box1.dy(), -150.0);
3977            assert_eq!(box2.dy(), 100.0);
3978            assert_eq!(box3.dy(), 350.0);
3979        });
3980    }
3981
3982    /// "Fling overscroll triggers stretching animation correctly".
3983    #[test]
3984    fn a_short_fling_into_the_edge_keeps_stretching_after_it_ends() {
3985        test_widgets(|tester| {
3986            let boxes = Boxes::new(tester);
3987            let tree = build_test(&boxes, BuildTest::default());
3988            tester.pump_widget(tree.clone());
3989
3990            assert_one_stretching_indicator(tester);
3991            assert_eq!(boxes.offset(tester), 0.0);
3992            assert_eq!(
3993                boxes.origins(tester),
3994                [
3995                    Offset::ZERO,
3996                    Offset::new(0.0, 250.0),
3997                    Offset::new(0.0, 500.0)
3998                ]
3999            );
4000
4001            // Simulates a fast and short user fling.
4002            tester.fling_from(VIEW_CENTER, Offset::new(0.0, 50.0), 1000.0, 1);
4003
4004            // Records the current stretch strength of the StretchEffect widget
4005            // before pumping additional frames, so it can be compared later
4006            // to verify that the stretch increases after the fling.
4007            let progress_strength = stretch_strength(tester);
4008
4009            tester.pump_frames(tree, Duration::from_millis(50));
4010
4011            // Verifies that the stretchStrength has increased compared to the
4012            // previously recorded value, ensuring the fling triggers stretching.
4013            assert!(stretch_strength(tester) > progress_strength);
4014
4015            tester.pump_and_settle();
4016            assert_eq!(stretch_strength(tester).abs(), 0.0);
4017        });
4018    }
4019
4020    /// "Fling overscroll triggers stretching animation correctly in reverse".
4021    #[test]
4022    fn a_short_fling_into_the_reversed_edge_keeps_stretching_after_it_ends() {
4023        test_widgets(|tester| {
4024            let boxes = Boxes::new(tester);
4025            let tree = build_test(
4026                &boxes,
4027                BuildTest {
4028                    reverse: true,
4029                    ..BuildTest::default()
4030                },
4031            );
4032            tester.pump_widget(tree.clone());
4033
4034            assert_one_stretching_indicator(tester);
4035            assert_eq!(boxes.offset(tester), 0.0);
4036            assert_eq!(
4037                boxes.origins(tester),
4038                [
4039                    Offset::new(0.0, 350.0),
4040                    Offset::new(0.0, 100.0),
4041                    Offset::new(0.0, -150.0)
4042                ]
4043            );
4044
4045            // Simulates a fast and short user fling.
4046            tester.fling_from(VIEW_CENTER, Offset::new(0.0, -50.0), 1000.0, 1);
4047
4048            // Records the current stretch strength of the StretchEffect widget
4049            // before pumping additional frames, so it can be compared later
4050            // to verify that the stretch increases after the fling.
4051            let progress_strength = stretch_strength(tester);
4052
4053            tester.pump_frames(tree, Duration::from_millis(50));
4054
4055            // Verifies that the stretchStrength has increased compared to the
4056            // previously recorded value, ensuring the fling triggers stretching.
4057            assert!(stretch_strength(tester) < progress_strength);
4058
4059            tester.pump_and_settle();
4060            assert_eq!(stretch_strength(tester).abs(), 0.0);
4061        });
4062    }
4063
4064    // ---- the notification itself ----
4065
4066    #[test]
4067    fn a_confirmation_describes_its_side_and_can_be_disallowed() {
4068        let notification = OverscrollIndicatorNotification::new(true);
4069        assert!(notification.accepted.get());
4070        notification.disallow_indicator();
4071        assert!(!notification.accepted.get());
4072        assert_eq!(
4073            format!("{notification:?}"),
4074            "OverscrollIndicatorNotification(depth: 0 (local), side: leading edge)"
4075        );
4076        assert_eq!(
4077            format!("{:?}", OverscrollIndicatorNotification::new(false)),
4078            "OverscrollIndicatorNotification(depth: 0 (local), side: trailing edge)"
4079        );
4080    }
4081}