Skip to main content

gpui/
gestures.rs

1// Modified by Longbridge for gpui-fast.
2//! Touch gesture recognition vocabulary.
3//!
4//! GPUI recognizes gestures from raw [`TouchEvent`](crate::TouchEvent)s using
5//! a portable recognizer. Taps synthesize mouse presses and releases so
6//! existing click listeners and text selection work on mobile. Pans produce
7//! [`ScrollEvent`](crate::ScrollEvent)s, including post-release
8//! momentum. Long presses and touch drags can be claimed by element listeners.
9
10use std::collections::VecDeque;
11use std::mem;
12use std::time::Duration;
13
14use scheduler::Instant;
15use smallvec::SmallVec;
16
17use crate::{
18    Axis, GestureEvent, InputEvent, IsZero, Modifiers, MouseButton, MouseDownEvent, MouseEvent,
19    MouseUpEvent, Pixels, PlatformInput, Point, ScrollDelta, ScrollEvent, ScrollSource, TouchEvent,
20    TouchId, TouchPhase, point, px, seal::Sealed,
21};
22
23const SCROLL_EVENT_SEPARATION: Duration = Duration::from_millis(28);
24
25fn dominant_axis(delta: Point<Pixels>) -> Axis {
26    if delta.x.abs() <= delta.y.abs() {
27        Axis::Vertical
28    } else {
29        Axis::Horizontal
30    }
31}
32
33fn lock_delta_to_axis(delta: &mut Point<Pixels>, axis: Axis) {
34    match axis {
35        Axis::Vertical => delta.x = Pixels::ZERO,
36        Axis::Horizontal => delta.y = Pixels::ZERO,
37    }
38}
39
40fn movements_oppose(left: Point<Pixels>, right: Point<Pixels>) -> bool {
41    f32::from(left.x) * f32::from(right.x) + f32::from(left.y) * f32::from(right.y) < 0.
42}
43
44/// Tracks the dominant axis across the events in a scroll gesture.
45#[derive(Clone, Copy, Debug, Default)]
46pub struct OngoingScroll {
47    last_event: Option<Instant>,
48    axis: Option<Axis>,
49}
50
51impl OngoingScroll {
52    /// Filters the given delta to the dominant axis of the current scroll gesture.
53    ///
54    /// Gestures are delimited by their touch phase when available, with a timeout
55    /// fallback for platforms that only emit [`TouchPhase::Moved`].
56    pub fn filter(&mut self, delta: &mut Point<Pixels>, touch_phase: TouchPhase) {
57        self.filter_at(delta, touch_phase, Instant::now())
58    }
59
60    fn filter_at(&mut self, delta: &mut Point<Pixels>, touch_phase: TouchPhase, now: Instant) {
61        const UNLOCK_PERCENT: f32 = 1.9;
62        const UNLOCK_LOWER_BOUND: Pixels = px(6.);
63
64        if matches!(touch_phase, TouchPhase::Ended | TouchPhase::Cancelled) {
65            self.last_event = None;
66            self.axis = None;
67            return;
68        }
69
70        let x = delta.x.abs();
71        let y = delta.y.abs();
72        if x.is_zero() && y.is_zero() {
73            if touch_phase == TouchPhase::Started {
74                self.last_event = None;
75                self.axis = None;
76            }
77            return;
78        }
79
80        let starts_new_gesture = touch_phase == TouchPhase::Started
81            || self
82                .last_event
83                .is_none_or(|last_event| now.duration_since(last_event) >= SCROLL_EVENT_SEPARATION);
84        let mut axis = self.axis;
85        if starts_new_gesture {
86            axis = Some(dominant_axis(*delta));
87        } else if x.max(y) >= UNLOCK_LOWER_BOUND {
88            match axis {
89                Some(Axis::Vertical) if x > y && x >= y * UNLOCK_PERCENT => {
90                    axis = None;
91                }
92                Some(Axis::Horizontal) if y > x && y >= x * UNLOCK_PERCENT => {
93                    axis = None;
94                }
95                _ => {}
96            }
97        }
98
99        self.last_event = Some(now);
100        self.axis = axis;
101        if let Some(axis) = axis {
102            lock_delta_to_axis(delta, axis);
103        }
104    }
105}
106
107/// Feel constants consumed by gesture recognizers. Provided on a best-effort
108/// basis, depending on each platform's support, defaulting to GPUI's own
109/// (iOS flavored) values
110#[derive(Clone, Copy, Debug, PartialEq)]
111pub struct GestureTuning {
112    /// Distance a touch may travel before it stops being a potential tap and
113    /// becomes a pan/drag.
114    pub touch_slop: Pixels,
115    /// Maximum interval between taps for them to accumulate a tap count.
116    pub multi_tap_interval: Duration,
117    /// Maximum distance between taps for them to accumulate a tap count.
118    pub multi_tap_slop: Pixels,
119    /// How long a touch must remain within [`Self::touch_slop`] to be
120    /// recognized as a long press.
121    pub long_press_duration: Duration,
122    /// How scroll momentum decelerates after a fling.
123    pub scroll_physics: ScrollPhysics,
124    /// Minimum release velocity, in pixels per second, required to start
125    /// scroll momentum.
126    pub min_fling_velocity: f32,
127}
128
129impl Default for GestureTuning {
130    fn default() -> Self {
131        Self {
132            touch_slop: px(8.),
133            multi_tap_interval: Duration::from_millis(400),
134            multi_tap_slop: px(16.),
135            long_press_duration: Duration::from_millis(500),
136            scroll_physics: ScrollPhysics::ios(),
137            min_fling_velocity: 50.,
138        }
139    }
140}
141
142/// How free scrolling decelerates after a fling.
143///
144/// This models deceleration only. Boundary behavior — bouncing, edge glow,
145/// clamping — is the scroll container's policy: the container is the one that
146/// knows its extents.
147#[derive(Clone, Copy, Debug, PartialEq)]
148pub enum ScrollPhysics {
149    /// Exponential velocity decay, the `UIScrollView` model:
150    /// `velocity(t) = v₀ · decay_per_msᵐˢ`.
151    Exponential {
152        /// Per-millisecond velocity decay factor. `UIScrollView`'s normal
153        /// deceleration rate is `0.998`.
154        decay_per_ms: f32,
155    },
156    /// The friction spline of Android's `OverScroller`: fling duration and
157    /// distance follow a logarithmic deceleration law, and progress along
158    /// the fling follows a cubic-Bezier ease-out curve. Transcribed from
159    /// AOSP's `SplineOverScroller` (Apache-2.0).
160    FrictionSpline {
161        /// The scroll friction coefficient;
162        /// `ViewConfiguration.getScrollFriction()` is `0.015` on Android.
163        friction: f32,
164        /// Pixels per physical inch of the display, in the coordinate space
165        /// the fling runs in. Android folds display density into its
166        /// deceleration coefficient, so the same finger speed flings
167        /// further in pixels on a denser screen.
168        pixels_per_inch: f32,
169    },
170}
171
172impl ScrollPhysics {
173    /// iOS scroll feel: `UIScrollView`'s normal deceleration rate.
174    pub fn ios() -> Self {
175        Self::Exponential {
176            decay_per_ms: 0.998,
177        }
178    }
179
180    /// Android scroll feel: `OverScroller` with stock friction, at Android's
181    /// nominal density of 160 density-independent pixels per inch — the
182    /// right pairing when fling distances are in logical pixels. Platforms
183    /// that fling in physical pixels, or know the display's true density in
184    /// their logical space, should construct
185    /// [`ScrollPhysics::FrictionSpline`] directly.
186    pub fn android() -> Self {
187        Self::FrictionSpline {
188            friction: 0.015,
189            pixels_per_inch: 160.,
190        }
191    }
192
193    /// How long a fling released at `speed` pixels per second coasts before
194    /// it stops.
195    fn fling_duration(self, speed: f32) -> Duration {
196        match self {
197            Self::Exponential { decay_per_ms } => {
198                if speed <= MOMENTUM_STOP_VELOCITY {
199                    return Duration::ZERO;
200                }
201                let milliseconds = (MOMENTUM_STOP_VELOCITY / speed).ln() / decay_per_ms.ln();
202                Duration::from_secs_f32(milliseconds / 1000.)
203            }
204            Self::FrictionSpline {
205                friction,
206                pixels_per_inch,
207            } => {
208                if speed <= 0. {
209                    return Duration::ZERO;
210                }
211                let deceleration = friction_spline::deceleration(speed, friction, pixels_per_inch);
212                let seconds = (deceleration / (friction_spline::deceleration_rate() - 1.)).exp();
213                Duration::from_secs_f64(seconds)
214            }
215        }
216    }
217
218    /// Distance traveled `elapsed` into a fling released at `speed` pixels
219    /// per second, in pixels along the fling direction. Evaluated in closed
220    /// form so the trajectory is independent of tick timing.
221    fn fling_distance(self, speed: f32, elapsed: Duration) -> f32 {
222        let duration = self.fling_duration(speed);
223        if duration.is_zero() {
224            return 0.;
225        }
226        let elapsed = elapsed.min(duration);
227        match self {
228            Self::Exponential { decay_per_ms } => {
229                // ∫₀ᵗ v₀·kᵐˢ dms, with speed converted to pixels per
230                // millisecond.
231                let milliseconds = elapsed.as_secs_f32() * 1000.;
232                (speed / 1000.) * (decay_per_ms.powf(milliseconds) - 1.) / decay_per_ms.ln()
233            }
234            Self::FrictionSpline {
235                friction,
236                pixels_per_inch,
237            } => {
238                let deceleration = friction_spline::deceleration(speed, friction, pixels_per_inch);
239                let rate = friction_spline::deceleration_rate();
240                let total_distance = friction as f64
241                    * friction_spline::physical_coefficient(pixels_per_inch)
242                    * (rate / (rate - 1.) * deceleration).exp();
243                let progress = elapsed.as_secs_f64() / duration.as_secs_f64();
244                total_distance as f32 * friction_spline::distance_coefficient(progress as f32)
245            }
246        }
247    }
248}
249
250/// The fling model of Android's `OverScroller.SplineOverScroller`,
251/// transcribed from AOSP (Apache-2.0). `SPLINE_TIME`, which AOSP uses for
252/// programmatic scroll animations rather than flings, is intentionally not
253/// transcribed.
254mod friction_spline {
255    use std::sync::LazyLock;
256
257    const NB_SAMPLES: usize = 100;
258    const INFLEXION: f32 = 0.35;
259    const START_TENSION: f32 = 0.5;
260    const END_TENSION: f32 = 1.0;
261    const P1: f32 = START_TENSION * INFLEXION;
262    const P2: f32 = 1.0 - END_TENSION * (1.0 - INFLEXION);
263
264    /// Android's `DECELERATION_RATE`: `ln(0.78) / ln(0.9)`.
265    pub(super) fn deceleration_rate() -> f64 {
266        0.78f64.ln() / 0.9f64.ln()
267    }
268
269    /// `SPLINE_POSITION` from AOSP's static initializer: fractional fling
270    /// distance sampled at 100 evenly spaced fractions of the fling
271    /// duration, from a cubic Bezier with control points shaped by
272    /// `INFLEXION` and the start/end tensions.
273    static SPLINE_POSITION: LazyLock<[f32; NB_SAMPLES + 1]> = LazyLock::new(|| {
274        let mut spline_position = [0f32; NB_SAMPLES + 1];
275        let mut x_min = 0f32;
276        for (i, sample) in spline_position.iter_mut().take(NB_SAMPLES).enumerate() {
277            let alpha = i as f32 / NB_SAMPLES as f32;
278            let mut x_max = 1f32;
279            let (x, coefficient) = loop {
280                let x = x_min + (x_max - x_min) / 2.;
281                let coefficient = 3. * x * (1. - x);
282                let time = coefficient * ((1. - x) * P1 + x * P2) + x * x * x;
283                if (time - alpha).abs() < 1e-5 {
284                    break (x, coefficient);
285                }
286                if time > alpha {
287                    x_max = x;
288                } else {
289                    x_min = x;
290                }
291            };
292            *sample = coefficient * ((1. - x) * START_TENSION + x) + x * x * x;
293        }
294        spline_position[NB_SAMPLES] = 1.;
295        spline_position
296    });
297
298    /// `SensorManager.GRAVITY_EARTH · 39.37 in/m · ppi · 0.84`, AOSP's
299    /// `mPhysicalCoeff`: gravity expressed in pixels, times an empirical
300    /// "look and feel" tuning factor.
301    pub(super) fn physical_coefficient(pixels_per_inch: f32) -> f64 {
302        9.80665 * 39.37 * pixels_per_inch as f64 * 0.84
303    }
304
305    /// AOSP's `getSplineDeceleration`.
306    pub(super) fn deceleration(speed: f32, friction: f32, pixels_per_inch: f32) -> f64 {
307        (INFLEXION as f64 * speed as f64
308            / (friction as f64 * physical_coefficient(pixels_per_inch)))
309        .ln()
310    }
311
312    /// Fraction of the total fling distance covered at fraction `time` of
313    /// the fling duration: table lookup plus linear interpolation, as in
314    /// `SplineOverScroller.update`.
315    pub(super) fn distance_coefficient(time: f32) -> f32 {
316        if time >= 1. {
317            return 1.;
318        }
319        let index = ((NB_SAMPLES as f32 * time) as usize).min(NB_SAMPLES - 1);
320        let time_lower = index as f32 / NB_SAMPLES as f32;
321        let time_upper = (index + 1) as f32 / NB_SAMPLES as f32;
322        let distance_lower = SPLINE_POSITION[index];
323        let distance_upper = SPLINE_POSITION[index + 1];
324        let velocity_coefficient = (distance_upper - distance_lower) / (time_upper - time_lower);
325        distance_lower + (time - time_lower) * velocity_coefficient
326    }
327
328    #[cfg(test)]
329    pub(super) fn bezier_time_and_position(parameter: f32) -> (f32, f32) {
330        let coefficient = 3. * parameter * (1. - parameter);
331        let cubed = parameter * parameter * parameter;
332        (
333            coefficient * ((1. - parameter) * P1 + parameter * P2) + cubed,
334            coefficient * ((1. - parameter) * START_TENSION + parameter) + cubed,
335        )
336    }
337
338    #[cfg(test)]
339    pub(super) fn spline_position_samples() -> &'static [f32; NB_SAMPLES + 1] {
340        &SPLINE_POSITION
341    }
342}
343
344/// The set of gesture kinds that participate in recognition.
345///
346/// Used by [`PlatformGestures::native_recognizers`] to declare which gestures
347/// the platform recognizes natively rather than leaving to gpui core's
348/// portable recognizers.
349#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
350pub struct GestureKinds {
351    /// Tap (and multi-tap), synthesized as mouse presses by the portable recognizer.
352    pub tap: bool,
353    /// Long press, surfaced as [`LongPressEvent`].
354    pub long_press: bool,
355    /// Pan/scroll (including fling momentum), surfaced as
356    /// [`ScrollEvent`](crate::ScrollEvent)s.
357    pub pan: bool,
358    /// Pinch to zoom, surfaced as [`PinchEvent`](crate::PinchEvent)s.
359    pub pinch: bool,
360}
361
362impl GestureKinds {
363    /// No gestures; gpui core's portable recognizers handle everything.
364    pub const NONE: Self = Self {
365        tap: false,
366        long_press: false,
367        pan: false,
368        pinch: false,
369    };
370
371    /// All gesture kinds.
372    pub const ALL: Self = Self {
373        tap: true,
374        long_press: true,
375        pan: true,
376        pinch: true,
377    };
378}
379
380/// A direct touch drag claimed by an element before touch input becomes a tap,
381/// long press, or scrolling gesture.
382#[derive(Clone, Debug)]
383pub struct TouchDragEvent {
384    /// The phase of the touch drag.
385    pub phase: TouchPhase,
386    /// The position where the touch started.
387    pub start_position: Point<Pixels>,
388    /// The touch's current position.
389    pub position: Point<Pixels>,
390}
391
392impl Sealed for TouchDragEvent {}
393impl InputEvent for TouchDragEvent {
394    fn to_platform_input(self) -> PlatformInput {
395        PlatformInput::TouchDrag(self)
396    }
397}
398impl GestureEvent for TouchDragEvent {}
399impl MouseEvent for TouchDragEvent {}
400
401/// A back-navigation gesture, such as the iOS swipe from the leading screen
402/// edge.
403///
404/// Elements receive it through
405/// [`InteractiveElement::on_back_gesture`](crate::InteractiveElement::on_back_gesture).
406/// The innermost element under [`Self::start_position`] claims the whole
407/// gesture when it starts; the platform cancels the gesture if no element does.
408/// Every phase is delivered at the start position, so the claiming element
409/// should stay in place while it animates its contents.
410#[derive(Clone, Debug, Default)]
411pub struct BackGestureEvent {
412    /// The phase of the gesture.
413    pub phase: BackGesturePhase,
414    /// Where the gesture started.
415    pub start_position: Point<Pixels>,
416    /// How far the gesture has travelled toward going back, from 0 to 1.
417    pub progress: f32,
418}
419
420/// The phase of a [`BackGestureEvent`].
421#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
422pub enum BackGesturePhase {
423    /// The gesture began. Claiming it here routes the remaining phases to the
424    /// same element.
425    #[default]
426    Started,
427    /// The gesture moved; [`BackGestureEvent::progress`] changed.
428    Progressed,
429    /// The gesture ended and the platform decided to go back.
430    Committed,
431    /// The gesture ended without going back.
432    Cancelled,
433}
434
435impl Sealed for BackGestureEvent {}
436impl InputEvent for BackGestureEvent {
437    fn to_platform_input(self) -> PlatformInput {
438        PlatformInput::BackGesture(self)
439    }
440}
441impl GestureEvent for BackGestureEvent {}
442impl MouseEvent for BackGestureEvent {}
443
444/// A phased long-press gesture recognized from a touch.
445#[derive(Clone, Debug)]
446pub struct LongPressEvent {
447    /// The phase of the long press.
448    pub phase: TouchPhase,
449    /// The position where the touch started.
450    pub start_position: Point<Pixels>,
451    /// The touch's current position.
452    pub position: Point<Pixels>,
453}
454
455impl Default for LongPressEvent {
456    fn default() -> Self {
457        Self {
458            phase: TouchPhase::Started,
459            start_position: Point::default(),
460            position: Point::default(),
461        }
462    }
463}
464
465impl Sealed for LongPressEvent {}
466impl InputEvent for LongPressEvent {
467    fn to_platform_input(self) -> PlatformInput {
468        PlatformInput::LongPress(self)
469    }
470}
471impl GestureEvent for LongPressEvent {}
472impl MouseEvent for LongPressEvent {}
473
474/// Platform gesture recognition services.
475///
476/// If your mobile platform supports native gesture recognition, use this
477/// to share it with GPUI.
478pub trait PlatformGestures {
479    /// Feel constants for the portable recognizers on this platform.
480    fn tuning(&self) -> GestureTuning {
481        GestureTuning::default()
482    }
483
484    /// The gesture kinds this platform recognizes natively.
485    fn native_recognizers(&self) -> GestureKinds {
486        GestureKinds::NONE
487    }
488}
489
490/// A no-op [`PlatformGestures`] implementation: no native recognizers and
491/// default tuning. Suitable for desktop platforms and tests.
492pub struct NullPlatformGestures;
493
494impl PlatformGestures for NullPlatformGestures {}
495
496/// Ceiling on recognized fling velocity, in pixels per second (matches
497/// Flutter's `kMaxFlingVelocity`).
498const MAX_FLING_VELOCITY: f32 = 8000.;
499
500/// Momentum below this speed, in pixels per second, is imperceptible. The
501/// exponential model, which never mathematically stops, treats reaching this
502/// speed as the end of the fling. (The friction spline has a finite duration
503/// of its own.)
504const MOMENTUM_STOP_VELOCITY: f32 = 10.;
505
506/// How far back the release-velocity estimate looks. Samples older than this
507/// reflect an earlier part of the gesture, not the speed at release.
508const VELOCITY_WINDOW: Duration = Duration::from_millis(100);
509
510/// A pause between samples longer than this means the finger stopped:
511/// anything before the pause describes an earlier motion, not the release
512/// (Flutter's `kAssumePointerMoveStoppedMilliseconds`). Touch hardware
513/// reports movement every 8–16ms while the finger is in motion.
514const VELOCITY_ASSUME_STOPPED_GAP: Duration = Duration::from_millis(40);
515
516const VELOCITY_MAX_SAMPLES: usize = 20;
517
518/// The portable recognizer behind raw touch input: it watches the
519/// [`TouchEvent`] stream for one touch at a time and resolves it into either
520/// a tap or a pan, following the competition model described in the module
521/// docs. Pans continue into post-release momentum when the touch lifts at
522/// speed; the window drives that phase through [`Self::tick_momentum`].
523///
524/// Taps are currently surfaced as synthesized mouse presses rather than
525/// [`ClickEvent::Touch`](crate::ClickEvent), which keeps every existing
526/// mouse-driven behavior (click listeners, caret placement, double-tap
527/// selection) working before elements grow a direct tap-delivery path.
528/// Pinch recognition is not implemented yet, and additional touches are ignored
529/// while one is being recognized.
530pub(crate) struct TouchGestureRecognizer {
531    tuning: GestureTuning,
532    state: TouchGestureState,
533    momentum: Option<Momentum>,
534    last_tap: Option<CompletedTap>,
535}
536
537/// A semantic event recognized from raw touches, ready to dispatch through
538/// the window's existing input paths.
539#[derive(Debug)]
540pub(crate) enum RecognizedTouchGesture {
541    /// One step of a pan (or of its post-release momentum), delivered to
542    /// scroll listeners at the pan's starting position.
543    Scroll(ScrollEvent),
544    /// A recognized tap, delivered as a synthesized mouse press and release.
545    Tap {
546        down: MouseDownEvent,
547        up: MouseUpEvent,
548    },
549    TouchDrag(TouchDragEvent),
550    LongPress(LongPressEvent),
551}
552
553enum TouchGestureState {
554    Idle,
555    /// The touch is still within `touch_slop` of where it started: it can
556    /// still resolve into either a tap or a pan.
557    Pending {
558        touch: ActiveTouch,
559        deadline: Instant,
560        long_press_offered: bool,
561        touch_drag_offered: bool,
562    },
563    /// The touch exceeded `touch_slop`: it is a pan until it ends, and its
564    /// movement flows out as scroll events.
565    Panning {
566        touch: ActiveTouch,
567        axis: Axis,
568    },
569    /// The touch caught a fling: it is a pan from its first pixel, and can
570    /// never be a tap, but its axis is its own — decided by its first
571    /// movement, not inherited from the fling it stopped.
572    Caught(ActiveTouch),
573    LongPressing(ActiveTouch),
574    TouchDragging(ActiveTouch),
575}
576
577struct ActiveTouch {
578    id: TouchId,
579    start_position: Point<Pixels>,
580    /// The latest raw position reported for this touch.
581    last_position: Point<Pixels>,
582    /// The position pan output has scrolled to so far. While panning this
583    /// may run ahead of the raw touch by the event's predicted position;
584    /// the release event targets the raw position again, so the total
585    /// scrolled distance always converges to the finger's actual travel.
586    emitted_position: Point<Pixels>,
587    /// Retained across stationary samples so prediction corrections cannot
588    /// reverse a pan when integer browser coordinates repeat.
589    last_movement: Point<Pixels>,
590    velocity_tracker: VelocityTracker,
591}
592
593struct CompletedTap {
594    position: Point<Pixels>,
595    time: Instant,
596    count: usize,
597}
598
599/// One fling in progress. The trajectory is a closed-form curve of elapsed
600/// time — each tick evaluates it and emits the increment — so the fling is
601/// exactly frame-rate independent: a stalled frame simply resumes further
602/// along the same curve.
603struct Momentum {
604    /// Where the pan started; synthesized scroll events keep hit-testing
605    /// there so momentum stays with the container the gesture began on.
606    position: Point<Pixels>,
607    /// Unit vector of the release velocity.
608    direction: Point<f32>,
609    /// Release speed in pixels per second.
610    speed: f32,
611    started_at: Instant,
612    duration: Duration,
613    /// Distance already emitted along `direction`, in pixels.
614    emitted_distance: f32,
615}
616
617impl TouchGestureRecognizer {
618    pub(crate) fn new(tuning: GestureTuning) -> Self {
619        Self {
620            tuning,
621            state: TouchGestureState::Idle,
622            momentum: None,
623            last_tap: None,
624        }
625    }
626
627    pub(crate) fn handle_event(
628        &mut self,
629        event: &TouchEvent,
630    ) -> SmallVec<[RecognizedTouchGesture; 2]> {
631        self.handle_event_at(event, Instant::now())
632    }
633
634    fn handle_event_at(
635        &mut self,
636        event: &TouchEvent,
637        now: Instant,
638    ) -> SmallVec<[RecognizedTouchGesture; 2]> {
639        let mut recognized = SmallVec::new();
640        match event.phase {
641            TouchPhase::Started => {
642                let caught_fling = if let Some(momentum) = self.momentum.take() {
643                    recognized.push(RecognizedTouchGesture::Scroll(scroll_event(
644                        momentum.position,
645                        Point::default(),
646                        TouchPhase::Ended,
647                    )));
648                    true
649                } else {
650                    false
651                };
652                if matches!(self.state, TouchGestureState::Idle) {
653                    let mut velocity_tracker = VelocityTracker::default();
654                    velocity_tracker.push(now, event.position);
655                    let touch = ActiveTouch {
656                        id: event.id,
657                        start_position: event.position,
658                        last_position: event.position,
659                        emitted_position: event.position,
660                        last_movement: Point::default(),
661                        velocity_tracker,
662                    };
663                    if caught_fling {
664                        // A touch that catches a fling is a drag from the
665                        // first pixel: waiting out the slop would freeze the
666                        // content mid-scroll and then jump. It can also never
667                        // be a tap; releasing it just leaves the content
668                        // stopped, as on Android and iOS. Which way it pans
669                        // is its own to decide: a finger that stops a
670                        // sideways fling and moves up scrolls up.
671                        recognized.push(RecognizedTouchGesture::Scroll(scroll_event(
672                            touch.start_position,
673                            Point::default(),
674                            TouchPhase::Started,
675                        )));
676                        self.state = TouchGestureState::Caught(touch);
677                    } else {
678                        self.state = TouchGestureState::Pending {
679                            touch,
680                            deadline: now + self.tuning.long_press_duration,
681                            long_press_offered: false,
682                            touch_drag_offered: false,
683                        };
684                    }
685                }
686            }
687            TouchPhase::Moved => match mem::replace(&mut self.state, TouchGestureState::Idle) {
688                TouchGestureState::Pending {
689                    mut touch,
690                    deadline,
691                    long_press_offered,
692                    touch_drag_offered,
693                } if touch.id == event.id => {
694                    touch.velocity_tracker.push(now, event.position);
695                    touch.last_position = event.position;
696                    let accumulated = event.position - touch.start_position;
697                    if accumulated.magnitude() > f64::from(self.tuning.touch_slop) {
698                        // Carry the full movement so far into the first scroll
699                        // step: the content catches up to the finger instead
700                        // of losing the slop distance.
701                        let mut target = event.predicted_position.unwrap_or(event.position);
702                        let axis = dominant_axis(accumulated);
703                        let mut delta = target - touch.start_position;
704                        lock_delta_to_axis(&mut delta, axis);
705                        touch.last_movement = accumulated;
706                        lock_delta_to_axis(&mut touch.last_movement, axis);
707                        if movements_oppose(delta, touch.last_movement) {
708                            target = event.position;
709                            delta = accumulated;
710                            lock_delta_to_axis(&mut delta, axis);
711                        }
712                        touch.emitted_position = target;
713                        recognized.push(RecognizedTouchGesture::Scroll(scroll_event(
714                            touch.start_position,
715                            delta,
716                            TouchPhase::Started,
717                        )));
718                        self.state = TouchGestureState::Panning { touch, axis };
719                    } else {
720                        self.state = TouchGestureState::Pending {
721                            touch,
722                            deadline,
723                            long_press_offered,
724                            touch_drag_offered,
725                        };
726                    }
727                }
728                TouchGestureState::Caught(touch) if touch.id == event.id => {
729                    let accumulated = event.position - touch.start_position;
730                    if accumulated == Point::default() {
731                        self.state = TouchGestureState::Caught(touch);
732                    } else {
733                        // The first movement picks the axis; from here on this
734                        // is an ordinary pan, so let the pan arm emit it.
735                        let axis = dominant_axis(accumulated);
736                        self.state = TouchGestureState::Panning { touch, axis };
737                        return self.handle_event_at(event, now);
738                    }
739                }
740                TouchGestureState::Panning { mut touch, axis } if touch.id == event.id => {
741                    let mut raw_delta = event.position - touch.last_position;
742                    lock_delta_to_axis(&mut raw_delta, axis);
743                    if raw_delta != Point::default() {
744                        touch.last_movement = raw_delta;
745                    }
746                    touch.velocity_tracker.push(now, event.position);
747                    touch.last_position = event.position;
748                    let mut target = event.predicted_position.unwrap_or(event.position);
749                    let mut delta = target - touch.emitted_position;
750                    lock_delta_to_axis(&mut delta, axis);
751                    // Prediction error must not reverse content while the raw
752                    // touch still advances. Fall back to the raw position so a
753                    // real finger reversal remains responsive.
754                    if movements_oppose(delta, touch.last_movement) {
755                        target = event.position;
756                        delta = target - touch.emitted_position;
757                        lock_delta_to_axis(&mut delta, axis);
758                        if movements_oppose(delta, touch.last_movement) {
759                            target = touch.emitted_position;
760                            delta = Point::default();
761                        }
762                    }
763                    touch.emitted_position = target;
764                    recognized.push(RecognizedTouchGesture::Scroll(scroll_event(
765                        touch.start_position,
766                        delta,
767                        TouchPhase::Moved,
768                    )));
769                    self.state = TouchGestureState::Panning { touch, axis };
770                }
771                TouchGestureState::LongPressing(mut touch) if touch.id == event.id => {
772                    touch.last_position = event.position;
773                    recognized.push(RecognizedTouchGesture::LongPress(LongPressEvent {
774                        phase: TouchPhase::Moved,
775                        start_position: touch.start_position,
776                        position: event.position,
777                    }));
778                    self.state = TouchGestureState::LongPressing(touch);
779                }
780                TouchGestureState::TouchDragging(mut touch) if touch.id == event.id => {
781                    touch.last_position = event.position;
782                    recognized.push(RecognizedTouchGesture::TouchDrag(TouchDragEvent {
783                        phase: TouchPhase::Moved,
784                        start_position: touch.start_position,
785                        position: event.position,
786                    }));
787                    self.state = TouchGestureState::TouchDragging(touch);
788                }
789                other => self.state = other,
790            },
791            TouchPhase::Ended => match mem::replace(&mut self.state, TouchGestureState::Idle) {
792                TouchGestureState::Pending { touch, .. } if touch.id == event.id => {
793                    let tap_count = match &self.last_tap {
794                        Some(tap)
795                            if now.duration_since(tap.time) <= self.tuning.multi_tap_interval
796                                && (event.position - tap.position).magnitude()
797                                    <= f64::from(self.tuning.multi_tap_slop) =>
798                        {
799                            tap.count + 1
800                        }
801                        _ => 1,
802                    };
803                    self.last_tap = Some(CompletedTap {
804                        position: event.position,
805                        time: now,
806                        count: tap_count,
807                    });
808                    recognized.push(RecognizedTouchGesture::Tap {
809                        down: MouseDownEvent {
810                            button: MouseButton::Left,
811                            position: event.position,
812                            modifiers: Modifiers::default(),
813                            click_count: tap_count,
814                            first_mouse: false,
815                        },
816                        up: MouseUpEvent {
817                            button: MouseButton::Left,
818                            position: event.position,
819                            modifiers: Modifiers::default(),
820                            click_count: tap_count,
821                        },
822                    });
823                }
824                TouchGestureState::Caught(touch) if touch.id == event.id => {
825                    // Never moved: the content it stopped stays where it is.
826                    recognized.push(RecognizedTouchGesture::Scroll(scroll_event(
827                        touch.start_position,
828                        Point::default(),
829                        TouchPhase::Ended,
830                    )));
831                }
832                TouchGestureState::Panning { touch, axis } if touch.id == event.id => {
833                    // The release deliberately contributes no velocity
834                    // sample: it usually repeats the last movement's position
835                    // with a later timestamp, which would dilute the
836                    // estimate. But a release long after the last movement
837                    // means the finger had already stopped, so nothing
838                    // flings.
839                    let finger_stopped =
840                        touch
841                            .velocity_tracker
842                            .latest_sample_time()
843                            .is_none_or(|latest| {
844                                now.duration_since(latest) > VELOCITY_ASSUME_STOPPED_GAP
845                            });
846                    let mut velocity = if finger_stopped {
847                        Point::default()
848                    } else {
849                        touch.velocity_tracker.velocity()
850                    };
851                    match axis {
852                        Axis::Vertical => velocity.x = 0.,
853                        Axis::Horizontal => velocity.y = 0.,
854                    }
855                    let speed = (velocity.x.powi(2) + velocity.y.powi(2)).sqrt();
856                    let mut release_delta = event.position - touch.emitted_position;
857                    lock_delta_to_axis(&mut release_delta, axis);
858                    if speed >= self.tuning.min_fling_velocity {
859                        let direction = point(velocity.x / speed, velocity.y / speed);
860                        let speed = speed.min(MAX_FLING_VELOCITY);
861                        let duration = self.tuning.scroll_physics.fling_duration(speed);
862                        if !duration.is_zero() {
863                            let total_distance =
864                                self.tuning.scroll_physics.fling_distance(speed, duration);
865                            // Prediction may have left the content ahead of
866                            // the raw release position. Emitting that
867                            // correction here would visibly snap the content
868                            // backwards just as the fling launches, so fold
869                            // it into the fling instead: start the curve
870                            // already advanced by the overshoot, keeping the
871                            // total travel exact while staying monotonic.
872                            let overshoot = -(f32::from(release_delta.x) * direction.x
873                                + f32::from(release_delta.y) * direction.y);
874                            let emitted_distance = if overshoot > 0. && overshoot < total_distance {
875                                release_delta +=
876                                    point(px(direction.x * overshoot), px(direction.y * overshoot));
877                                overshoot
878                            } else {
879                                0.
880                            };
881                            self.momentum = Some(Momentum {
882                                position: touch.start_position,
883                                direction,
884                                speed,
885                                started_at: now,
886                                duration,
887                                emitted_distance,
888                            });
889                        }
890                    }
891                    recognized.push(RecognizedTouchGesture::Scroll(scroll_event(
892                        touch.start_position,
893                        release_delta,
894                        TouchPhase::Ended,
895                    )));
896                }
897                TouchGestureState::LongPressing(touch) if touch.id == event.id => {
898                    recognized.push(RecognizedTouchGesture::LongPress(LongPressEvent {
899                        phase: TouchPhase::Ended,
900                        start_position: touch.start_position,
901                        position: event.position,
902                    }));
903                }
904                TouchGestureState::TouchDragging(touch) if touch.id == event.id => {
905                    recognized.push(RecognizedTouchGesture::TouchDrag(TouchDragEvent {
906                        phase: TouchPhase::Ended,
907                        start_position: touch.start_position,
908                        position: event.position,
909                    }));
910                }
911                other => self.state = other,
912            },
913            TouchPhase::Cancelled => match mem::replace(&mut self.state, TouchGestureState::Idle) {
914                TouchGestureState::Pending { touch, .. } if touch.id == event.id => {}
915                TouchGestureState::Panning { touch, .. } | TouchGestureState::Caught(touch)
916                    if touch.id == event.id =>
917                {
918                    recognized.push(RecognizedTouchGesture::Scroll(scroll_event(
919                        touch.start_position,
920                        Point::default(),
921                        TouchPhase::Cancelled,
922                    )));
923                }
924                TouchGestureState::LongPressing(touch) if touch.id == event.id => {
925                    recognized.push(RecognizedTouchGesture::LongPress(LongPressEvent {
926                        phase: TouchPhase::Cancelled,
927                        start_position: touch.start_position,
928                        position: event.position,
929                    }));
930                }
931                TouchGestureState::TouchDragging(touch) if touch.id == event.id => {
932                    recognized.push(RecognizedTouchGesture::TouchDrag(TouchDragEvent {
933                        phase: TouchPhase::Cancelled,
934                        start_position: touch.start_position,
935                        position: event.position,
936                    }));
937                }
938                other => self.state = other,
939            },
940        }
941        recognized
942    }
943
944    pub(crate) fn pending_long_press(&self) -> Option<(TouchId, Duration)> {
945        let TouchGestureState::Pending {
946            touch,
947            deadline,
948            long_press_offered: false,
949            ..
950        } = &self.state
951        else {
952            return None;
953        };
954        Some((touch.id, deadline.saturating_duration_since(Instant::now())))
955    }
956
957    pub(crate) fn offer_long_press(&mut self, id: TouchId) -> Option<RecognizedTouchGesture> {
958        let TouchGestureState::Pending {
959            touch,
960            long_press_offered,
961            ..
962        } = &mut self.state
963        else {
964            return None;
965        };
966        if touch.id != id || *long_press_offered {
967            return None;
968        }
969        *long_press_offered = true;
970        Some(RecognizedTouchGesture::LongPress(LongPressEvent {
971            phase: TouchPhase::Started,
972            start_position: touch.start_position,
973            position: touch.last_position,
974        }))
975    }
976
977    pub(crate) fn resolve_long_press(&mut self, claimed: bool) {
978        if !claimed {
979            return;
980        }
981        let state = mem::replace(&mut self.state, TouchGestureState::Idle);
982        self.state = match state {
983            TouchGestureState::Pending {
984                touch,
985                long_press_offered: true,
986                ..
987            } => TouchGestureState::LongPressing(touch),
988            other => other,
989        };
990    }
991
992    pub(crate) fn offer_touch_drag(&mut self, id: TouchId) -> Option<RecognizedTouchGesture> {
993        let TouchGestureState::Pending {
994            touch,
995            touch_drag_offered,
996            ..
997        } = &mut self.state
998        else {
999            return None;
1000        };
1001        if touch.id != id || *touch_drag_offered {
1002            return None;
1003        }
1004        *touch_drag_offered = true;
1005        Some(RecognizedTouchGesture::TouchDrag(TouchDragEvent {
1006            phase: TouchPhase::Started,
1007            start_position: touch.start_position,
1008            position: touch.last_position,
1009        }))
1010    }
1011
1012    pub(crate) fn resolve_touch_drag(&mut self, claimed: bool) {
1013        if !claimed {
1014            return;
1015        }
1016        let state = mem::replace(&mut self.state, TouchGestureState::Idle);
1017        self.state = match state {
1018            TouchGestureState::Pending {
1019                touch,
1020                touch_drag_offered: true,
1021                ..
1022            } => TouchGestureState::TouchDragging(touch),
1023            other => other,
1024        };
1025    }
1026
1027    pub(crate) fn has_momentum(&self) -> bool {
1028        self.momentum.is_some()
1029    }
1030
1031    /// Advances post-fling momentum by one frame, returning the scroll step
1032    /// to dispatch, or `None` when no momentum is in progress. The final step
1033    /// carries [`TouchPhase::Ended`] to close the synthetic scroll stream.
1034    pub(crate) fn tick_momentum(&mut self) -> Option<RecognizedTouchGesture> {
1035        self.tick_momentum_at(Instant::now())
1036    }
1037
1038    fn tick_momentum_at(&mut self, now: Instant) -> Option<RecognizedTouchGesture> {
1039        let momentum = self.momentum.as_mut()?;
1040        let elapsed = now.duration_since(momentum.started_at);
1041        let distance = self
1042            .tuning
1043            .scroll_physics
1044            .fling_distance(momentum.speed, elapsed);
1045        // Prediction overshoot can start momentum ahead of its curve. Hold
1046        // that position until the curve catches up instead of stepping back.
1047        let step = (distance - momentum.emitted_distance).max(0.);
1048        momentum.emitted_distance = momentum.emitted_distance.max(distance);
1049        let delta = point(
1050            px(momentum.direction.x * step),
1051            px(momentum.direction.y * step),
1052        );
1053        let position = momentum.position;
1054        if elapsed >= momentum.duration {
1055            self.momentum = None;
1056            Some(RecognizedTouchGesture::Scroll(scroll_event(
1057                position,
1058                delta,
1059                TouchPhase::Ended,
1060            )))
1061        } else {
1062            Some(RecognizedTouchGesture::Scroll(scroll_event(
1063                position,
1064                delta,
1065                TouchPhase::Moved,
1066            )))
1067        }
1068    }
1069}
1070
1071fn scroll_event(
1072    position: Point<Pixels>,
1073    delta: Point<Pixels>,
1074    touch_phase: TouchPhase,
1075) -> ScrollEvent {
1076    ScrollEvent {
1077        position,
1078        delta: ScrollDelta::Pixels(delta),
1079        modifiers: Modifiers::default(),
1080        touch_phase,
1081        source: ScrollSource::Touch,
1082    }
1083}
1084
1085/// Estimates the velocity a touch had at its newest sample.
1086#[derive(Default)]
1087struct VelocityTracker {
1088    samples: VecDeque<(Instant, Point<Pixels>)>,
1089}
1090
1091impl VelocityTracker {
1092    fn push(&mut self, time: Instant, position: Point<Pixels>) {
1093        self.samples.push_back((time, position));
1094        while self.samples.len() > VELOCITY_MAX_SAMPLES {
1095            self.samples.pop_front();
1096        }
1097    }
1098
1099    fn latest_sample_time(&self) -> Option<Instant> {
1100        self.samples.back().map(|(time, _)| *time)
1101    }
1102
1103    /// The velocity at the newest sample, in pixels per second.
1104    ///
1105    /// Fits a second-degree polynomial by least squares over the trailing
1106    /// [`VELOCITY_WINDOW`] and takes its derivative at the newest sample,
1107    /// like Flutter's `VelocityTracker` and Android's `lsq2` strategy. An
1108    /// endpoint difference over the same window would report the window's
1109    /// *average* speed, which for a flick — still accelerating at lift-off —
1110    /// is roughly half the speed the finger actually had at release.
1111    fn velocity(&self) -> Point<f32> {
1112        let Some((newest_time, _)) = self.samples.back() else {
1113            return Point::default();
1114        };
1115        let mut times_seconds: SmallVec<[f64; VELOCITY_MAX_SAMPLES]> = SmallVec::new();
1116        let mut horizontal: SmallVec<[f64; VELOCITY_MAX_SAMPLES]> = SmallVec::new();
1117        let mut vertical: SmallVec<[f64; VELOCITY_MAX_SAMPLES]> = SmallVec::new();
1118        let mut previous_time = *newest_time;
1119        for (time, position) in self.samples.iter().rev() {
1120            let age = newest_time.duration_since(*time);
1121            if age > VELOCITY_WINDOW
1122                || previous_time.duration_since(*time) > VELOCITY_ASSUME_STOPPED_GAP
1123            {
1124                break;
1125            }
1126            previous_time = *time;
1127            times_seconds.push(-age.as_secs_f64());
1128            horizontal.push(f64::from(f32::from(position.x)));
1129            vertical.push(f64::from(f32::from(position.y)));
1130        }
1131
1132        let endpoint_estimate = |values: &[f64]| -> f32 {
1133            let elapsed = -times_seconds.last().copied().unwrap_or(0.);
1134            if elapsed <= f64::EPSILON {
1135                return 0.;
1136            }
1137            ((values.first().copied().unwrap_or(0.) - values.last().copied().unwrap_or(0.))
1138                / elapsed) as f32
1139        };
1140        if times_seconds.len() < 3 {
1141            return point(endpoint_estimate(&horizontal), endpoint_estimate(&vertical));
1142        }
1143        point(
1144            crate::fast::misc::touch_fling::release_velocity(
1145                endpoint_estimate(&horizontal),
1146                quadratic_velocity_at_newest(&times_seconds, &horizontal),
1147            ),
1148            crate::fast::misc::touch_fling::release_velocity(
1149                endpoint_estimate(&vertical),
1150                quadratic_velocity_at_newest(&times_seconds, &vertical),
1151            ),
1152        )
1153    }
1154}
1155
1156/// Least-squares fit of `value = a0 + a1·t + a2·t²` returning `a1`: the
1157/// fitted curve's velocity at `t = 0`, which callers place at the newest
1158/// sample. `None` when the samples are too degenerate to fit (all
1159/// simultaneous, for example).
1160fn quadratic_velocity_at_newest(times: &[f64], values: &[f64]) -> Option<f64> {
1161    let count = times.len() as f64;
1162    let (mut sum_t1, mut sum_t2, mut sum_t3, mut sum_t4) = (0., 0., 0., 0.);
1163    let (mut sum_v, mut sum_vt, mut sum_vt2) = (0., 0., 0.);
1164    for (&time, &value) in times.iter().zip(values) {
1165        let time_squared = time * time;
1166        sum_t1 += time;
1167        sum_t2 += time_squared;
1168        sum_t3 += time_squared * time;
1169        sum_t4 += time_squared * time_squared;
1170        sum_v += value;
1171        sum_vt += value * time;
1172        sum_vt2 += value * time_squared;
1173    }
1174    // Cramer's rule on the 3×3 normal equations, solved for the linear
1175    // coefficient only.
1176    let determinant = count * (sum_t2 * sum_t4 - sum_t3 * sum_t3)
1177        - sum_t1 * (sum_t1 * sum_t4 - sum_t3 * sum_t2)
1178        + sum_t2 * (sum_t1 * sum_t3 - sum_t2 * sum_t2);
1179    if determinant.abs() < 1e-12 {
1180        return None;
1181    }
1182    let linear_determinant = count * (sum_vt * sum_t4 - sum_t3 * sum_vt2)
1183        - sum_v * (sum_t1 * sum_t4 - sum_t3 * sum_t2)
1184        + sum_t2 * (sum_t1 * sum_vt2 - sum_vt * sum_t2);
1185    Some(linear_determinant / determinant)
1186}
1187
1188#[cfg(test)]
1189mod tests {
1190    use super::*;
1191    use crate::point;
1192
1193    #[test]
1194    fn ongoing_scroll_locks_to_dominant_axis() {
1195        let now = Instant::now();
1196        let mut ongoing_scroll = OngoingScroll::default();
1197        let mut horizontal_delta = point(px(10.), px(2.));
1198        ongoing_scroll.filter_at(&mut horizontal_delta, TouchPhase::Started, now);
1199        assert_eq!(ongoing_scroll.axis, Some(Axis::Horizontal));
1200        assert_eq!(horizontal_delta, point(px(10.), px(0.)));
1201
1202        let mut continued_delta = point(px(3.), px(2.));
1203        ongoing_scroll.filter_at(
1204            &mut continued_delta,
1205            TouchPhase::Moved,
1206            now + Duration::from_millis(1),
1207        );
1208        assert_eq!(ongoing_scroll.axis, Some(Axis::Horizontal));
1209        assert_eq!(continued_delta, point(px(3.), px(0.)));
1210    }
1211
1212    #[test]
1213    fn ongoing_scroll_unlocks_when_direction_changes() {
1214        let now = Instant::now();
1215        let mut ongoing_scroll = OngoingScroll::default();
1216        let mut horizontal_delta = point(px(10.), px(2.));
1217        ongoing_scroll.filter_at(&mut horizontal_delta, TouchPhase::Started, now);
1218
1219        let mut vertical_delta = point(px(2.), px(10.));
1220        ongoing_scroll.filter_at(
1221            &mut vertical_delta,
1222            TouchPhase::Moved,
1223            now + Duration::from_millis(1),
1224        );
1225        assert_eq!(ongoing_scroll.axis, None);
1226        assert_eq!(vertical_delta, point(px(2.), px(10.)));
1227    }
1228
1229    #[test]
1230    fn ongoing_scroll_starts_new_gesture_at_timeout_boundary() {
1231        let now = Instant::now();
1232        let mut ongoing_scroll = OngoingScroll::default();
1233        let mut horizontal_delta = point(px(10.), px(2.));
1234        ongoing_scroll.filter_at(&mut horizontal_delta, TouchPhase::Moved, now);
1235
1236        let mut vertical_delta = point(px(2.), px(10.));
1237        ongoing_scroll.filter_at(
1238            &mut vertical_delta,
1239            TouchPhase::Moved,
1240            now + SCROLL_EVENT_SEPARATION,
1241        );
1242        assert_eq!(ongoing_scroll.axis, Some(Axis::Vertical));
1243        assert_eq!(vertical_delta, point(px(0.), px(10.)));
1244    }
1245
1246    #[test]
1247    fn ongoing_scroll_ignores_zero_delta_and_resets_when_ended() {
1248        let now = Instant::now();
1249        let mut ongoing_scroll = OngoingScroll::default();
1250        let mut horizontal_delta = point(px(10.), px(2.));
1251        ongoing_scroll.filter_at(&mut horizontal_delta, TouchPhase::Started, now);
1252
1253        let mut zero_delta = Point::default();
1254        ongoing_scroll.filter_at(
1255            &mut zero_delta,
1256            TouchPhase::Ended,
1257            now + Duration::from_millis(1),
1258        );
1259        assert_eq!(ongoing_scroll.axis, None);
1260
1261        let mut vertical_delta = point(px(2.), px(3.));
1262        ongoing_scroll.filter_at(
1263            &mut vertical_delta,
1264            TouchPhase::Moved,
1265            now + Duration::from_millis(2),
1266        );
1267        assert_eq!(ongoing_scroll.axis, Some(Axis::Vertical));
1268        assert_eq!(vertical_delta, point(px(0.), px(3.)));
1269    }
1270
1271    #[test]
1272    fn ongoing_scroll_ignores_zero_delta_movement() {
1273        let now = Instant::now();
1274        let mut ongoing_scroll = OngoingScroll::default();
1275        let mut horizontal_delta = point(px(10.), px(2.));
1276        ongoing_scroll.filter_at(&mut horizontal_delta, TouchPhase::Started, now);
1277
1278        let mut zero_delta = Point::default();
1279        ongoing_scroll.filter_at(
1280            &mut zero_delta,
1281            TouchPhase::Moved,
1282            now + SCROLL_EVENT_SEPARATION,
1283        );
1284
1285        let mut vertical_delta = point(px(2.), px(10.));
1286        ongoing_scroll.filter_at(
1287            &mut vertical_delta,
1288            TouchPhase::Moved,
1289            now + SCROLL_EVENT_SEPARATION,
1290        );
1291        assert_eq!(ongoing_scroll.axis, Some(Axis::Vertical));
1292        assert_eq!(vertical_delta, point(px(0.), px(10.)));
1293    }
1294
1295    #[test]
1296    fn ongoing_scroll_supports_moved_only_platforms() {
1297        let now = Instant::now();
1298        let mut ongoing_scroll = OngoingScroll::default();
1299        let mut horizontal_delta = point(px(10.), px(2.));
1300        ongoing_scroll.filter_at(&mut horizontal_delta, TouchPhase::Moved, now);
1301        assert_eq!(ongoing_scroll.axis, Some(Axis::Horizontal));
1302        assert_eq!(horizontal_delta, point(px(10.), px(0.)));
1303    }
1304
1305    #[test]
1306    fn touch_within_slop_resolves_to_tap() {
1307        let mut recognizer = TouchGestureRecognizer::new(GestureTuning::default());
1308        let now = Instant::now();
1309        let touch = TouchId(1);
1310
1311        let recognized =
1312            recognizer.handle_event_at(&touch_event(touch, TouchPhase::Started, 10., 10.), now);
1313        assert!(recognized.is_empty());
1314        let recognized = recognizer.handle_event_at(
1315            &touch_event(touch, TouchPhase::Moved, 12., 11.),
1316            now + Duration::from_millis(20),
1317        );
1318        assert!(recognized.is_empty());
1319
1320        let recognized = recognizer.handle_event_at(
1321            &touch_event(touch, TouchPhase::Ended, 12., 11.),
1322            now + Duration::from_millis(60),
1323        );
1324        let [RecognizedTouchGesture::Tap { down, up }] = recognized.as_slice() else {
1325            panic!("expected tap, got {recognized:?}");
1326        };
1327        assert_eq!(down.click_count, 1);
1328        assert_eq!(down.position, point(px(12.), px(11.)));
1329        assert_eq!(up.click_count, 1);
1330    }
1331
1332    #[test]
1333    fn consecutive_taps_accumulate_tap_count() {
1334        let mut recognizer = TouchGestureRecognizer::new(GestureTuning::default());
1335        let now = Instant::now();
1336
1337        recognizer.handle_event_at(&touch_event(TouchId(1), TouchPhase::Started, 10., 10.), now);
1338        recognizer.handle_event_at(
1339            &touch_event(TouchId(1), TouchPhase::Ended, 10., 10.),
1340            now + Duration::from_millis(40),
1341        );
1342
1343        let second_down = now + Duration::from_millis(200);
1344        recognizer.handle_event_at(
1345            &touch_event(TouchId(2), TouchPhase::Started, 14., 10.),
1346            second_down,
1347        );
1348        let recognized = recognizer.handle_event_at(
1349            &touch_event(TouchId(2), TouchPhase::Ended, 14., 10.),
1350            second_down + Duration::from_millis(40),
1351        );
1352        let [RecognizedTouchGesture::Tap { down, .. }] = recognized.as_slice() else {
1353            panic!("expected tap, got {recognized:?}");
1354        };
1355        assert_eq!(down.click_count, 2);
1356
1357        let late_down = second_down + Duration::from_secs(2);
1358        recognizer.handle_event_at(
1359            &touch_event(TouchId(3), TouchPhase::Started, 14., 10.),
1360            late_down,
1361        );
1362        let recognized = recognizer.handle_event_at(
1363            &touch_event(TouchId(3), TouchPhase::Ended, 14., 10.),
1364            late_down + Duration::from_millis(40),
1365        );
1366        let [RecognizedTouchGesture::Tap { down, .. }] = recognized.as_slice() else {
1367            panic!("expected tap, got {recognized:?}");
1368        };
1369        assert_eq!(down.click_count, 1);
1370    }
1371
1372    #[test]
1373    fn touch_beyond_slop_resolves_to_pan() {
1374        let mut recognizer = TouchGestureRecognizer::new(GestureTuning::default());
1375        let now = Instant::now();
1376        let touch = TouchId(1);
1377
1378        recognizer.handle_event_at(&touch_event(touch, TouchPhase::Started, 100., 100.), now);
1379
1380        let recognized = recognizer.handle_event_at(
1381            &touch_event(touch, TouchPhase::Moved, 100., 120.),
1382            now + Duration::from_millis(16),
1383        );
1384        let [RecognizedTouchGesture::Scroll(scroll)] = recognized.as_slice() else {
1385            panic!("expected scroll, got {recognized:?}");
1386        };
1387        assert_eq!(scroll.touch_phase, TouchPhase::Started);
1388        assert_eq!(scroll.position, point(px(100.), px(100.)));
1389        assert_eq!(scroll.delta.pixel_delta(px(16.)), point(px(0.), px(20.)));
1390
1391        let recognized = recognizer.handle_event_at(
1392            &touch_event(touch, TouchPhase::Moved, 100., 135.),
1393            now + Duration::from_millis(32),
1394        );
1395        let [RecognizedTouchGesture::Scroll(scroll)] = recognized.as_slice() else {
1396            panic!("expected scroll, got {recognized:?}");
1397        };
1398        assert_eq!(scroll.touch_phase, TouchPhase::Moved);
1399        assert_eq!(scroll.position, point(px(100.), px(100.)));
1400        assert_eq!(scroll.delta.pixel_delta(px(16.)), point(px(0.), px(15.)));
1401
1402        let recognized = recognizer.handle_event_at(
1403            &touch_event(touch, TouchPhase::Ended, 100., 135.),
1404            now + Duration::from_millis(48),
1405        );
1406        let [RecognizedTouchGesture::Scroll(scroll)] = recognized.as_slice() else {
1407            panic!("expected scroll, got {recognized:?}");
1408        };
1409        assert_eq!(scroll.touch_phase, TouchPhase::Ended);
1410    }
1411
1412    #[test]
1413    fn touch_pan_stays_locked_to_its_initial_dominant_axis() {
1414        let mut recognizer = TouchGestureRecognizer::new(GestureTuning::default());
1415        let now = Instant::now();
1416        let touch = TouchId(1);
1417
1418        recognizer.handle_event_at(&touch_event(touch, TouchPhase::Started, 100., 100.), now);
1419
1420        let recognized = recognizer.handle_event_at(
1421            &touch_event(touch, TouchPhase::Moved, 104., 120.),
1422            now + Duration::from_millis(16),
1423        );
1424        let [RecognizedTouchGesture::Scroll(scroll)] = recognized.as_slice() else {
1425            panic!("expected scroll, got {recognized:?}");
1426        };
1427        assert_eq!(scroll.delta.pixel_delta(px(16.)), point(px(0.), px(20.)));
1428
1429        let recognized = recognizer.handle_event_at(
1430            &touch_event(touch, TouchPhase::Moved, 134., 125.),
1431            now + Duration::from_millis(32),
1432        );
1433        let [RecognizedTouchGesture::Scroll(scroll)] = recognized.as_slice() else {
1434            panic!("expected scroll, got {recognized:?}");
1435        };
1436        assert_eq!(scroll.delta.pixel_delta(px(16.)), point(px(0.), px(5.)));
1437    }
1438
1439    #[test]
1440    fn touch_pan_locks_to_horizontal_axis() {
1441        let mut recognizer = TouchGestureRecognizer::new(GestureTuning::default());
1442        let now = Instant::now();
1443        let touch = TouchId(1);
1444
1445        recognizer.handle_event_at(&touch_event(touch, TouchPhase::Started, 100., 100.), now);
1446
1447        let recognized = recognizer.handle_event_at(
1448            &touch_event(touch, TouchPhase::Moved, 120., 104.),
1449            now + Duration::from_millis(16),
1450        );
1451        let [RecognizedTouchGesture::Scroll(scroll)] = recognized.as_slice() else {
1452            panic!("expected scroll, got {recognized:?}");
1453        };
1454        assert_eq!(scroll.delta.pixel_delta(px(16.)), point(px(20.), px(0.)));
1455    }
1456
1457    #[test]
1458    fn predicted_positions_lead_the_pan_but_totals_converge_on_release() {
1459        let mut recognizer = TouchGestureRecognizer::new(GestureTuning::default());
1460        let now = Instant::now();
1461        let touch = TouchId(1);
1462
1463        recognizer.handle_event_at(&touch_event(touch, TouchPhase::Started, 100., 100.), now);
1464
1465        // The first pan step scrolls to the predicted position, not the raw one.
1466        let mut moved = touch_event(touch, TouchPhase::Moved, 100., 120.);
1467        moved.predicted_position = Some(point(px(106.), px(128.)));
1468        let recognized = recognizer.handle_event_at(&moved, now + Duration::from_millis(16));
1469        let [RecognizedTouchGesture::Scroll(scroll)] = recognized.as_slice() else {
1470            panic!("expected scroll, got {recognized:?}");
1471        };
1472        assert_eq!(scroll.delta.pixel_delta(px(16.)), point(px(0.), px(28.)));
1473
1474        // The next step is measured from where the previous prediction left
1475        // the content, so an overshoot is paid back here.
1476        let mut moved = touch_event(touch, TouchPhase::Moved, 100., 130.);
1477        moved.predicted_position = Some(point(px(104.), px(134.)));
1478        let recognized = recognizer.handle_event_at(&moved, now + Duration::from_millis(32));
1479        let [RecognizedTouchGesture::Scroll(scroll)] = recognized.as_slice() else {
1480            panic!("expected scroll, got {recognized:?}");
1481        };
1482        assert_eq!(scroll.delta.pixel_delta(px(16.)), point(px(0.), px(6.)));
1483
1484        // A release without a fling (the finger stopped long before lifting)
1485        // targets the raw position: the total scrolled distance equals the
1486        // finger's actual travel despite the predictions.
1487        let recognized = recognizer.handle_event_at(
1488            &touch_event(touch, TouchPhase::Ended, 100., 130.),
1489            now + Duration::from_millis(120),
1490        );
1491        let [RecognizedTouchGesture::Scroll(scroll)] = recognized.as_slice() else {
1492            panic!("expected scroll, got {recognized:?}");
1493        };
1494        assert_eq!(scroll.touch_phase, TouchPhase::Ended);
1495        assert!(!recognizer.has_momentum());
1496        assert_eq!(scroll.delta.pixel_delta(px(16.)), point(px(0.), px(-4.)));
1497    }
1498
1499    #[test]
1500    fn predicted_positions_do_not_emit_false_reversals() {
1501        let mut recognizer = TouchGestureRecognizer::new(GestureTuning::default());
1502        let now = Instant::now();
1503        let touch = TouchId(1);
1504
1505        recognizer.handle_event_at(&touch_event(touch, TouchPhase::Started, 100., 100.), now);
1506
1507        let mut moved = touch_event(touch, TouchPhase::Moved, 100., 120.);
1508        moved.predicted_position = Some(point(px(100.), px(130.)));
1509        let recognized = recognizer.handle_event_at(&moved, now + Duration::from_millis(16));
1510        let [RecognizedTouchGesture::Scroll(scroll)] = recognized.as_slice() else {
1511            panic!("expected scroll, got {recognized:?}");
1512        };
1513        assert_eq!(scroll.delta.pixel_delta(px(16.)), point(px(0.), px(30.)));
1514
1515        let mut moved = touch_event(touch, TouchPhase::Moved, 100., 125.);
1516        moved.predicted_position = Some(point(px(100.), px(127.)));
1517        let recognized = recognizer.handle_event_at(&moved, now + Duration::from_millis(32));
1518        let [RecognizedTouchGesture::Scroll(scroll)] = recognized.as_slice() else {
1519            panic!("expected scroll, got {recognized:?}");
1520        };
1521        assert_eq!(
1522            scroll.delta.pixel_delta(px(16.)),
1523            Point::<Pixels>::default()
1524        );
1525
1526        let mut moved = touch_event(touch, TouchPhase::Moved, 100., 125.);
1527        moved.predicted_position = Some(point(px(100.), px(126.)));
1528        let recognized = recognizer.handle_event_at(&moved, now + Duration::from_millis(40));
1529        let [RecognizedTouchGesture::Scroll(scroll)] = recognized.as_slice() else {
1530            panic!("expected scroll, got {recognized:?}");
1531        };
1532        assert_eq!(
1533            scroll.delta.pixel_delta(px(16.)),
1534            Point::<Pixels>::default()
1535        );
1536
1537        let mut moved = touch_event(touch, TouchPhase::Moved, 100., 132.);
1538        moved.predicted_position = Some(point(px(100.), px(136.)));
1539        let recognized = recognizer.handle_event_at(&moved, now + Duration::from_millis(48));
1540        let [RecognizedTouchGesture::Scroll(scroll)] = recognized.as_slice() else {
1541            panic!("expected scroll, got {recognized:?}");
1542        };
1543        assert_eq!(scroll.delta.pixel_delta(px(16.)), point(px(0.), px(6.)));
1544
1545        let mut moved = touch_event(touch, TouchPhase::Moved, 100., 124.);
1546        moved.predicted_position = Some(point(px(100.), px(140.)));
1547        let recognized = recognizer.handle_event_at(&moved, now + Duration::from_millis(64));
1548        let [RecognizedTouchGesture::Scroll(scroll)] = recognized.as_slice() else {
1549            panic!("expected scroll, got {recognized:?}");
1550        };
1551        assert_eq!(scroll.delta.pixel_delta(px(16.)), point(px(0.), px(-12.)));
1552    }
1553
1554    #[test]
1555    fn predicted_overshoot_folds_into_the_fling_without_scrolling_backwards() {
1556        let now = Instant::now();
1557        let mut total_with_prediction = 0f32;
1558        let mut total_without_prediction = 0f32;
1559        for use_prediction in [true, false] {
1560            let mut recognizer = TouchGestureRecognizer::new(GestureTuning::default());
1561            let mut total = 0f32;
1562            let mut drain = |recognized: &[RecognizedTouchGesture], upward_only: bool| {
1563                for gesture in recognized {
1564                    let RecognizedTouchGesture::Scroll(scroll) = gesture else {
1565                        panic!("expected scroll, got {gesture:?}");
1566                    };
1567                    let delta = scroll.delta.pixel_delta(px(16.)).y;
1568                    if upward_only {
1569                        assert!(
1570                            delta <= px(0.),
1571                            "content moved backwards by {delta:?} during an upward gesture"
1572                        );
1573                    }
1574                    total += f32::from(delta);
1575                }
1576            };
1577
1578            recognizer.handle_event_at(
1579                &touch_event(TouchId(1), TouchPhase::Started, 100., 500.),
1580                now,
1581            );
1582            for step in 1..=5u64 {
1583                let raw_y = 500. - step as f32 * 40.;
1584                let mut moved = touch_event(TouchId(1), TouchPhase::Moved, 100., raw_y);
1585                if use_prediction {
1586                    moved.predicted_position = Some(point(px(100.), px(raw_y - 25.)));
1587                }
1588                let recognized =
1589                    recognizer.handle_event_at(&moved, now + Duration::from_millis(step * 16));
1590                drain(&recognized, use_prediction);
1591            }
1592            // The release leaves the emitted position 25px ahead of the raw
1593            // one; with prediction the correction must not scroll backwards.
1594            let recognized = recognizer.handle_event_at(
1595                &touch_event(TouchId(1), TouchPhase::Ended, 100., 300.),
1596                now + Duration::from_millis(90),
1597            );
1598            drain(&recognized, use_prediction);
1599            assert!(recognizer.has_momentum());
1600            let mut tick = now + Duration::from_millis(91);
1601            while recognizer.has_momentum() {
1602                if let Some(gesture) = recognizer.tick_momentum_at(tick) {
1603                    drain(&[gesture], use_prediction);
1604                }
1605                tick += Duration::from_millis(16);
1606            }
1607
1608            if use_prediction {
1609                total_with_prediction = total;
1610            } else {
1611                total_without_prediction = total;
1612            }
1613        }
1614        // Folding the overshoot into the fling redistributes the travel but
1615        // must not change where the content comes to rest.
1616        assert!(
1617            (total_with_prediction - total_without_prediction).abs() < 0.01,
1618            "totals diverged: {total_with_prediction} vs {total_without_prediction}"
1619        );
1620    }
1621
1622    #[test]
1623    fn fast_release_starts_momentum_that_decays_to_a_stop() {
1624        let mut recognizer = TouchGestureRecognizer::new(GestureTuning::default());
1625        let now = Instant::now();
1626        let touch = TouchId(1);
1627
1628        recognizer.handle_event_at(&touch_event(touch, TouchPhase::Started, 100., 300.), now);
1629        for step in 1..=5 {
1630            recognizer.handle_event_at(
1631                &touch_event(touch, TouchPhase::Moved, 100., 300. - step as f32 * 20.),
1632                now + Duration::from_millis(step * 16),
1633            );
1634        }
1635        recognizer.handle_event_at(
1636            &touch_event(touch, TouchPhase::Ended, 100., 200.),
1637            now + Duration::from_millis(6 * 16),
1638        );
1639        assert!(recognizer.has_momentum());
1640
1641        let tick = now + Duration::from_millis(6 * 16 + 16);
1642        let recognized = recognizer.tick_momentum_at(tick);
1643        let Some(RecognizedTouchGesture::Scroll(scroll)) = recognized else {
1644            panic!("expected momentum scroll, got {recognized:?}");
1645        };
1646        assert_eq!(scroll.touch_phase, TouchPhase::Moved);
1647        assert_eq!(scroll.position, point(px(100.), px(300.)));
1648        let delta = scroll.delta.pixel_delta(px(16.));
1649        assert!(
1650            delta.y < px(0.),
1651            "momentum should continue upward, got {delta:?}"
1652        );
1653        // The least-squares fit may leave float residue on the motionless axis.
1654        assert!(
1655            delta.x.abs() < px(0.001),
1656            "expected no x motion, got {delta:?}"
1657        );
1658
1659        let mut last_phase = TouchPhase::Moved;
1660        let mut ticks = 0;
1661        let mut time = tick;
1662        while recognizer.has_momentum() {
1663            time += Duration::from_millis(16);
1664            ticks += 1;
1665            assert!(ticks < 1000, "momentum never stopped");
1666            if let Some(RecognizedTouchGesture::Scroll(scroll)) = recognizer.tick_momentum_at(time)
1667            {
1668                last_phase = scroll.touch_phase;
1669            }
1670        }
1671        assert_eq!(last_phase, TouchPhase::Ended);
1672        assert!(recognizer.tick_momentum_at(time).is_none());
1673    }
1674
1675    #[test]
1676    fn diagonal_release_flings_only_on_locked_axis() {
1677        let mut recognizer = TouchGestureRecognizer::new(GestureTuning::default());
1678        let now = Instant::now();
1679        let touch = TouchId(1);
1680
1681        recognizer.handle_event_at(&touch_event(touch, TouchPhase::Started, 100., 300.), now);
1682        for step in 1..=5 {
1683            let recognized = recognizer.handle_event_at(
1684                &touch_event(
1685                    touch,
1686                    TouchPhase::Moved,
1687                    100. + step as f32 * 3.,
1688                    300. - step as f32 * 20.,
1689                ),
1690                now + Duration::from_millis(step * 16),
1691            );
1692            let [RecognizedTouchGesture::Scroll(scroll)] = recognized.as_slice() else {
1693                panic!("expected scroll, got {recognized:?}");
1694            };
1695            assert_eq!(scroll.delta.pixel_delta(px(16.)).x, px(0.));
1696        }
1697        recognizer.handle_event_at(
1698            &touch_event(touch, TouchPhase::Ended, 115., 200.),
1699            now + Duration::from_millis(6 * 16),
1700        );
1701        assert!(recognizer.has_momentum());
1702
1703        let mut time = now + Duration::from_millis(6 * 16);
1704        while recognizer.has_momentum() {
1705            time += Duration::from_millis(16);
1706            if let Some(RecognizedTouchGesture::Scroll(scroll)) = recognizer.tick_momentum_at(time)
1707            {
1708                let delta = scroll.delta.pixel_delta(px(16.));
1709                assert_eq!(delta.x, px(0.));
1710                assert!(delta.y <= px(0.));
1711            }
1712        }
1713    }
1714
1715    #[test]
1716    fn slow_release_does_not_start_momentum() {
1717        let mut recognizer = TouchGestureRecognizer::new(GestureTuning::default());
1718        let now = Instant::now();
1719        let touch = TouchId(1);
1720
1721        recognizer.handle_event_at(&touch_event(touch, TouchPhase::Started, 100., 300.), now);
1722        recognizer.handle_event_at(
1723            &touch_event(touch, TouchPhase::Moved, 100., 280.),
1724            now + Duration::from_millis(16),
1725        );
1726        recognizer.handle_event_at(
1727            &touch_event(touch, TouchPhase::Moved, 100., 279.),
1728            now + Duration::from_millis(500),
1729        );
1730        recognizer.handle_event_at(
1731            &touch_event(touch, TouchPhase::Ended, 100., 279.),
1732            now + Duration::from_millis(600),
1733        );
1734        assert!(!recognizer.has_momentum());
1735    }
1736
1737    #[test]
1738    fn new_touch_interrupts_momentum() {
1739        let mut recognizer = TouchGestureRecognizer::new(GestureTuning::default());
1740        let now = Instant::now();
1741
1742        recognizer.handle_event_at(
1743            &touch_event(TouchId(1), TouchPhase::Started, 100., 300.),
1744            now,
1745        );
1746        for step in 1..=3 {
1747            recognizer.handle_event_at(
1748                &touch_event(
1749                    TouchId(1),
1750                    TouchPhase::Moved,
1751                    100.,
1752                    300. - step as f32 * 33.,
1753                ),
1754                now + Duration::from_millis(step * 16),
1755            );
1756        }
1757        recognizer.handle_event_at(
1758            &touch_event(TouchId(1), TouchPhase::Ended, 100., 200.),
1759            now + Duration::from_millis(64),
1760        );
1761        assert!(recognizer.has_momentum());
1762
1763        let recognized = recognizer.handle_event_at(
1764            &touch_event(TouchId(2), TouchPhase::Started, 100., 200.),
1765            now + Duration::from_millis(200),
1766        );
1767        assert!(!recognizer.has_momentum());
1768        let [
1769            RecognizedTouchGesture::Scroll(closing),
1770            RecognizedTouchGesture::Scroll(opening),
1771        ] = recognized.as_slice()
1772        else {
1773            panic!("expected closing and opening scrolls, got {recognized:?}");
1774        };
1775        assert_eq!(closing.touch_phase, TouchPhase::Ended);
1776        assert!(closing.delta.pixel_delta(px(16.)).is_zero());
1777        assert_eq!(opening.touch_phase, TouchPhase::Started);
1778        assert!(opening.delta.pixel_delta(px(16.)).is_zero());
1779    }
1780
1781    #[test]
1782    fn catching_a_fling_pans_immediately_and_never_taps() {
1783        let mut recognizer = TouchGestureRecognizer::new(GestureTuning::default());
1784        let now = Instant::now();
1785
1786        recognizer.handle_event_at(
1787            &touch_event(TouchId(1), TouchPhase::Started, 100., 300.),
1788            now,
1789        );
1790        for step in 1..=3 {
1791            recognizer.handle_event_at(
1792                &touch_event(
1793                    TouchId(1),
1794                    TouchPhase::Moved,
1795                    100.,
1796                    300. - step as f32 * 33.,
1797                ),
1798                now + Duration::from_millis(step * 16),
1799            );
1800        }
1801        recognizer.handle_event_at(
1802            &touch_event(TouchId(1), TouchPhase::Ended, 100., 200.),
1803            now + Duration::from_millis(64),
1804        );
1805        assert!(recognizer.has_momentum());
1806
1807        recognizer.handle_event_at(
1808            &touch_event(TouchId(2), TouchPhase::Started, 100., 200.),
1809            now + Duration::from_millis(200),
1810        );
1811
1812        // A movement well within the slop scrolls immediately.
1813        let recognized = recognizer.handle_event_at(
1814            &touch_event(TouchId(2), TouchPhase::Moved, 100., 197.),
1815            now + Duration::from_millis(216),
1816        );
1817        let [RecognizedTouchGesture::Scroll(scroll)] = recognized.as_slice() else {
1818            panic!("expected scroll, got {recognized:?}");
1819        };
1820        assert_eq!(scroll.touch_phase, TouchPhase::Moved);
1821        assert_eq!(scroll.delta.pixel_delta(px(16.)), point(px(0.), px(-3.)));
1822
1823        // Releasing the catch is not a tap.
1824        let recognized = recognizer.handle_event_at(
1825            &touch_event(TouchId(2), TouchPhase::Ended, 100., 197.),
1826            now + Duration::from_millis(232),
1827        );
1828        let [RecognizedTouchGesture::Scroll(scroll)] = recognized.as_slice() else {
1829            panic!("expected scroll, got {recognized:?}");
1830        };
1831        assert_eq!(scroll.touch_phase, TouchPhase::Ended);
1832    }
1833
1834    #[test]
1835    fn catching_a_fling_takes_the_axis_from_the_new_touch() {
1836        let mut recognizer = TouchGestureRecognizer::new(GestureTuning::default());
1837        let now = Instant::now();
1838
1839        // A fast horizontal pan flings sideways.
1840        recognizer.handle_event_at(
1841            &touch_event(TouchId(1), TouchPhase::Started, 300., 300.),
1842            now,
1843        );
1844        for step in 1..=3 {
1845            recognizer.handle_event_at(
1846                &touch_event(
1847                    TouchId(1),
1848                    TouchPhase::Moved,
1849                    300. - step as f32 * 33.,
1850                    300.,
1851                ),
1852                now + Duration::from_millis(step * 16),
1853            );
1854        }
1855        recognizer.handle_event_at(
1856            &touch_event(TouchId(1), TouchPhase::Ended, 200., 300.),
1857            now + Duration::from_millis(64),
1858        );
1859        assert!(recognizer.has_momentum());
1860
1861        // A finger that catches it and moves up scrolls up: the fling's axis
1862        // is not this touch's axis.
1863        recognizer.handle_event_at(
1864            &touch_event(TouchId(2), TouchPhase::Started, 200., 300.),
1865            now + Duration::from_millis(200),
1866        );
1867        let recognized = recognizer.handle_event_at(
1868            &touch_event(TouchId(2), TouchPhase::Moved, 201., 280.),
1869            now + Duration::from_millis(216),
1870        );
1871        let [RecognizedTouchGesture::Scroll(scroll)] = recognized.as_slice() else {
1872            panic!("expected scroll, got {recognized:?}");
1873        };
1874        assert_eq!(scroll.touch_phase, TouchPhase::Moved);
1875        assert_eq!(scroll.delta.pixel_delta(px(16.)), point(px(0.), px(-20.)));
1876
1877        // And stays on that axis for the rest of the pan.
1878        let recognized = recognizer.handle_event_at(
1879            &touch_event(TouchId(2), TouchPhase::Moved, 205., 260.),
1880            now + Duration::from_millis(232),
1881        );
1882        let [RecognizedTouchGesture::Scroll(scroll)] = recognized.as_slice() else {
1883            panic!("expected scroll, got {recognized:?}");
1884        };
1885        assert_eq!(scroll.delta.pixel_delta(px(16.)), point(px(0.), px(-20.)));
1886    }
1887
1888    #[test]
1889    fn cancelled_pan_emits_cancelled_scroll_and_no_tap() {
1890        let mut recognizer = TouchGestureRecognizer::new(GestureTuning::default());
1891        let now = Instant::now();
1892        let touch = TouchId(1);
1893
1894        recognizer.handle_event_at(&touch_event(touch, TouchPhase::Started, 100., 100.), now);
1895        recognizer.handle_event_at(
1896            &touch_event(touch, TouchPhase::Moved, 100., 150.),
1897            now + Duration::from_millis(16),
1898        );
1899        let recognized = recognizer.handle_event_at(
1900            &touch_event(touch, TouchPhase::Cancelled, 100., 150.),
1901            now + Duration::from_millis(32),
1902        );
1903        let [RecognizedTouchGesture::Scroll(scroll)] = recognized.as_slice() else {
1904            panic!("expected cancelled scroll, got {recognized:?}");
1905        };
1906        assert_eq!(scroll.touch_phase, TouchPhase::Cancelled);
1907        assert!(!recognizer.has_momentum());
1908
1909        let mut recognizer = TouchGestureRecognizer::new(GestureTuning::default());
1910        recognizer.handle_event_at(&touch_event(touch, TouchPhase::Started, 100., 100.), now);
1911        let recognized = recognizer.handle_event_at(
1912            &touch_event(touch, TouchPhase::Cancelled, 100., 102.),
1913            now + Duration::from_millis(16),
1914        );
1915        assert!(recognized.is_empty(), "cancelled tap must not click");
1916    }
1917
1918    #[test]
1919    fn concurrent_touches_are_ignored_while_one_is_active() {
1920        let mut recognizer = TouchGestureRecognizer::new(GestureTuning::default());
1921        let now = Instant::now();
1922
1923        recognizer.handle_event_at(
1924            &touch_event(TouchId(1), TouchPhase::Started, 100., 100.),
1925            now,
1926        );
1927        let recognized = recognizer.handle_event_at(
1928            &touch_event(TouchId(2), TouchPhase::Started, 200., 200.),
1929            now + Duration::from_millis(8),
1930        );
1931        assert!(recognized.is_empty());
1932        let recognized = recognizer.handle_event_at(
1933            &touch_event(TouchId(2), TouchPhase::Moved, 200., 300.),
1934            now + Duration::from_millis(16),
1935        );
1936        assert!(recognized.is_empty());
1937        let recognized = recognizer.handle_event_at(
1938            &touch_event(TouchId(2), TouchPhase::Ended, 200., 300.),
1939            now + Duration::from_millis(24),
1940        );
1941        assert!(recognized.is_empty());
1942
1943        // The first touch still resolves normally.
1944        let recognized = recognizer.handle_event_at(
1945            &touch_event(TouchId(1), TouchPhase::Moved, 100., 150.),
1946            now + Duration::from_millis(32),
1947        );
1948        let [RecognizedTouchGesture::Scroll(scroll)] = recognized.as_slice() else {
1949            panic!("expected scroll, got {recognized:?}");
1950        };
1951        assert_eq!(scroll.touch_phase, TouchPhase::Started);
1952    }
1953
1954    #[test]
1955    fn spline_position_table_matches_the_bezier_curve() {
1956        let samples = friction_spline::spline_position_samples();
1957        // AOSP's initializer solves sample 0 numerically like every other
1958        // sample, so it lands within solver tolerance of zero, not at zero.
1959        assert!(samples[0].abs() < 1e-4);
1960        assert_eq!(samples[100], 1.);
1961        for window in samples.windows(2) {
1962            assert!(window[0] < window[1], "table must be strictly increasing");
1963        }
1964        // Each table entry must lie on the defining parametric Bezier: for
1965        // sample i there must be a curve parameter whose time component is
1966        // i/100 and whose position component is the stored value.
1967        for (i, &stored_position) in samples.iter().enumerate().take(100) {
1968            let alpha = i as f32 / 100.;
1969            let (mut lower, mut upper) = (0f32, 1f32);
1970            for _ in 0..50 {
1971                let middle = (lower + upper) / 2.;
1972                let (time, _) = friction_spline::bezier_time_and_position(middle);
1973                if time > alpha {
1974                    upper = middle;
1975                } else {
1976                    lower = middle;
1977                }
1978            }
1979            let (time, position) = friction_spline::bezier_time_and_position((lower + upper) / 2.);
1980            assert!(
1981                (time - alpha).abs() < 1e-4,
1982                "sample {i}: time {time} != {alpha}"
1983            );
1984            assert!(
1985                (position - stored_position).abs() < 1e-3,
1986                "sample {i}: position {position} != stored {stored_position}"
1987            );
1988        }
1989    }
1990
1991    #[test]
1992    fn fling_curves_are_sane_for_both_physics() {
1993        for physics in [ScrollPhysics::ios(), ScrollPhysics::android()] {
1994            let slow = physics.fling_duration(500.);
1995            let fast = physics.fling_duration(4000.);
1996            assert!(slow > Duration::ZERO, "{physics:?}");
1997            assert!(fast > slow, "faster flings must coast longer: {physics:?}");
1998
1999            let halfway = physics.fling_distance(4000., fast / 2);
2000            let total = physics.fling_distance(4000., fast);
2001            assert!(halfway > 0. && halfway < total, "{physics:?}");
2002            assert!(
2003                physics.fling_distance(4000., fast * 2) == total,
2004                "distance must not grow past the fling duration: {physics:?}"
2005            );
2006            assert!(
2007                physics.fling_distance(4000., fast) > physics.fling_distance(500., slow),
2008                "faster flings must travel further: {physics:?}"
2009            );
2010        }
2011    }
2012
2013    #[test]
2014    fn momentum_is_frame_rate_independent() {
2015        // The same fling ticked at 60Hz and as one huge stalled frame must
2016        // cover identical ground.
2017        let total_distance_with_tick_length = |tick: Duration| -> f32 {
2018            let mut recognizer = TouchGestureRecognizer::new(GestureTuning {
2019                scroll_physics: ScrollPhysics::android(),
2020                ..GestureTuning::default()
2021            });
2022            let now = Instant::now();
2023            recognizer.handle_event_at(
2024                &touch_event(TouchId(1), TouchPhase::Started, 100., 500.),
2025                now,
2026            );
2027            for step in 1..=3 {
2028                recognizer.handle_event_at(
2029                    &touch_event(
2030                        TouchId(1),
2031                        TouchPhase::Moved,
2032                        100.,
2033                        500. - step as f32 * 40.,
2034                    ),
2035                    now + Duration::from_millis(step * 16),
2036                );
2037            }
2038            recognizer.handle_event_at(
2039                &touch_event(TouchId(1), TouchPhase::Ended, 100., 380.),
2040                now + Duration::from_millis(64),
2041            );
2042            assert!(recognizer.has_momentum());
2043
2044            let mut total = 0f32;
2045            let mut time = now + Duration::from_millis(64);
2046            let mut guard = 0;
2047            while recognizer.has_momentum() {
2048                time += tick;
2049                guard += 1;
2050                assert!(guard < 10_000, "momentum never stopped");
2051                if let Some(RecognizedTouchGesture::Scroll(scroll)) =
2052                    recognizer.tick_momentum_at(time)
2053                {
2054                    total += f32::from(scroll.delta.pixel_delta(px(16.)).y);
2055                }
2056            }
2057            total
2058        };
2059
2060        let smooth = total_distance_with_tick_length(Duration::from_millis(16));
2061        let stalled = total_distance_with_tick_length(Duration::from_secs(10));
2062        assert!(
2063            (smooth - stalled).abs() < 0.01,
2064            "expected identical fling distance, got {smooth} vs {stalled}"
2065        );
2066    }
2067
2068    #[test]
2069    fn flick_velocity_reflects_release_speed_not_window_average() {
2070        // A uniformly accelerating flick: position grows quadratically, so
2071        // the speed at the newest sample (2·k·t) is twice the window
2072        // average (k·t). The estimator must report the former.
2073        let mut velocity_tracker = VelocityTracker::default();
2074        let start = Instant::now();
2075        for step in 0..=6 {
2076            let t = step as f32 * 0.016;
2077            velocity_tracker.push(
2078                start + Duration::from_millis(step * 16),
2079                point(px(0.), px(1000. * t * t)),
2080            );
2081        }
2082        let velocity = velocity_tracker.velocity();
2083        let release_speed = 2. * 1000. * 0.096;
2084        assert!(
2085            (velocity.y - release_speed).abs() < 1.,
2086            "expected ≈{release_speed} px/s at release, got {} px/s",
2087            velocity.y
2088        );
2089        assert_eq!(velocity.x, 0.);
2090    }
2091
2092    #[test]
2093    fn samples_before_a_pause_do_not_contribute_velocity() {
2094        // Fast motion, then a hold longer than the stopped-finger gap, then
2095        // a slow nudge: only the motion after the pause describes the
2096        // release.
2097        let mut velocity_tracker = VelocityTracker::default();
2098        let start = Instant::now();
2099        velocity_tracker.push(start, point(px(0.), px(0.)));
2100        velocity_tracker.push(start + Duration::from_millis(16), point(px(0.), px(50.)));
2101        velocity_tracker.push(start + Duration::from_millis(80), point(px(0.), px(52.)));
2102        velocity_tracker.push(start + Duration::from_millis(96), point(px(0.), px(54.)));
2103        let velocity = velocity_tracker.velocity();
2104        assert!(
2105            velocity.y < 200.,
2106            "pre-pause motion leaked into the estimate: {} px/s",
2107            velocity.y
2108        );
2109    }
2110
2111    #[test]
2112    fn claimed_touch_drag_emits_phased_stream_without_pan_or_tap() {
2113        let mut recognizer = TouchGestureRecognizer::new(GestureTuning::default());
2114        let touch = TouchId(1);
2115        let now = Instant::now();
2116        recognizer.handle_event_at(&touch_event(touch, TouchPhase::Started, 10., 20.), now);
2117        let Some(RecognizedTouchGesture::TouchDrag(started)) = recognizer.offer_touch_drag(touch)
2118        else {
2119            panic!("expected touch drag");
2120        };
2121        assert_eq!(started.phase, TouchPhase::Started);
2122        assert_eq!(started.start_position, point(px(10.), px(20.)));
2123        recognizer.resolve_touch_drag(true);
2124
2125        let moved = recognizer.handle_event_at(
2126            &touch_event(touch, TouchPhase::Moved, 40., 50.),
2127            now + Duration::from_millis(10),
2128        );
2129        let [RecognizedTouchGesture::TouchDrag(moved)] = moved.as_slice() else {
2130            panic!("expected moved touch drag, got {moved:?}");
2131        };
2132        assert_eq!(moved.phase, TouchPhase::Moved);
2133        assert_eq!(moved.position, point(px(40.), px(50.)));
2134
2135        let ended = recognizer.handle_event_at(
2136            &touch_event(touch, TouchPhase::Ended, 45., 55.),
2137            now + Duration::from_millis(20),
2138        );
2139        let [RecognizedTouchGesture::TouchDrag(ended)] = ended.as_slice() else {
2140            panic!("expected ended touch drag, got {ended:?}");
2141        };
2142        assert_eq!(ended.phase, TouchPhase::Ended);
2143        assert_eq!(ended.position, point(px(45.), px(55.)));
2144    }
2145
2146    #[test]
2147    fn unclaimed_touch_drag_remains_a_pan_candidate() {
2148        let mut recognizer = TouchGestureRecognizer::new(GestureTuning::default());
2149        let touch = TouchId(1);
2150        let now = Instant::now();
2151        recognizer.handle_event_at(&touch_event(touch, TouchPhase::Started, 0., 0.), now);
2152        assert!(recognizer.offer_touch_drag(touch).is_some());
2153        recognizer.resolve_touch_drag(false);
2154
2155        let moved = recognizer.handle_event_at(
2156            &touch_event(touch, TouchPhase::Moved, 20., 0.),
2157            now + Duration::from_millis(10),
2158        );
2159        assert!(matches!(
2160            moved.as_slice(),
2161            [RecognizedTouchGesture::Scroll(ScrollEvent {
2162                touch_phase: TouchPhase::Started,
2163                ..
2164            })]
2165        ));
2166    }
2167
2168    #[test]
2169    fn claimed_long_press_emits_phased_stream_without_tap() {
2170        let mut recognizer = TouchGestureRecognizer::new(GestureTuning::default());
2171        let touch = TouchId(1);
2172        let now = Instant::now();
2173        recognizer.handle_event_at(&touch_event(touch, TouchPhase::Started, 10., 20.), now);
2174        let Some(RecognizedTouchGesture::LongPress(started)) = recognizer.offer_long_press(touch)
2175        else {
2176            panic!("expected long press");
2177        };
2178        assert_eq!(started.phase, TouchPhase::Started);
2179        assert_eq!(started.start_position, point(px(10.), px(20.)));
2180        recognizer.resolve_long_press(true);
2181
2182        let moved = recognizer.handle_event_at(
2183            &touch_event(touch, TouchPhase::Moved, 12., 21.),
2184            now + Duration::from_millis(510),
2185        );
2186        let [RecognizedTouchGesture::LongPress(moved)] = moved.as_slice() else {
2187            panic!("expected moved long press, got {moved:?}");
2188        };
2189        assert_eq!(moved.phase, TouchPhase::Moved);
2190
2191        let ended = recognizer.handle_event_at(
2192            &touch_event(touch, TouchPhase::Ended, 12., 21.),
2193            now + Duration::from_millis(520),
2194        );
2195        let [RecognizedTouchGesture::LongPress(ended)] = ended.as_slice() else {
2196            panic!("expected ended long press, got {ended:?}");
2197        };
2198        assert_eq!(ended.phase, TouchPhase::Ended);
2199    }
2200
2201    #[test]
2202    fn unclaimed_long_press_remains_a_tap_candidate() {
2203        let mut recognizer = TouchGestureRecognizer::new(GestureTuning::default());
2204        let touch = TouchId(1);
2205        let now = Instant::now();
2206        recognizer.handle_event_at(&touch_event(touch, TouchPhase::Started, 10., 20.), now);
2207        assert!(recognizer.offer_long_press(touch).is_some());
2208        recognizer.resolve_long_press(false);
2209
2210        let ended = recognizer.handle_event_at(
2211            &touch_event(touch, TouchPhase::Ended, 10., 20.),
2212            now + Duration::from_millis(510),
2213        );
2214        assert!(matches!(
2215            ended.as_slice(),
2216            [RecognizedTouchGesture::Tap { .. }]
2217        ));
2218    }
2219
2220    #[test]
2221    fn unclaimed_long_press_can_still_become_a_pan() {
2222        let mut recognizer = TouchGestureRecognizer::new(GestureTuning::default());
2223        let touch = TouchId(1);
2224        let now = Instant::now();
2225        recognizer.handle_event_at(&touch_event(touch, TouchPhase::Started, 0., 0.), now);
2226        assert!(recognizer.offer_long_press(touch).is_some());
2227        recognizer.resolve_long_press(false);
2228
2229        let moved = recognizer.handle_event_at(
2230            &touch_event(touch, TouchPhase::Moved, 20., 0.),
2231            now + Duration::from_millis(510),
2232        );
2233        assert!(matches!(
2234            moved.as_slice(),
2235            [RecognizedTouchGesture::Scroll(ScrollEvent {
2236                touch_phase: TouchPhase::Started,
2237                ..
2238            })]
2239        ));
2240    }
2241
2242    #[test]
2243    fn long_press_offer_is_one_shot_and_specific_to_pending_touch() {
2244        let mut recognizer = TouchGestureRecognizer::new(GestureTuning::default());
2245        let touch = TouchId(1);
2246        recognizer.handle_event(&touch_event(touch, TouchPhase::Started, 0., 0.));
2247
2248        assert!(
2249            recognizer
2250                .handle_event(&touch_event(TouchId(2), TouchPhase::Moved, 20., 0.))
2251                .is_empty()
2252        );
2253        assert!(recognizer.offer_long_press(TouchId(2)).is_none());
2254        assert!(recognizer.offer_long_press(touch).is_some());
2255        assert!(recognizer.offer_long_press(touch).is_none());
2256    }
2257
2258    #[test]
2259    fn long_press_cannot_be_offered_after_pending_touch_resolves() {
2260        for phase in [TouchPhase::Ended, TouchPhase::Cancelled, TouchPhase::Moved] {
2261            let mut recognizer = TouchGestureRecognizer::new(GestureTuning::default());
2262            let touch = TouchId(1);
2263            let now = Instant::now();
2264            recognizer.handle_event_at(&touch_event(touch, TouchPhase::Started, 0., 0.), now);
2265            let position = if phase == TouchPhase::Moved { 20. } else { 0. };
2266            recognizer.handle_event_at(
2267                &touch_event(touch, phase, position, 0.),
2268                now + Duration::from_millis(10),
2269            );
2270            assert!(recognizer.offer_long_press(touch).is_none());
2271        }
2272    }
2273
2274    #[test]
2275    fn claimed_long_press_emits_cancelled_for_its_touch_only() {
2276        let mut recognizer = TouchGestureRecognizer::new(GestureTuning::default());
2277        let touch = TouchId(1);
2278        recognizer.handle_event(&touch_event(touch, TouchPhase::Started, 4., 5.));
2279        assert!(recognizer.offer_long_press(touch).is_some());
2280        recognizer.resolve_long_press(true);
2281
2282        assert!(
2283            recognizer
2284                .handle_event(&touch_event(TouchId(2), TouchPhase::Cancelled, 9., 9.))
2285                .is_empty()
2286        );
2287        let cancelled = recognizer.handle_event(&touch_event(touch, TouchPhase::Cancelled, 6., 7.));
2288        let [RecognizedTouchGesture::LongPress(cancelled)] = cancelled.as_slice() else {
2289            panic!("expected cancelled long press, got {cancelled:?}");
2290        };
2291        assert_eq!(cancelled.phase, TouchPhase::Cancelled);
2292        assert_eq!(cancelled.start_position, point(px(4.), px(5.)));
2293        assert_eq!(cancelled.position, point(px(6.), px(7.)));
2294    }
2295
2296    #[test]
2297    fn unrelated_touch_cannot_end_or_cancel_pending_touch() {
2298        for phase in [TouchPhase::Ended, TouchPhase::Cancelled] {
2299            let mut recognizer = TouchGestureRecognizer::new(GestureTuning::default());
2300            let touch = TouchId(1);
2301            recognizer.handle_event(&touch_event(touch, TouchPhase::Started, 4., 5.));
2302
2303            assert!(
2304                recognizer
2305                    .handle_event(&touch_event(TouchId(2), phase, 9., 9.))
2306                    .is_empty()
2307            );
2308            assert!(recognizer.offer_long_press(touch).is_some());
2309        }
2310    }
2311
2312    #[test]
2313    fn completed_touch_id_cannot_claim_replacement_touch() {
2314        let mut recognizer = TouchGestureRecognizer::new(GestureTuning::default());
2315        let completed_touch = TouchId(1);
2316        let replacement_touch = TouchId(2);
2317        recognizer.handle_event(&touch_event(completed_touch, TouchPhase::Started, 0., 0.));
2318        recognizer.handle_event(&touch_event(completed_touch, TouchPhase::Cancelled, 0., 0.));
2319        recognizer.handle_event(&touch_event(replacement_touch, TouchPhase::Started, 5., 5.));
2320
2321        assert!(recognizer.offer_long_press(completed_touch).is_none());
2322        assert!(recognizer.offer_long_press(replacement_touch).is_some());
2323    }
2324
2325    fn touch_event(id: TouchId, phase: TouchPhase, x: f32, y: f32) -> TouchEvent {
2326        TouchEvent {
2327            id,
2328            phase,
2329            position: point(px(x), px(y)),
2330            predicted_position: None,
2331            force: None,
2332        }
2333    }
2334}