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