Skip to main content

day_core/
gesture.rs

1// Copyright © The Daybrite Project
2// SPDX-License-Identifier: MPL-2.0
3
4//! Gesture recognition shared by every toolkit (docs/gestures.md "Recognizers").
5//!
6//! Every native event passes through `route` on its way to a node's handlers. That one
7//! place does what no backend has to repeat:
8//!
9//! - **Velocity.** A drag's and a pan's velocity is estimated from the event samples
10//!   ([`VelocityTracker`]); a backend whose recognizer measures its own sends
11//!   `Event::GestureVelocity` before `Ended` and that value wins.
12//! - **Derived recognizers.** Where `Toolkit::gesture_support` answers `Unsupported`, press-in
13//!   and press-out, long press, double tap and a single-contact touch list are derived from the
14//!   tap and drag events (`Recognizer`).
15//! - **The drag axis.** A drag declared along one axis never reaches its handler when the
16//!   pointer set off along the other.
17//! - **Disabled subtrees.** Input addressed to a node under `.enabled(false)` is dropped.
18//! - **The input kind.** `Event::PointerKindChanged` lands in [`primary_pointer`].
19
20use std::cell::{Cell, RefCell};
21use std::collections::{HashMap, VecDeque};
22
23use day_reactive::Signal;
24use day_spec::{
25    DragAxis, DragPhase, Event, GestureKind, NodeId, Point, PointerKind, Support, Touch, TouchPhase,
26};
27
28use crate::tree::{RNode, id_to_rnode, rnode_to_id, with_tree};
29
30/// How long a press is held still before it is a long press, in milliseconds, where day-core
31/// derives the gesture. A native recognizer uses the platform's own delay.
32pub const LONG_PRESS_MS: u32 = 500;
33/// How long a single tap waits for a second one on a piece that handles both, in milliseconds,
34/// where day-core derives the double tap. A native recognizer uses the platform's interval.
35pub const DOUBLE_TAP_MS: u32 = 300;
36/// How far apart two taps may land and still be a double tap, in points.
37const DOUBLE_TAP_SLOP: f64 = 40.0;
38/// How far a press may travel and still become a long press, in points.
39const PRESS_SLOP: f64 = 10.0;
40/// How far a drag declared along one axis travels before its direction is judged, in points.
41const AXIS_SLOP: f64 = 3.0;
42/// The span of samples a velocity is measured over, in seconds.
43const VELOCITY_WINDOW: f64 = 0.1;
44/// A tap this soon after a press ended belongs to that press, in seconds: some backends report
45/// a still press as a zero-length drag and a tap, and the pair is one press.
46const SAME_PRESS: f64 = 0.3;
47
48day_reactive::tls_slots! {
49    gesture;
50    static NODES: RefCell<HashMap<NodeId, NodeState>> = RefCell::new(HashMap::new());
51    static POINTER: Cell<Option<Signal<PointerKind>>> = const { Cell::new(None) };
52}
53
54/// Estimates a pointer's velocity from timestamped positions: the distance covered over the
55/// last tenth of a second, in points per second, and zero once the pointer has rested that
56/// long. One per drag and per pan; public so a piece that tracks its own pointer (a custom
57/// recognizer over `on_touches`) measures the same way.
58#[derive(Clone, Debug, Default)]
59pub struct VelocityTracker {
60    samples: VecDeque<(f64, Point)>,
61}
62
63impl VelocityTracker {
64    /// Forget every sample: a new gesture began.
65    pub fn reset(&mut self) {
66        self.samples.clear();
67    }
68
69    /// Record the pointer at `position` at time `at` (seconds on a monotonic clock).
70    pub fn push(&mut self, at: f64, position: Point) {
71        self.samples.push_back((at, position));
72        while self
73            .samples
74            .front()
75            .is_some_and(|(t, _)| at - t > VELOCITY_WINDOW * 2.0)
76        {
77            self.samples.pop_front();
78        }
79    }
80
81    /// The velocity at time `now`, in points per second. Zero with fewer than two samples in
82    /// the window, or when they span less than a millisecond (a scripted gesture's samples
83    /// arrive at once and measure nothing).
84    #[must_use]
85    pub fn velocity(&self, now: f64) -> Point {
86        let mut recent = self
87            .samples
88            .iter()
89            .filter(|(t, _)| now - t <= VELOCITY_WINDOW);
90        let Some(&(t0, p0)) = recent.next() else {
91            return Point::ZERO;
92        };
93        let Some(&(t1, p1)) = recent.next_back() else {
94            return Point::ZERO;
95        };
96        let span = t1 - t0;
97        if span < 0.001 {
98            return Point::ZERO;
99        }
100        Point::new((p1.x - p0.x) / span, (p1.y - p0.y) / span)
101    }
102}
103
104/// Which gestures day-core derives for a node, decided when the piece enabled them.
105#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
106pub(crate) struct Derived {
107    pub press: bool,
108    pub long_press: bool,
109    pub double_tap: bool,
110    pub touches: bool,
111}
112
113/// What a [`Recognizer`] asks its host to do after an event.
114#[derive(Clone, Debug, PartialEq)]
115pub(crate) enum Action {
116    /// Deliver this event to the node's handlers.
117    Emit(Event),
118    /// Call [`Recognizer::long_press_due`] with this token after the long-press delay.
119    ArmLongPress(u64),
120    /// Call [`Recognizer::tap_due`] with this token after the double-tap interval.
121    ArmTap(u64),
122}
123
124/// Whether a drag declared along one axis is the node's.
125#[derive(Clone, Copy, Debug, Default, PartialEq)]
126enum AxisGate {
127    /// No drag under way.
128    #[default]
129    Idle,
130    /// `Began` arrived and is held back until the pointer has moved far enough to judge.
131    Pending { location: Point, translation: Point },
132    /// The drag runs along the axis: its events pass.
133    Open,
134    /// The drag set off across the axis: its events are withheld until it ends.
135    Closed,
136}
137
138/// The per-node state machine behind the derived recognizers, free of clocks and timers so it
139/// can be tested directly: every method takes the time, and timers are requested as
140/// [`Action`]s and answered through [`Recognizer::long_press_due`] and [`Recognizer::tap_due`].
141#[derive(Debug, Default)]
142pub(crate) struct Recognizer {
143    pub derived: Derived,
144    /// The piece handles a single tap.
145    pub wants_tap: bool,
146    /// The piece handles a double tap.
147    pub wants_double_tap: bool,
148    /// The piece handles a drag.
149    pub wants_drag: bool,
150    pub axis: Option<DragAxis>,
151    gate: AxisGate,
152    /// The press point while the pointer is down.
153    pressed: Option<Point>,
154    /// The press moved past [`PRESS_SLOP`], which rules a long press out.
155    moved: bool,
156    /// This press already fired its long press, which rules a tap out.
157    held: bool,
158    press_ended_at: f64,
159    swallow_tap_until: f64,
160    long_press_token: u64,
161    /// A single tap waiting out the double-tap interval: where, when, and its timer token.
162    pending_tap: Option<(Point, f64, u64)>,
163    /// The previous tap on a piece that handles double taps only.
164    last_tap: Option<(Point, f64)>,
165    next_token: u64,
166}
167
168impl Recognizer {
169    fn token(&mut self) -> u64 {
170        self.next_token += 1;
171        self.next_token
172    }
173
174    /// Whether the pointer is down on the node, as far as the derived press knows.
175    pub fn is_pressed(&self) -> bool {
176        self.pressed.is_some()
177    }
178
179    fn press_in(&mut self, at: Point, moved: bool, out: &mut Vec<Action>) {
180        self.pressed = Some(at);
181        self.moved = moved;
182        self.held = false;
183        if self.derived.press {
184            out.push(Action::Emit(Event::Press {
185                pressed: true,
186                location: at,
187            }));
188        }
189        if self.derived.long_press && !moved {
190            self.long_press_token = self.token();
191            out.push(Action::ArmLongPress(self.long_press_token));
192        }
193    }
194
195    fn press_out(&mut self, at: Point, now: f64, out: &mut Vec<Action>) {
196        if self.pressed.take().is_none() {
197            return;
198        }
199        self.long_press_token = 0;
200        self.press_ended_at = now;
201        if self.held {
202            self.swallow_tap_until = now + SAME_PRESS;
203        }
204        if self.derived.press {
205            out.push(Action::Emit(Event::Press {
206                pressed: false,
207                location: at,
208            }));
209        }
210    }
211
212    /// A press event, native or scripted: the long press is timed from it where derived.
213    pub fn on_press(&mut self, pressed: bool, location: Point, now: f64, out: &mut Vec<Action>) {
214        if pressed {
215            self.pressed = Some(location);
216            self.moved = false;
217            self.held = false;
218            if self.derived.long_press {
219                self.long_press_token = self.token();
220                out.push(Action::ArmLongPress(self.long_press_token));
221            }
222        } else if self.pressed.take().is_none() {
223            // A release with no press under way (a toolkit reporting both edges of a press it
224            // did not start here) ends nothing.
225            return;
226        } else {
227            self.long_press_token = 0;
228            self.press_ended_at = now;
229            if self.held {
230                self.swallow_tap_until = now + SAME_PRESS;
231            }
232        }
233        out.push(Action::Emit(Event::Press { pressed, location }));
234    }
235
236    /// One drag event. Derives the press and the touch list from its phases, then lets the
237    /// drag itself through unless the axis gate withholds it.
238    pub fn on_drag(
239        &mut self,
240        phase: DragPhase,
241        location: Point,
242        translation: Point,
243        now: f64,
244        out: &mut Vec<Action>,
245    ) {
246        let travel = translation.x.hypot(translation.y);
247        let derive_press = self.derived.press || self.derived.long_press;
248        match phase {
249            DragPhase::Began => {
250                if derive_press {
251                    // A recognizer that waited for movement reports `Began` with the
252                    // translation already applied: the press point is where it started.
253                    let at = Point::new(location.x - translation.x, location.y - translation.y);
254                    self.press_in(at, travel > PRESS_SLOP / 2.0, out);
255                }
256                if self.derived.touches {
257                    out.push(Action::Emit(Event::Touches(vec![Touch::new(
258                        0,
259                        TouchPhase::Began,
260                        location,
261                    )])));
262                }
263            }
264            DragPhase::Changed => {
265                if derive_press && travel > PRESS_SLOP && !self.moved {
266                    self.moved = true;
267                    self.long_press_token = 0;
268                }
269                if self.derived.touches {
270                    out.push(Action::Emit(Event::Touches(vec![Touch::new(
271                        0,
272                        TouchPhase::Moved,
273                        location,
274                    )])));
275                }
276            }
277            DragPhase::Ended => {
278                if derive_press {
279                    self.press_out(location, now, out);
280                }
281                if self.derived.touches {
282                    out.push(Action::Emit(Event::Touches(vec![Touch::new(
283                        0,
284                        TouchPhase::Ended,
285                        location,
286                    )])));
287                }
288            }
289        }
290        let drag = |phase, location, translation| {
291            Action::Emit(Event::Drag {
292                phase,
293                location,
294                translation,
295            })
296        };
297        let Some(axis) = self.axis else {
298            out.push(drag(phase, location, translation));
299            return;
300        };
301        match (phase, self.gate) {
302            (DragPhase::Began, _) => {
303                if travel >= AXIS_SLOP {
304                    if axis.leads(translation) {
305                        self.gate = AxisGate::Open;
306                        out.push(drag(phase, location, translation));
307                    } else {
308                        self.gate = AxisGate::Closed;
309                    }
310                } else {
311                    self.gate = AxisGate::Pending {
312                        location,
313                        translation,
314                    };
315                }
316            }
317            (
318                DragPhase::Changed,
319                AxisGate::Pending {
320                    location: began_at,
321                    translation: began_by,
322                },
323            ) => {
324                if travel >= AXIS_SLOP {
325                    if axis.leads(translation) {
326                        self.gate = AxisGate::Open;
327                        out.push(drag(DragPhase::Began, began_at, began_by));
328                        out.push(drag(phase, location, translation));
329                    } else {
330                        self.gate = AxisGate::Closed;
331                    }
332                }
333            }
334            (DragPhase::Changed, AxisGate::Open) => out.push(drag(phase, location, translation)),
335            (DragPhase::Ended, AxisGate::Open) => {
336                self.gate = AxisGate::Idle;
337                out.push(drag(phase, location, translation));
338            }
339            // A flick whose movement arrives only with its release (no `Changed` in between)
340            // is decided there, and delivered whole when it went the drag's way.
341            (
342                DragPhase::Ended,
343                AxisGate::Pending {
344                    location: began_at,
345                    translation: began_by,
346                },
347            ) => {
348                self.gate = AxisGate::Idle;
349                if travel >= AXIS_SLOP && axis.leads(translation) {
350                    out.push(drag(DragPhase::Began, began_at, began_by));
351                    out.push(drag(phase, location, translation));
352                }
353            }
354            (DragPhase::Ended, _) => self.gate = AxisGate::Idle,
355            (DragPhase::Changed, _) => {}
356        }
357    }
358
359    /// One tap. Swallows the release of a long press, derives a press for a backend whose
360    /// drag begins only with movement, and pairs taps into a double tap.
361    pub fn on_tap(&mut self, at: Point, now: f64, out: &mut Vec<Action>) {
362        if now < self.swallow_tap_until {
363            self.swallow_tap_until = 0.0;
364            return;
365        }
366        if self.derived.press && self.pressed.is_none() && now - self.press_ended_at > SAME_PRESS {
367            out.push(Action::Emit(Event::Press {
368                pressed: true,
369                location: at,
370            }));
371            out.push(Action::Emit(Event::Press {
372                pressed: false,
373                location: at,
374            }));
375            self.press_ended_at = now;
376        }
377        if !(self.derived.double_tap && self.wants_double_tap) {
378            out.push(Action::Emit(Event::Tap(at)));
379            return;
380        }
381        let near = |a: Point, b: Point| (a.x - b.x).hypot(a.y - b.y) <= DOUBLE_TAP_SLOP;
382        let window = f64::from(DOUBLE_TAP_MS) / 1000.0;
383        if self.wants_tap {
384            match self.pending_tap.take() {
385                Some((first, when, _)) if now - when <= window && near(first, at) => {
386                    out.push(Action::Emit(Event::DoubleTap(at)));
387                }
388                stale => {
389                    // A tap that outlived its interval without its timer (the app was
390                    // suspended) is delivered now, ahead of the new one that takes its place.
391                    if let Some((first, ..)) = stale {
392                        out.push(Action::Emit(Event::Tap(first)));
393                    }
394                    let token = self.token();
395                    self.pending_tap = Some((at, now, token));
396                    out.push(Action::ArmTap(token));
397                }
398            }
399        } else {
400            match self.last_tap.take() {
401                Some((first, when)) if now - when <= window && near(first, at) => {
402                    out.push(Action::Emit(Event::DoubleTap(at)));
403                }
404                _ => self.last_tap = Some((at, now)),
405            }
406            out.push(Action::Emit(Event::Tap(at)));
407        }
408    }
409
410    /// The long-press timer `token` fired: a long press, if that press is still held still.
411    pub fn long_press_due(&mut self, token: u64, out: &mut Vec<Action>) {
412        if token == 0 || token != self.long_press_token || self.moved {
413            return;
414        }
415        let Some(at) = self.pressed else { return };
416        self.long_press_token = 0;
417        self.held = true;
418        out.push(Action::Emit(Event::LongPress(at)));
419    }
420
421    /// The double-tap timer `token` fired: the single tap it held back, if no second tap came.
422    pub fn tap_due(&mut self, token: u64, out: &mut Vec<Action>) {
423        if let Some((at, _, pending)) = self.pending_tap
424            && pending == token
425        {
426            self.pending_tap = None;
427            out.push(Action::Emit(Event::Tap(at)));
428        }
429    }
430
431    /// End a press the node can no longer finish (its subtree was disabled).
432    pub fn cancel(&mut self, now: f64, out: &mut Vec<Action>) {
433        if let Some(at) = self.pressed {
434            self.press_out(at, now, out);
435            if !self.derived.press {
436                out.push(Action::Emit(Event::Press {
437                    pressed: false,
438                    location: at,
439                }));
440            }
441        }
442        self.pending_tap = None;
443        self.gate = AxisGate::Idle;
444    }
445}
446
447#[derive(Default)]
448struct NodeState {
449    recognizer: Recognizer,
450    drag: VelocityTracker,
451    pan: VelocityTracker,
452    /// The pan's position so far: its deltas summed, which is what the tracker samples.
453    pan_position: Point,
454    /// The latest velocity of the drag and of the pan, as handlers read it.
455    velocity: [Point; 2],
456    /// The velocity the backend's own recognizer reported for the gesture about to end.
457    native_velocity: [Option<Point>; 2],
458}
459
460fn slot(kind: GestureKind) -> usize {
461    usize::from(kind == GestureKind::Pan)
462}
463
464fn with_state<R>(id: NodeId, f: impl FnOnce(&mut NodeState) -> R) -> R {
465    NODES.with(|n| f(n.borrow_mut().entry(id).or_default()))
466}
467
468fn pointer_signal() -> Signal<PointerKind> {
469    POINTER.with(|p| {
470        if let Some(s) = p.get() {
471            s
472        } else {
473            let initial = if crate::tree::has_tree() {
474                with_tree(|t| t.primary_pointer())
475            } else {
476                PointerKind::platform_default()
477            };
478            let s = Signal::global(initial);
479            p.set(Some(s));
480            s
481        }
482    })
483}
484
485/// The kind of pointer the person is using: touch, mouse or stylus, following the last input
486/// (docs/gestures.md "Input kind"). A tracked read, so wording and affordances that depend on it
487/// update when an iPad's trackpad or a laptop's touch screen comes into use. Before any input
488/// it is the platform's usual kind.
489#[must_use]
490pub fn primary_pointer() -> PointerKind {
491    pointer_signal().get()
492}
493
494/// The velocity of `node`'s drag or pan (`kind`) as of the event being handled, in points per
495/// second: the backend's own measurement at the release where it sent one, day-core's estimate
496/// from the event samples otherwise. What `Drag::velocity` and `Pan::velocity` carry.
497#[must_use]
498pub fn velocity(node: NodeId, kind: GestureKind) -> Point {
499    NODES.with(|n| {
500        n.borrow()
501            .get(&node)
502            .map_or(Point::ZERO, |s| s.velocity[slot(kind)])
503    })
504}
505
506/// How the active toolkit delivers a gesture (docs/gestures.md "Recognizers"): `Native` for the
507/// platform's own recognizer, `Emulated` where day-core derives it from taps and drags (a
508/// derived `Touches` reports one contact), `Unsupported` where it never fires.
509#[must_use]
510pub fn gesture_support(kind: GestureKind) -> Support {
511    match with_tree(|t| t.gesture_support(kind)) {
512        Support::Unsupported
513            if matches!(
514                kind,
515                GestureKind::LongPress
516                    | GestureKind::DoubleTap
517                    | GestureKind::Press
518                    | GestureKind::Touches
519            ) =>
520        {
521            Support::Emulated
522        }
523        other => other,
524    }
525}
526
527/// Record that `node` enabled `kind`, and whether day-core derives it (the tree's
528/// `enable_gesture` decides, since it owns the toolkit).
529pub(crate) fn note_enabled(node: NodeId, kind: GestureKind, derived: bool) {
530    with_state(node, |s| {
531        let r = &mut s.recognizer;
532        match kind {
533            GestureKind::Tap => r.wants_tap = true,
534            GestureKind::Drag => r.wants_drag = true,
535            GestureKind::DoubleTap => {
536                r.wants_double_tap = true;
537                r.derived.double_tap = derived;
538            }
539            GestureKind::LongPress => r.derived.long_press = derived,
540            GestureKind::Press => r.derived.press = derived,
541            GestureKind::Touches => r.derived.touches = derived,
542            _ => {}
543        }
544    });
545}
546
547/// Record the axis `node`'s drag follows (`Decorate::on_drag_along`).
548pub(crate) fn set_axis(node: NodeId, axis: Option<DragAxis>) {
549    with_state(node, |s| s.recognizer.axis = axis);
550}
551
552/// Drop a removed node's gesture state (the tree's removal path calls it).
553pub(crate) fn forget(node: NodeId) {
554    let _ = NODES.try_with(|n| n.borrow_mut().remove(&node));
555}
556
557fn is_input(ev: &Event) -> bool {
558    matches!(
559        ev,
560        Event::Pressed
561            | Event::Tap(_)
562            | Event::DoubleTap(_)
563            | Event::LongPress(_)
564            | Event::Press { pressed: true, .. }
565            | Event::Touches(_)
566            | Event::Drag { .. }
567            | Event::Pan { .. }
568            | Event::Pinch { .. }
569            | Event::Rotate { .. }
570            | Event::Hover {
571                phase: DragPhase::Began | DragPhase::Changed,
572                ..
573            }
574            | Event::Key(_)
575            | Event::ContextMenu { .. }
576            // A link in a label is a control too: a disabled group's links do not open.
577            | Event::LinkActivated(_)
578    )
579}
580
581fn target(id: NodeId, kind: GestureKind) -> NodeId {
582    if id == day_spec::WINDOW_NODE {
583        return id;
584    }
585    with_tree(|t| t.gesture_target(id_to_rnode(id), kind)).map_or(id, rnode_to_id)
586}
587
588/// Run a recognizer step for `node` and carry out what it asks: collect the events to deliver
589/// and start the timers.
590fn step(
591    node: NodeId,
592    f: &mut dyn FnMut(&mut Recognizer, &mut Vec<Action>),
593) -> Vec<(NodeId, Event)> {
594    let mut actions = Vec::new();
595    with_state(node, |s| f(&mut s.recognizer, &mut actions));
596    let mut out = Vec::new();
597    for action in actions {
598        match action {
599            Action::Emit(ev) => out.push((node, ev)),
600            Action::ArmLongPress(token) => arm(node, LONG_PRESS_MS, Due::LongPress(token)),
601            Action::ArmTap(token) => arm(node, DOUBLE_TAP_MS, Due::Tap(token)),
602        }
603    }
604    out
605}
606
607/// Send the taps or drags (`kind`) in `events` on to the nearest piece above `node` that
608/// handles them, when `node` itself only watched them to derive a press: a pressable row
609/// inside a tappable card must not swallow the card's tap.
610///
611/// Each one arrives at the piece above as if it had been delivered there: its point moved into
612/// that piece's coordinates, through that piece's own recognizer (its drag axis, its double
613/// tap, its own press), and a drag carries the release velocity `node` measured or was sent.
614fn pass_on(
615    node: NodeId,
616    kind: GestureKind,
617    events: Vec<(NodeId, Event)>,
618    now: f64,
619) -> Vec<(NodeId, Event)> {
620    let handles_it = NODES.with(|n| {
621        n.borrow().get(&node).is_none_or(|s| {
622            let r = &s.recognizer;
623            // Only a node day-core attached the recognizer to for its own derivation can
624            // have received an event it does not handle.
625            let watched = r.derived.press || r.derived.long_press;
626            match kind {
627                GestureKind::Tap => !watched || r.wants_tap || r.wants_double_tap,
628                _ => !(watched || r.derived.touches) || r.wants_drag,
629            }
630        })
631    });
632    if handles_it {
633        return events;
634    }
635    let Some((above, offset)) = with_tree(|t| {
636        let below = id_to_rnode(node);
637        let above = t.gesture_ancestor(below, kind)?;
638        // Before a layout there is no offset to apply; the point is the best there is.
639        Some((above, t.offset_in(below, above).unwrap_or(Point::ZERO)))
640    }) else {
641        return events;
642    };
643    let above = rnode_to_id(above);
644    let moved = |p: Point| Point::new(p.x + offset.x, p.y + offset.y);
645    let mut out = Vec::new();
646    for (id, ev) in events {
647        match (kind, ev) {
648            (GestureKind::Tap, Event::Tap(at)) => out.extend(tap_at(above, moved(at), now)),
649            (
650                GestureKind::Drag,
651                Event::Drag {
652                    phase,
653                    location,
654                    translation,
655                },
656            ) => {
657                let released =
658                    (phase == DragPhase::Ended).then(|| velocity(node, GestureKind::Drag));
659                out.extend(drag_at(
660                    above,
661                    phase,
662                    moved(location),
663                    translation,
664                    now,
665                    released,
666                ));
667            }
668            (_, ev) => out.push((id, ev)),
669        }
670    }
671    out
672}
673
674/// Deliver a drag to `node` (already resolved as its target): track its velocity, run its
675/// recognizer, and pass it on if `node` only watched it. `native` is a release velocity a
676/// recognizer below already settled on, which wins over this node's estimate like the
677/// backend's own measurement does.
678fn drag_at(
679    node: NodeId,
680    phase: DragPhase,
681    location: Point,
682    translation: Point,
683    now: f64,
684    native: Option<Point>,
685) -> Vec<(NodeId, Event)> {
686    with_state(node, |s| {
687        if phase == DragPhase::Began {
688            s.drag.reset();
689            s.native_velocity[0] = None;
690        }
691        if native.is_some() {
692            s.native_velocity[0] = native;
693        }
694        s.drag.push(now, translation);
695        s.velocity[0] = match (phase, s.native_velocity[0].take()) {
696            (DragPhase::Ended, Some(native)) => native,
697            _ => s.drag.velocity(now),
698        };
699    });
700    let out = step(node, &mut |r, out| {
701        r.on_drag(phase, location, translation, now, out);
702    });
703    pass_on(node, GestureKind::Drag, out, now)
704}
705
706/// Deliver a tap to `node` (already resolved as its target): its recognizer holds it back for
707/// a double tap or turns it into one, and it is passed on if `node` only watched it.
708fn tap_at(node: NodeId, at: Point, now: f64) -> Vec<(NodeId, Event)> {
709    // Nothing is derived for a node that never enabled a gesture through the tree.
710    if NODES.with(|n| n.borrow().contains_key(&node)) {
711        let out = step(node, &mut |r, out| r.on_tap(at, now, out));
712        pass_on(node, GestureKind::Tap, out, now)
713    } else {
714        vec![(node, Event::Tap(at))]
715    }
716}
717
718/// What a timer answers when it fires.
719#[derive(Clone, Copy)]
720enum Due {
721    LongPress(u64),
722    Tap(u64),
723}
724
725fn arm(node: NodeId, ms: u32, due: Due) {
726    crate::task(async move {
727        crate::sleep(ms).await;
728        // The node may be gone by now; a state entry is only read, never created, here.
729        if !NODES.with(|n| n.borrow().contains_key(&node)) {
730            return;
731        }
732        let events = step(node, &mut |r, out| match due {
733            Due::LongPress(token) => r.long_press_due(token, out),
734            Due::Tap(token) => r.tap_due(token, out),
735        });
736        for (id, ev) in events {
737            crate::tree::dispatch_routed(id, &ev);
738        }
739    });
740}
741
742/// Enable or disable everything under `node` (`Decorate::enabled`, docs/forms.md "Disabling a
743/// group"): the toolkit disables the native controls, and from here on day-core drops the
744/// input addressed to the subtree. A press under way when the subtree is disabled ends.
745pub fn set_subtree_enabled(node: RNode, enabled: bool) {
746    with_tree(|t| t.set_subtree_enabled(node, enabled));
747    if !enabled {
748        cancel_disabled();
749    }
750}
751
752/// End the presses under a subtree that was just disabled, so nothing stays pressed.
753fn cancel_disabled() {
754    let pressed: Vec<NodeId> = NODES.with(|n| {
755        n.borrow()
756            .iter()
757            .filter(|(_, s)| s.recognizer.is_pressed())
758            .map(|(id, _)| *id)
759            .collect()
760    });
761    let now = crate::frame::now_secs();
762    for id in pressed {
763        if with_tree(|t| t.subtree_disabled(id_to_rnode(id))) {
764            for (id, ev) in step(id, &mut |r, out| r.cancel(now, out)) {
765                crate::tree::dispatch_routed(id, &ev);
766            }
767        }
768    }
769}
770
771/// Route one event on its way to the handlers: the events to deliver in its place, each with
772/// the node it goes to. Most events come back unchanged; see the module docs for the rest.
773pub(crate) fn route(id: NodeId, ev: Event) -> Vec<(NodeId, Event)> {
774    match &ev {
775        Event::PointerKindChanged(kind) => {
776            pointer_signal().set(*kind);
777            return Vec::new();
778        }
779        Event::GestureVelocity { kind, velocity } => {
780            let node = target(id, *kind);
781            with_state(node, |s| s.native_velocity[slot(*kind)] = Some(*velocity));
782            return Vec::new();
783        }
784        _ => {}
785    }
786    if id != day_spec::WINDOW_NODE
787        && is_input(&ev)
788        && with_tree(|t| t.subtree_disabled(id_to_rnode(id)))
789    {
790        return Vec::new();
791    }
792    let now = crate::frame::now_secs();
793    match ev {
794        Event::Drag {
795            phase,
796            location,
797            translation,
798        } => drag_at(
799            target(id, GestureKind::Drag),
800            phase,
801            location,
802            translation,
803            now,
804            None,
805        ),
806        Event::Pan { phase, delta, .. } => {
807            let node = target(id, GestureKind::Pan);
808            with_state(node, |s| {
809                if phase == DragPhase::Began {
810                    s.pan.reset();
811                    s.pan_position = Point::ZERO;
812                    s.native_velocity[1] = None;
813                }
814                s.pan_position = Point::new(s.pan_position.x + delta.x, s.pan_position.y + delta.y);
815                s.pan.push(now, s.pan_position);
816                s.velocity[1] = match (phase, s.native_velocity[1].take()) {
817                    (DragPhase::Ended, Some(native)) => native,
818                    _ => s.pan.velocity(now),
819                };
820            });
821            vec![(node, ev)]
822        }
823        Event::Tap(at) => tap_at(target(id, GestureKind::Tap), at, now),
824        Event::Press { pressed, location } => {
825            let node = target(id, GestureKind::Press);
826            step(node, &mut |r, out| r.on_press(pressed, location, now, out))
827        }
828        other => vec![(id, other)],
829    }
830}
831
832#[cfg(test)]
833mod tests {
834    use super::*;
835
836    fn emitted(actions: &[Action]) -> Vec<Event> {
837        actions
838            .iter()
839            .filter_map(|a| match a {
840                Action::Emit(ev) => Some(ev.clone()),
841                _ => None,
842            })
843            .collect()
844    }
845
846    fn p(x: f64, y: f64) -> Point {
847        Point::new(x, y)
848    }
849
850    #[test]
851    fn velocity_is_distance_over_the_last_tenth_of_a_second() {
852        let mut v = VelocityTracker::default();
853        assert_eq!(v.velocity(0.0), Point::ZERO, "no samples");
854        v.push(0.00, p(0.0, 0.0));
855        assert_eq!(v.velocity(0.0), Point::ZERO, "one sample");
856        v.push(0.05, p(50.0, -25.0));
857        let now = v.velocity(0.05);
858        assert!((now.x - 1000.0).abs() < 1e-6 && (now.y + 500.0).abs() < 1e-6);
859        // An older stretch drops out of the window: only the last 100 ms count.
860        v.push(0.20, p(60.0, -25.0));
861        v.push(0.25, p(80.0, -25.0));
862        let later = v.velocity(0.25);
863        assert!((later.x - 400.0).abs() < 1e-6 && later.y.abs() < 1e-6);
864        // A pointer that rested before the release has no velocity.
865        assert_eq!(v.velocity(0.50), Point::ZERO);
866        // Samples that arrive at once measure nothing, they do not divide by zero.
867        let mut burst = VelocityTracker::default();
868        burst.push(1.0, p(0.0, 0.0));
869        burst.push(1.0, p(90.0, 0.0));
870        assert_eq!(burst.velocity(1.0), Point::ZERO);
871        burst.reset();
872        assert_eq!(burst.velocity(1.0), Point::ZERO);
873    }
874
875    #[test]
876    fn press_and_long_press_are_derived_from_drag_phases() {
877        let mut r = Recognizer {
878            derived: Derived {
879                press: true,
880                long_press: true,
881                ..Derived::default()
882            },
883            ..Recognizer::default()
884        };
885        let mut out = Vec::new();
886        r.on_drag(DragPhase::Began, p(5.0, 5.0), Point::ZERO, 0.0, &mut out);
887        let token = out
888            .iter()
889            .find_map(|a| match a {
890                Action::ArmLongPress(t) => Some(*t),
891                _ => None,
892            })
893            .expect("a still press arms the long press");
894        assert!(matches!(
895            emitted(&out)[0],
896            Event::Press { pressed: true, .. }
897        ));
898        assert!(r.is_pressed());
899        out.clear();
900        r.long_press_due(token, &mut out);
901        assert_eq!(emitted(&out), vec![Event::LongPress(p(5.0, 5.0))]);
902        out.clear();
903        r.on_drag(DragPhase::Ended, p(5.0, 5.0), Point::ZERO, 0.6, &mut out);
904        assert!(matches!(
905            emitted(&out)[0],
906            Event::Press { pressed: false, .. }
907        ));
908        // The release of a long press is not a tap.
909        out.clear();
910        r.on_tap(p(5.0, 5.0), 0.61, &mut out);
911        assert!(emitted(&out).is_empty(), "{out:?}");
912        // The tap after that is one again, and it brings no second press pair with it while
913        // the first press is this recent.
914        r.on_tap(p(5.0, 5.0), 0.7, &mut out);
915        assert_eq!(emitted(&out), vec![Event::Tap(p(5.0, 5.0))]);
916    }
917
918    #[test]
919    fn a_press_that_moves_or_lifts_never_becomes_a_long_press() {
920        let derived = Derived {
921            long_press: true,
922            ..Derived::default()
923        };
924        let mut moved = Recognizer {
925            derived,
926            ..Recognizer::default()
927        };
928        let mut out = Vec::new();
929        moved.on_drag(DragPhase::Began, p(0.0, 0.0), Point::ZERO, 0.0, &mut out);
930        let Some(Action::ArmLongPress(token)) = out.first().cloned() else {
931            panic!("armed: {out:?}")
932        };
933        moved.on_drag(
934            DragPhase::Changed,
935            p(30.0, 0.0),
936            p(30.0, 0.0),
937            0.1,
938            &mut out,
939        );
940        out.clear();
941        moved.long_press_due(token, &mut out);
942        assert!(out.is_empty(), "moved past the slop: {out:?}");
943
944        let mut lifted = Recognizer {
945            derived,
946            ..Recognizer::default()
947        };
948        lifted.on_drag(DragPhase::Began, p(0.0, 0.0), Point::ZERO, 0.0, &mut out);
949        let Some(Action::ArmLongPress(token)) = out.first().cloned() else {
950            panic!("armed: {out:?}")
951        };
952        lifted.on_drag(DragPhase::Ended, p(0.0, 0.0), Point::ZERO, 0.1, &mut out);
953        out.clear();
954        lifted.long_press_due(token, &mut out);
955        assert!(out.is_empty(), "lifted first: {out:?}");
956        // A press derived for nobody emits no press events of its own.
957        assert!(
958            !emitted(&out)
959                .iter()
960                .any(|e| matches!(e, Event::Press { .. }))
961        );
962    }
963
964    #[test]
965    fn a_tap_alone_is_a_whole_press_where_the_drag_needs_movement() {
966        let mut r = Recognizer {
967            derived: Derived {
968                press: true,
969                ..Derived::default()
970            },
971            wants_tap: true,
972            ..Recognizer::default()
973        };
974        let mut out = Vec::new();
975        r.on_tap(p(1.0, 2.0), 5.0, &mut out);
976        assert_eq!(
977            emitted(&out),
978            vec![
979                Event::Press {
980                    pressed: true,
981                    location: p(1.0, 2.0)
982                },
983                Event::Press {
984                    pressed: false,
985                    location: p(1.0, 2.0)
986                },
987                Event::Tap(p(1.0, 2.0)),
988            ]
989        );
990        // A backend that sends the zero-length drag AND the tap gets one pair, from the drag.
991        out.clear();
992        r.on_drag(DragPhase::Began, p(1.0, 2.0), Point::ZERO, 9.0, &mut out);
993        r.on_drag(DragPhase::Ended, p(1.0, 2.0), Point::ZERO, 9.05, &mut out);
994        r.on_tap(p(1.0, 2.0), 9.06, &mut out);
995        let presses = emitted(&out)
996            .iter()
997            .filter(|e| matches!(e, Event::Press { .. }))
998            .count();
999        assert_eq!(presses, 2, "{out:?}");
1000    }
1001
1002    #[test]
1003    fn a_single_tap_waits_only_when_a_double_tap_is_handled_too() {
1004        // Tap alone: straight through.
1005        let mut plain = Recognizer {
1006            wants_tap: true,
1007            ..Recognizer::default()
1008        };
1009        let mut out = Vec::new();
1010        plain.on_tap(p(0.0, 0.0), 0.0, &mut out);
1011        assert_eq!(out, vec![Action::Emit(Event::Tap(p(0.0, 0.0)))]);
1012
1013        // Both: the first tap is held, and delivered when its timer fires.
1014        let both = || Recognizer {
1015            derived: Derived {
1016                double_tap: true,
1017                ..Derived::default()
1018            },
1019            wants_tap: true,
1020            wants_double_tap: true,
1021            ..Recognizer::default()
1022        };
1023        let mut r = both();
1024        out.clear();
1025        r.on_tap(p(3.0, 3.0), 1.0, &mut out);
1026        let [Action::ArmTap(token)] = out[..] else {
1027            panic!("held: {out:?}")
1028        };
1029        out.clear();
1030        r.tap_due(token, &mut out);
1031        assert_eq!(emitted(&out), vec![Event::Tap(p(3.0, 3.0))]);
1032
1033        // Both, and a second tap inside the interval: one double tap, no single tap, and the
1034        // first tap's timer finds nothing left to deliver.
1035        let mut r = both();
1036        out.clear();
1037        r.on_tap(p(3.0, 3.0), 1.0, &mut out);
1038        let [Action::ArmTap(token)] = out[..] else {
1039            panic!("held: {out:?}")
1040        };
1041        out.clear();
1042        r.on_tap(p(4.0, 4.0), 1.2, &mut out);
1043        assert_eq!(emitted(&out), vec![Event::DoubleTap(p(4.0, 4.0))]);
1044        out.clear();
1045        r.tap_due(token, &mut out);
1046        assert_eq!(out, Vec::<Action>::new());
1047
1048        // Both, but the second tap lands far away: two single taps.
1049        let mut r = both();
1050        out.clear();
1051        r.on_tap(p(0.0, 0.0), 1.0, &mut out);
1052        r.on_tap(p(200.0, 0.0), 1.1, &mut out);
1053        assert_eq!(emitted(&out), vec![Event::Tap(p(0.0, 0.0))]);
1054
1055        // Double tap alone: nothing waits.
1056        let mut only = Recognizer {
1057            derived: Derived {
1058                double_tap: true,
1059                ..Derived::default()
1060            },
1061            wants_double_tap: true,
1062            ..Recognizer::default()
1063        };
1064        out.clear();
1065        only.on_tap(p(0.0, 0.0), 1.0, &mut out);
1066        only.on_tap(p(1.0, 0.0), 1.1, &mut out);
1067        assert_eq!(
1068            emitted(&out),
1069            vec![
1070                Event::Tap(p(0.0, 0.0)),
1071                Event::DoubleTap(p(1.0, 0.0)),
1072                Event::Tap(p(1.0, 0.0))
1073            ]
1074        );
1075    }
1076
1077    #[test]
1078    fn a_drag_along_one_axis_withholds_the_other() {
1079        let drags = |r: &mut Recognizer, to: Point| {
1080            let mut out = Vec::new();
1081            r.on_drag(DragPhase::Began, p(10.0, 10.0), Point::ZERO, 0.0, &mut out);
1082            r.on_drag(
1083                DragPhase::Changed,
1084                p(10.0 + to.x, 10.0 + to.y),
1085                to,
1086                0.01,
1087                &mut out,
1088            );
1089            r.on_drag(
1090                DragPhase::Ended,
1091                p(10.0 + to.x, 10.0 + to.y),
1092                to,
1093                0.02,
1094                &mut out,
1095            );
1096            emitted(&out)
1097                .into_iter()
1098                .filter_map(|e| match e {
1099                    Event::Drag { phase, .. } => Some(phase),
1100                    _ => None,
1101                })
1102                .collect::<Vec<_>>()
1103        };
1104        let mut r = Recognizer {
1105            axis: Some(DragAxis::Horizontal),
1106            ..Recognizer::default()
1107        };
1108        assert_eq!(
1109            drags(&mut r, p(40.0, 5.0)),
1110            vec![DragPhase::Began, DragPhase::Changed, DragPhase::Ended]
1111        );
1112        assert_eq!(drags(&mut r, p(5.0, 40.0)), Vec::<DragPhase>::new());
1113        // A press that never moves is nobody's drag.
1114        assert_eq!(drags(&mut r, Point::ZERO), Vec::<DragPhase>::new());
1115        // And the gate reopens for the next gesture.
1116        assert_eq!(drags(&mut r, p(-40.0, 0.0)).len(), 3);
1117        // A flick whose movement comes only with the release is decided there.
1118        let flick = |r: &mut Recognizer, to: Point| {
1119            let mut out = Vec::new();
1120            r.on_drag(DragPhase::Began, p(10.0, 10.0), Point::ZERO, 0.0, &mut out);
1121            r.on_drag(DragPhase::Ended, p(10.0 + to.x, 10.0), to, 0.02, &mut out);
1122            emitted(&out).len()
1123        };
1124        assert_eq!(flick(&mut r, p(30.0, 0.0)), 2, "Began and Ended");
1125        assert_eq!(flick(&mut r, p(0.0, 30.0)), 0);
1126        assert_eq!(flick(&mut r, p(1.0, 0.0)), 0, "too short to be a drag");
1127        // A single contact is derived from the same phases.
1128        let mut touches = Recognizer {
1129            derived: Derived {
1130                touches: true,
1131                ..Derived::default()
1132            },
1133            ..Recognizer::default()
1134        };
1135        let mut out = Vec::new();
1136        touches.on_drag(DragPhase::Began, p(1.0, 1.0), Point::ZERO, 0.0, &mut out);
1137        touches.on_drag(DragPhase::Ended, p(2.0, 1.0), p(1.0, 0.0), 0.1, &mut out);
1138        let phases: Vec<TouchPhase> = emitted(&out)
1139            .iter()
1140            .filter_map(|e| match e {
1141                Event::Touches(t) => Some(t[0].phase),
1142                _ => None,
1143            })
1144            .collect();
1145        assert_eq!(phases, vec![TouchPhase::Began, TouchPhase::Ended]);
1146    }
1147}