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