1use 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
30pub const LONG_PRESS_MS: u32 = 500;
33pub const DOUBLE_TAP_MS: u32 = 300;
36const DOUBLE_TAP_SLOP: f64 = 40.0;
38const PRESS_SLOP: f64 = 10.0;
40const AXIS_SLOP: f64 = 3.0;
42const VELOCITY_WINDOW: f64 = 0.1;
44const 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#[derive(Clone, Debug, Default)]
59pub struct VelocityTracker {
60 samples: VecDeque<(f64, Point)>,
61}
62
63impl VelocityTracker {
64 pub fn reset(&mut self) {
66 self.samples.clear();
67 }
68
69 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 #[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#[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#[derive(Clone, Debug, PartialEq)]
115pub(crate) enum Action {
116 Emit(Event),
118 ArmLongPress(u64),
120 ArmTap(u64),
122}
123
124#[derive(Clone, Copy, Debug, Default, PartialEq)]
126enum AxisGate {
127 #[default]
129 Idle,
130 Pending { location: Point, translation: Point },
132 Open,
134 Closed,
136}
137
138#[derive(Debug, Default)]
142pub(crate) struct Recognizer {
143 pub derived: Derived,
144 pub wants_tap: bool,
146 pub wants_double_tap: bool,
148 pub wants_drag: bool,
150 pub axis: Option<DragAxis>,
151 gate: AxisGate,
152 pressed: Option<Point>,
154 moved: bool,
156 held: bool,
158 press_ended_at: f64,
159 swallow_tap_until: f64,
160 long_press_token: u64,
161 pending_tap: Option<(Point, f64, u64)>,
163 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 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 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 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 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 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 (
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 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 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 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 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 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 pan_position: Point,
454 velocity: [Point; 2],
456 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#[must_use]
490pub fn primary_pointer() -> PointerKind {
491 pointer_signal().get()
492}
493
494#[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#[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
527pub(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
547pub(crate) fn set_axis(node: NodeId, axis: Option<DragAxis>) {
549 with_state(node, |s| s.recognizer.axis = axis);
550}
551
552pub(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 | 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
588fn 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
607fn 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 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 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
674fn 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
706fn tap_at(node: NodeId, at: Point, now: f64) -> Vec<(NodeId, Event)> {
709 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#[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 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
742pub 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
752fn 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
771pub(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 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 assert_eq!(v.velocity(0.50), Point::ZERO);
866 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 out.clear();
910 r.on_tap(p(5.0, 5.0), 0.61, &mut out);
911 assert!(emitted(&out).is_empty(), "{out:?}");
912 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 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 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 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 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 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 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 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 assert_eq!(drags(&mut r, Point::ZERO), Vec::<DragPhase>::new());
1115 assert_eq!(drags(&mut r, p(-40.0, 0.0)).len(), 3);
1117 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 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}