Skip to main content

waft_gestures/
recognizer.rs

1//! Flutter counterpart: `gestures/recognizer.dart`.
2//!
3//! Superclass field bags and `super` namespaces. Leaves implement
4//! [`RecognizerLeaf`] so a superclass body calls the leaf, not a sibling. A
5//! `super` call is a namespace fn taking the leaf's `Handle` first.
6//!
7//! Dart's `GestureRecognizer` used as a type (a field, a `Map<Type,
8//! GestureRecognizer>` value) is the erased [`AnyGestureRecognizer`], minted by
9//! [`GestureRecognizerLeaf::as_recognizer`].
10
11use std::any::TypeId;
12use std::collections::{HashMap, HashSet};
13use std::fmt;
14use std::rc::Rc;
15use std::time::Duration;
16
17use waft_embedder::{Matrix4, Offset, PointerDeviceKind};
18use waft_foundation::{App, Handle, HandleId, Listener, OptionRetained, Timer, bare_type_name};
19
20use crate::arena::{GestureArenaEntry, GestureArenaMember, GestureDisposition};
21use crate::binding::GestureBinding;
22use crate::constants::K_TOUCH_SLOP;
23use crate::debug::{debug_print_gesture_arena_diagnostics, debug_print_recognizer_callbacks_trace};
24use crate::events::{PointerDownEvent, PointerEvent, PointerPanZoomStartEvent};
25use crate::gesture_settings::DeviceGestureSettings;
26use crate::pointer_router::PointerRoute;
27use crate::team::GestureArenaTeam;
28use waft_foundation::Ref;
29use waft_foundation::Retained;
30
31/// Signature for a recognizer's `allowed_buttons_filter`.
32///
33/// Used to filter the input buttons of incoming pointer events.
34/// The parameter `buttons` comes from `PointerEvent.buttons`.
35pub type AllowedButtonsFilter = Rc<dyn Fn(i64) -> bool>;
36
37/// `-1` is used as a sentinel value to indicate no touch slop was specified.
38///
39/// Pass it to [`PrimaryPointerData::new`] where Dart omits `preAcceptSlopTolerance`
40/// or `postAcceptSlopTolerance`.
41pub const UNSET_TOUCH_SLOP: f64 = -1.0;
42
43/// The default value for `allowedButtonsFilter`.
44/// Accept any input.
45pub(crate) fn default_button_accept_behavior(_buttons: i64) -> bool {
46    true
47}
48
49/// Configuration of offset passed to `DragStartDetails`.
50///
51/// See also:
52///
53///  * `DragGestureRecognizer.dragStartBehavior`, which gives an example for the
54///    different behaviors.
55#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
56pub enum DragStartBehavior {
57    /// Set the initial offset at the position where the first down event was
58    /// detected.
59    Down,
60
61    /// Set the initial position at the position where this gesture recognizer
62    /// won the arena.
63    #[default]
64    Start,
65}
66
67/// Configuration of multi-finger drag strategy on multi-touch devices.
68///
69/// When dragging with only one finger, there's no difference in behavior
70/// between all the settings.
71///
72/// Used by `DragGestureRecognizer.multitouchDragStrategy`.
73#[derive(Debug, Clone, Copy, PartialEq, Eq)]
74pub enum MultitouchDragStrategy {
75    /// Only the latest active pointer is tracked by the recognizer.
76    ///
77    /// If the tracked pointer is released, the first accepted of the remaining active
78    /// pointers will continue to be tracked.
79    ///
80    /// This is the behavior typically seen on Android.
81    LatestPointer,
82
83    /// All active pointers will be tracked, and the result is computed from
84    /// the boundary pointers.
85    ///
86    /// The scrolling offset is determined by the maximum deltas of both directions.
87    ///
88    /// This is the behavior typically seen on iOS.
89    AverageBoundaryPointers,
90
91    /// All active pointers will be tracked together. The scrolling offset
92    /// is the sum of the offsets of all active pointers.
93    SumAllPointers,
94}
95
96/// The possible states of a `PrimaryPointerGestureRecognizer`.
97///
98/// The recognizer advances from [`Ready`](Self::Ready) to [`Possible`](Self::Possible) when it starts tracking a
99/// primary pointer. Where it advances from there depends on how the gesture is
100/// resolved for that pointer:
101///
102///  * If the primary pointer is resolved by the gesture winning the arena, the
103///    recognizer stays in the [`Possible`](Self::Possible) state as long as it continues to track
104///    a pointer.
105///  * If the primary pointer is resolved by the gesture being rejected and
106///    losing the arena, the recognizer's state advances to [`Defunct`](Self::Defunct).
107///
108/// Once the recognizer has stopped tracking any remaining pointers, the
109/// recognizer returns to [`Ready`](Self::Ready).
110#[derive(Debug, Clone, Copy, PartialEq, Eq)]
111pub enum GestureRecognizerState {
112    /// The recognizer is ready to start recognizing a gesture.
113    Ready,
114
115    /// The sequence of pointer events seen thus far is consistent with the
116    /// gesture the recognizer is attempting to recognize but the gesture has not
117    /// been accepted definitively.
118    Possible,
119
120    /// Further pointer events cannot cause this recognizer to recognize the
121    /// gesture until the recognizer returns to the [`Ready`](Self::Ready) state (typically when
122    /// all the pointers the recognizer is tracking are removed from the screen).
123    Defunct,
124}
125
126/// Data associated with a pointer event.
127///
128/// This is stored by `GestureRecognizer`s on a per-pointer basis.
129#[derive(Clone, Copy)]
130pub(crate) struct RecognizerEventData {
131    pub kind: PointerDeviceKind,
132    pub buttons: i64,
133}
134
135/// Field bag for Dart's `GestureRecognizer`, the base class that all gesture
136/// recognizers inherit from.
137///
138/// A leaf holds one and hands it out through [`RecognizerLeafData::recognizer`].
139pub struct GestureRecognizerData {
140    pub(crate) gesture_settings: Option<DeviceGestureSettings>,
141    pub(crate) supported_devices: Option<HashSet<PointerDeviceKind>>,
142    pub(crate) allowed_buttons_filter: AllowedButtonsFilter,
143    pub(crate) pointer_to_event_data: HashMap<i64, RecognizerEventData>,
144}
145
146impl GestureRecognizerData {
147    /// Initializes the gesture recognizer: every device kind is recognized, and
148    /// every input button is accepted.
149    pub fn new() -> GestureRecognizerData {
150        GestureRecognizerData {
151            gesture_settings: None,
152            supported_devices: None,
153            allowed_buttons_filter: Rc::new(default_button_accept_behavior),
154            pointer_to_event_data: HashMap::new(),
155        }
156    }
157}
158
159impl GestureRecognizerData {
160    /// Optional device specific configuration that takes precedence over framework defaults.
161    pub fn gesture_settings(&self) -> Option<DeviceGestureSettings> {
162        self.gesture_settings
163    }
164
165    /// Sets [`gesture_settings`](Self::gesture_settings).
166    pub fn set_gesture_settings(&mut self, settings: Option<DeviceGestureSettings>) {
167        self.gesture_settings = settings;
168    }
169
170    /// Called when interaction starts; limits the buttons this recognizer accepts.
171    pub fn allowed_buttons_filter(&self) -> &AllowedButtonsFilter {
172        &self.allowed_buttons_filter
173    }
174
175    /// Sets [`allowed_buttons_filter`](Self::allowed_buttons_filter).
176    pub fn set_allowed_buttons_filter(&mut self, filter: AllowedButtonsFilter) {
177        self.allowed_buttons_filter = filter;
178    }
179}
180
181impl Default for GestureRecognizerData {
182    fn default() -> GestureRecognizerData {
183        GestureRecognizerData::new()
184    }
185}
186
187/// Field bag for Dart's `OneSequenceGestureRecognizer`, the base class for
188/// gesture recognizers that can only recognize one gesture at a time.
189///
190/// A leaf holds one and hands it out through [`RecognizerLeafData::one_sequence`].
191pub struct OneSequenceData {
192    pub(crate) entries: HashMap<i64, GestureArenaEntry>,
193    pub(crate) tracked_pointers: HashSet<i64>,
194    pub(crate) team: Option<Ref<GestureArenaTeam>>,
195}
196
197impl OneSequenceData {
198    /// Initializes the object: no arena entries, no tracked pointers, no team.
199    pub fn new() -> OneSequenceData {
200        OneSequenceData {
201            entries: HashMap::new(),
202            tracked_pointers: HashSet::new(),
203            team: None,
204        }
205    }
206}
207
208impl Default for OneSequenceData {
209    fn default() -> OneSequenceData {
210        OneSequenceData::new()
211    }
212}
213
214/// Field bag for Dart's `PrimaryPointerGestureRecognizer`, the base class for
215/// gesture recognizers that track a single primary pointer.
216///
217/// A leaf holds one and hands it out through [`PrimaryPointerLeafData::primary`].
218pub struct PrimaryPointerData {
219    pub(crate) deadline: Option<Duration>,
220    pub(crate) pre_accept_slop_tolerance: Option<f64>,
221    pub(crate) post_accept_slop_tolerance: Option<f64>,
222    pub(crate) state: GestureRecognizerState,
223    pub(crate) primary_pointer: Option<i64>,
224    pub(crate) initial_position: Option<OffsetPair>,
225    pub(crate) gesture_accepted: bool,
226    pub(crate) timer: Option<Timer>,
227    pub(crate) deadline_event: Option<crate::events::PointerDownEvent>,
228}
229
230impl PrimaryPointerData {
231    /// Initializes the `deadline` field during construction of a leaf.
232    ///
233    /// If `deadline` is non-null, the recognizer calls
234    /// [`PrimaryPointerLeaf::did_exceed_deadline`] after that amount of time has
235    /// elapsed since starting to track the primary pointer.
236    ///
237    /// A slop tolerance of [`UNSET_TOUCH_SLOP`] is Dart's omitted argument: the
238    /// tolerance then follows `gesture_settings.touch_slop`, falling back to
239    /// [`K_TOUCH_SLOP`](crate::K_TOUCH_SLOP). `None` lets the gesture drift any
240    /// distance.
241    pub fn new(
242        deadline: Option<Duration>,
243        pre_accept_slop_tolerance: Option<f64>,
244        post_accept_slop_tolerance: Option<f64>,
245    ) -> PrimaryPointerData {
246        debug_assert!(
247            pre_accept_slop_tolerance == Some(UNSET_TOUCH_SLOP)
248                || pre_accept_slop_tolerance.is_none()
249                || pre_accept_slop_tolerance.is_some_and(|value| value >= 0.0),
250            "The preAcceptSlopTolerance must be unspecified, positive, or null"
251        );
252        debug_assert!(
253            post_accept_slop_tolerance == Some(UNSET_TOUCH_SLOP)
254                || post_accept_slop_tolerance.is_none()
255                || post_accept_slop_tolerance.is_some_and(|value| value >= 0.0),
256            "The postAcceptSlopTolerance must be unspecified, positive, or null"
257        );
258        PrimaryPointerData {
259            deadline,
260            pre_accept_slop_tolerance,
261            post_accept_slop_tolerance,
262            state: GestureRecognizerState::Ready,
263            primary_pointer: None,
264            initial_position: None,
265            gesture_accepted: false,
266            timer: None,
267            deadline_event: None,
268        }
269    }
270
271    /// The ID of the primary pointer this recognizer is tracking.
272    ///
273    /// If this recognizer is no longer tracking any pointers, this field holds
274    /// the ID of the primary pointer this recognizer was most recently tracking.
275    /// This enables the recognizer to know which pointer it was most recently
276    /// tracking when `accept_gesture` or `reject_gesture` is called (which may be
277    /// called after the recognizer is no longer tracking a pointer if, e.g.
278    /// `GestureArenaManager::hold` has been called, or if there are other
279    /// recognizers keeping the arena open).
280    pub fn primary_pointer(&self) -> Option<i64> {
281        self.primary_pointer
282    }
283}
284
285/// A container for a [`local`](Self::local) and [`global`](Self::global) [`Offset`] pair.
286///
287/// Usually, the [`global`](Self::global) [`Offset`] is in the coordinate space of the screen
288/// after conversion to logical pixels and the [`local`](Self::local) offset is the same
289/// [`Offset`], but transformed to a local coordinate space.
290#[derive(Clone, Copy, Debug)]
291pub struct OffsetPair {
292    /// The [`Offset`] in the local coordinate space.
293    pub local: Offset,
294
295    /// The [`Offset`] in the global coordinate space after conversion to logical
296    /// pixels.
297    pub global: Offset,
298}
299
300impl OffsetPair {
301    /// A [`OffsetPair`] where both [`Offset`]s are [`Offset::ZERO`].
302    pub const ZERO: OffsetPair = OffsetPair {
303        local: Offset::ZERO,
304        global: Offset::ZERO,
305    };
306
307    /// Creates a [`OffsetPair`] combining a [`local`](Self::local) and [`global`](Self::global) [`Offset`].
308    pub const fn new(local: Offset, global: Offset) -> OffsetPair {
309        OffsetPair { local, global }
310    }
311
312    /// Creates a [`OffsetPair`] from [`PointerEvent::local_position`] and
313    /// [`PointerEvent::position`].
314    pub fn from_event_position(event: &PointerEvent) -> OffsetPair {
315        OffsetPair {
316            local: event.local_position(),
317            global: event.position(),
318        }
319    }
320
321    /// Creates a [`OffsetPair`] from [`PointerEvent::local_delta`] and
322    /// [`PointerEvent::delta`].
323    pub fn from_event_delta(event: &PointerEvent) -> OffsetPair {
324        OffsetPair {
325            local: event.local_delta(),
326            global: event.delta(),
327        }
328    }
329}
330
331impl std::ops::Add for OffsetPair {
332    type Output = OffsetPair;
333
334    fn add(self, other: OffsetPair) -> OffsetPair {
335        OffsetPair {
336            local: self.local + other.local,
337            global: self.global + other.global,
338        }
339    }
340}
341
342impl std::ops::Sub for OffsetPair {
343    type Output = OffsetPair;
344
345    fn sub(self, other: OffsetPair) -> OffsetPair {
346        OffsetPair {
347            local: self.local - other.local,
348            global: self.global - other.global,
349        }
350    }
351}
352
353impl fmt::Display for OffsetPair {
354    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
355        write!(
356            f,
357            "OffsetPair(local: {:?}, global: {:?})",
358            self.local, self.global
359        )
360    }
361}
362
363/// Superclass fields on every `GestureRecognizer` leaf.
364pub trait RecognizerLeafData {
365    /// The leaf's [`GestureRecognizer`] bag.
366    fn recognizer(&self) -> &GestureRecognizerData;
367
368    /// The leaf's [`GestureRecognizer`] bag, mutably.
369    fn recognizer_mut(&mut self) -> &mut GestureRecognizerData;
370}
371
372/// The extra field bag carried by `OneSequenceGestureRecognizer` leaves.
373pub trait OneSequenceLeafData: RecognizerLeafData {
374    /// The leaf's [`OneSequenceGestureRecognizer`] bag.
375    fn one_sequence(&self) -> &OneSequenceData;
376
377    /// The leaf's [`OneSequenceGestureRecognizer`] bag, mutably.
378    fn one_sequence_mut(&mut self) -> &mut OneSequenceData;
379}
380
381/// The extra field bag a [`PrimaryPointerGestureRecognizer`] leaf carries.
382pub trait PrimaryPointerLeafData: OneSequenceLeafData {
383    /// The leaf's [`PrimaryPointerGestureRecognizer`] bag.
384    fn primary(&self) -> &PrimaryPointerData;
385
386    /// The leaf's [`PrimaryPointerGestureRecognizer`] bag, mutably.
387    fn primary_mut(&mut self) -> &mut PrimaryPointerData;
388}
389
390/// Virtuals a superclass body calls on the leaf. Defaults match `GestureRecognizer`;
391/// leaves forward inherited overrides to their immediate superclass.
392///
393/// A leaf competes in the arena as its `Handle`: see the [`GestureArenaMember`]
394/// impl below.
395pub trait RecognizerLeaf: RecognizerLeafData + Sized + 'static {
396    /// The route registered per tracked pointer. A distinct fn item per leaf, so
397    /// the `TypeId` matches on remove.
398    fn handle_event_route(self: Handle<Self>, app: &mut App, event: PointerEvent) {
399        self.handle_event(app, event);
400    }
401
402    /// Registers a new pointer that might be relevant to this gesture recognizer.
403    ///
404    /// This is called for each and all pointers being added. A leaf that only
405    /// cares about the pointers it accepts overrides
406    /// [`add_allowed_pointer`](Self::add_allowed_pointer) instead.
407    fn add_pointer(self: Handle<Self>, app: &mut App, event: PointerDownEvent) {
408        GestureRecognizer::add_pointer(self, app, event);
409    }
410
411    /// Registers a new pointer pan/zoom that might be relevant to this gesture
412    /// recognizer.
413    fn add_pointer_pan_zoom(
414        self: Handle<Self>,
415        app: &mut App,
416        event: crate::events::PointerPanZoomStartEvent,
417    ) {
418        GestureRecognizer::add_pointer_pan_zoom(self, app, event);
419    }
420
421    /// Registers a new pointer that's been checked to be allowed by this gesture
422    /// recognizer.
423    ///
424    /// Override this instead of [`add_pointer`](Self::add_pointer), which is
425    /// called for each and all pointers being added.
426    fn add_allowed_pointer(self: Handle<Self>, _app: &mut App, _event: PointerDownEvent) {}
427
428    /// Registers a new pointer pan/zoom that's been checked to be allowed by this
429    /// gesture recognizer.
430    fn add_allowed_pointer_pan_zoom(
431        self: Handle<Self>,
432        _app: &mut App,
433        _event: crate::events::PointerPanZoomStartEvent,
434    ) {
435    }
436
437    /// Handles a pointer being added that's not allowed by this recognizer.
438    fn handle_non_allowed_pointer(self: Handle<Self>, _app: &mut App, _event: &PointerDownEvent) {}
439
440    /// Handles a pointer pan/zoom being added that's not allowed by this
441    /// recognizer.
442    fn handle_non_allowed_pointer_pan_zoom(
443        self: Handle<Self>,
444        _app: &mut App,
445        _event: &crate::events::PointerPanZoomStartEvent,
446    ) {
447    }
448
449    /// Checks whether or not a pointer is allowed to be tracked by this
450    /// recognizer.
451    fn is_pointer_allowed(self: Handle<Self>, app: &App, event: &PointerDownEvent) -> bool {
452        GestureRecognizer::is_pointer_allowed(self, app, event)
453    }
454
455    /// Checks whether or not a pointer pan/zoom is allowed to be tracked by this
456    /// recognizer.
457    fn is_pointer_pan_zoom_allowed(
458        self: Handle<Self>,
459        app: &App,
460        event: &crate::events::PointerPanZoomStartEvent,
461    ) -> bool {
462        GestureRecognizer::is_pointer_pan_zoom_allowed(self, app, event)
463    }
464
465    /// Causes events related to the given pointer ID to be routed to this
466    /// recognizer.
467    fn start_tracking_pointer(
468        self: Handle<Self>,
469        app: &mut App,
470        pointer: i64,
471        transform: Option<Matrix4>,
472    ) where
473        Self: OneSequenceLeafData,
474    {
475        OneSequenceGestureRecognizer::start_tracking_pointer(self, app, pointer, transform);
476    }
477
478    /// Called when a pointer event is routed to this recognizer.
479    fn handle_event(self: Handle<Self>, app: &mut App, event: PointerEvent);
480
481    /// Called when this member wins the arena for the given pointer id.
482    fn accept_gesture(self: Handle<Self>, _app: &mut App, _pointer: i64) {}
483
484    /// Called when this member loses the arena for the given pointer id.
485    fn reject_gesture(self: Handle<Self>, _app: &mut App, _pointer: i64) {}
486
487    /// Called when the number of pointers this recognizer is tracking changes
488    /// from one to zero.
489    fn did_stop_tracking_last_pointer(self: Handle<Self>, _app: &mut App, _pointer: i64) {}
490
491    /// Resolves this recognizer's participation in each gesture arena with the
492    /// given disposition.
493    fn resolve(self: Handle<Self>, app: &mut App, disposition: GestureDisposition)
494    where
495        Self: OneSequenceLeafData,
496    {
497        OneSequenceGestureRecognizer::resolve(self, app, disposition);
498    }
499
500    /// Releases any resources used by the object.
501    fn dispose(self: Handle<Self>, app: &mut App) {
502        GestureRecognizer::dispose(self, app);
503    }
504
505    /// Returns a very short pretty description of the gesture that the
506    /// recognizer looks for.
507    fn debug_description(self: Handle<Self>) -> &'static str;
508}
509
510/// Virtuals [`PrimaryPointerGestureRecognizer`]'s bodies call on its leaves.
511pub trait PrimaryPointerLeaf: RecognizerLeaf + PrimaryPointerLeafData {
512    /// The deadline timer's callback. A distinct fn item per leaf.
513    fn deadline_fired(self: Handle<Self>, app: &mut App) {
514        self.did_exceed_deadline_with_event(app);
515    }
516
517    /// Override to provide behavior for the primary pointer when the gesture is
518    /// still possible.
519    fn handle_primary_pointer(self: Handle<Self>, app: &mut App, event: PointerEvent);
520
521    /// Override to be notified when the deadline is exceeded.
522    ///
523    /// You must override this method or [`did_exceed_deadline_with_event`](Self::did_exceed_deadline_with_event)
524    /// if you supply a deadline. An override must _not_ call this body.
525    fn did_exceed_deadline(self: Handle<Self>, app: &mut App) {
526        debug_assert!(
527            app.get(self).primary().deadline.is_none(),
528            "must override didExceedDeadline if deadline is set"
529        );
530    }
531
532    /// Same as [`did_exceed_deadline`](Self::did_exceed_deadline), for the down
533    /// event that initiated the gesture.
534    ///
535    /// You must override this method or [`did_exceed_deadline`](Self::did_exceed_deadline)
536    /// if you supply a deadline. An override must _not_ call this body.
537    fn did_exceed_deadline_with_event(self: Handle<Self>, app: &mut App) {
538        PrimaryPointerGestureRecognizer::did_exceed_deadline_with_event(self, app);
539    }
540}
541
542/// Dart's `GestureRecognizer extends GestureArenaMember`: every leaf competes in
543/// the arena as its `Handle`, and its identity is the handle.
544impl<R: RecognizerLeaf> GestureArenaMember for Handle<R> {
545    fn accept_gesture(&self, app: &mut App, pointer: i64) {
546        R::accept_gesture(*self, app, pointer);
547    }
548
549    fn reject_gesture(&self, app: &mut App, pointer: i64) {
550        R::reject_gesture(*self, app, pointer);
551    }
552
553    fn member_id(&self) -> HandleId {
554        self.id()
555    }
556}
557
558/// A concrete recognizer: the bound Dart writes as `T extends GestureRecognizer`.
559///
560/// Every leaf ([`TapGestureRecognizer`](crate::TapGestureRecognizer),
561/// [`LongPressGestureRecognizer`](crate::LongPressGestureRecognizer)) implements it. It hands
562/// out the erased [`AnyGestureRecognizer`] that a field Dart types as `GestureRecognizer`
563/// holds.
564pub trait GestureRecognizerLeaf: Sized + 'static {
565    /// This recognizer as the erased [`AnyGestureRecognizer`] — what to pass where a Dart
566    /// API takes a `GestureRecognizer`.
567    ///
568    /// The object is untouched; this mints an erased second handle to it, so concrete
569    /// members stay reachable through the typed one.
570    fn as_recognizer(self: Handle<Self>) -> AnyGestureRecognizer;
571}
572
573/// A field Dart types as `GestureRecognizer`, kept: the erased recognizer with its count.
574pub type RecognizerRef = Retained<AnyGestureRecognizer>;
575
576waft_foundation::erased_handle!(AnyGestureRecognizer: GestureRecognizerLeaf => GestureRecognizerLeaf::as_recognizer);
577
578impl<R: RecognizerLeaf> GestureRecognizerLeaf for R {
579    fn as_recognizer(self: Handle<Self>) -> AnyGestureRecognizer {
580        AnyGestureRecognizer {
581            id: self.id(),
582            vtable: const { &GestureRecognizerVTable::of::<R>() },
583        }
584    }
585}
586
587/// The vtable of an erased [`AnyGestureRecognizer`]: one `&'static` table per leaf type,
588/// built by [`GestureRecognizerVTable::of`]. Copied out of the handle before a virtual call,
589/// so the slot is not borrowed across it.
590pub(crate) struct GestureRecognizerVTable {
591    type_id: fn() -> TypeId,
592    type_name: fn() -> &'static str,
593    add_pointer: fn(&mut App, HandleId, PointerDownEvent),
594    add_pointer_pan_zoom: fn(&mut App, HandleId, PointerPanZoomStartEvent),
595    is_pointer_allowed: fn(&App, HandleId, &PointerDownEvent) -> bool,
596    is_pointer_pan_zoom_allowed: fn(&App, HandleId, &PointerPanZoomStartEvent) -> bool,
597    dispose: fn(&mut App, HandleId),
598    set_gesture_settings: fn(&mut App, HandleId, Option<DeviceGestureSettings>),
599    debug_description: fn(HandleId) -> &'static str,
600}
601
602/// The typed handle for an erased id. Free: nothing is looked up; `get` checks the slot.
603fn resolve<R: 'static>(id: HandleId) -> Handle<R> {
604    Handle::from_id(id)
605}
606
607impl GestureRecognizerVTable {
608    /// The table for one leaf type.
609    const fn of<R: RecognizerLeaf>() -> GestureRecognizerVTable {
610        GestureRecognizerVTable {
611            type_id: TypeId::of::<R>,
612            type_name: std::any::type_name::<R>,
613            add_pointer: |app, id, event| R::add_pointer(resolve::<R>(id), app, event),
614            add_pointer_pan_zoom: |app, id, event| {
615                R::add_pointer_pan_zoom(resolve::<R>(id), app, event)
616            },
617            is_pointer_allowed: |app, id, event| R::is_pointer_allowed(resolve(id), app, event),
618            is_pointer_pan_zoom_allowed: |app, id, event| {
619                R::is_pointer_pan_zoom_allowed(resolve(id), app, event)
620            },
621            dispose: |app, id| R::dispose(resolve(id), app),
622            set_gesture_settings: |app, id, value| {
623                app.get_mut(resolve::<R>(id))
624                    .recognizer_mut()
625                    .set_gesture_settings(value)
626            },
627            debug_description: |id| R::debug_description(resolve(id)),
628        }
629    }
630}
631
632/// Erased `GestureRecognizer`: one identity and a static vtable, the fat pointer rustc
633/// cannot build for an arena id. No lease.
634///
635/// This is what a field Dart types as `GestureRecognizer` becomes. The leaf stays in the
636/// [`App`] under its own type; [`downcast`](Self::downcast) gets the typed handle back, and
637/// [`type_id`](Self::type_id) is Dart's `runtimeType`.
638///
639/// Equality is Dart's `==` on an object reference.
640#[derive(Clone, Copy)]
641pub struct AnyGestureRecognizer {
642    id: HandleId,
643    vtable: &'static GestureRecognizerVTable,
644}
645
646impl fmt::Debug for AnyGestureRecognizer {
647    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
648        write!(f, "{}({:?})", (self.vtable.type_name)(), self.id)
649    }
650}
651
652impl AnyGestureRecognizer {
653    /// The arena id behind this handle.
654    pub fn id(self) -> HandleId {
655        self.id
656    }
657
658    /// Dart's `runtimeType`: the leaf type this handle was minted from.
659    pub fn type_id(self) -> TypeId {
660        (self.vtable.type_id)()
661    }
662
663    /// Dart's `runtimeType.toString()`: the leaf type's name.
664    pub fn type_name(self) -> &'static str {
665        bare_type_name((self.vtable.type_name)())
666    }
667
668    /// Dart's `recognizer as T`: the typed handle when this recognizer is a `T`, else `None`.
669    pub fn downcast<T: 'static>(self, app: &App) -> Option<Handle<T>> {
670        app.handle::<T>(self.id)
671    }
672
673    /// Optional device-specific configuration for device gestures.
674    pub fn set_gesture_settings(self, app: &mut App, value: Option<DeviceGestureSettings>) {
675        (self.vtable.set_gesture_settings)(app, self.id, value);
676    }
677
678    /// Registers a new pointer that might be relevant to this gesture detector.
679    ///
680    /// The owner of this gesture recognizer calls `add_pointer` with the
681    /// [`PointerDownEvent`] of each pointer that should be considered for this gesture.
682    pub fn add_pointer(self, app: &mut App, event: &PointerDownEvent) {
683        (self.vtable.add_pointer)(app, self.id, event.clone());
684    }
685
686    /// Registers a new pointer pan/zoom that might be relevant to this gesture detector.
687    pub fn add_pointer_pan_zoom(self, app: &mut App, event: &PointerPanZoomStartEvent) {
688        (self.vtable.add_pointer_pan_zoom)(app, self.id, event.clone());
689    }
690
691    /// Checks whether or not a pointer is allowed to be tracked by this recognizer.
692    pub fn is_pointer_allowed(self, app: &App, event: &PointerDownEvent) -> bool {
693        (self.vtable.is_pointer_allowed)(app, self.id, event)
694    }
695
696    /// Checks whether or not a pointer pan/zoom is allowed to be tracked by this recognizer.
697    pub fn is_pointer_pan_zoom_allowed(self, app: &App, event: &PointerPanZoomStartEvent) -> bool {
698        (self.vtable.is_pointer_pan_zoom_allowed)(app, self.id, event)
699    }
700
701    /// Releases any resources used by the object and frees its arena slot. Every handle to it
702    /// is stale afterwards.
703    pub fn dispose(self, app: &mut App) {
704        (self.vtable.dispose)(app, self.id);
705    }
706
707    /// Returns a very short pretty description of the gesture that the recognizer looks for.
708    pub fn debug_description(self) -> &'static str {
709        (self.vtable.debug_description)(self.id)
710    }
711}
712
713/// Dart's `GestureRecognizer`: the base class that all gesture recognizers
714/// inherit from.
715///
716/// Its bodies are associated fns taking the leaf's `Handle`; a leaf's override
717/// calls one where Dart writes `super`. Its fields are [`GestureRecognizerData`].
718pub struct GestureRecognizer;
719
720impl GestureRecognizer {
721    /// Registers a new pointer pan/zoom that might be relevant to this gesture
722    /// detector.
723    ///
724    /// A pointer pan/zoom is a stream of events that conveys data covering pan,
725    /// zoom, and rotate data from a multi-finger trackpad gesture.
726    ///
727    /// This is called for each and all pointers being added. In most cases, a leaf
728    /// overrides [`RecognizerLeaf::add_allowed_pointer_pan_zoom`] instead.
729    pub fn add_pointer_pan_zoom<R: RecognizerLeaf>(
730        this: Handle<R>,
731        app: &mut App,
732        event: crate::events::PointerPanZoomStartEvent,
733    ) {
734        app.get_mut(this)
735            .recognizer_mut()
736            .pointer_to_event_data
737            .insert(
738                event.pointer,
739                RecognizerEventData {
740                    kind: event.kind,
741                    buttons: event.buttons,
742                },
743            );
744        if this.is_pointer_pan_zoom_allowed(app, &event) {
745            this.add_allowed_pointer_pan_zoom(app, event);
746        } else {
747            this.handle_non_allowed_pointer_pan_zoom(app, &event);
748        }
749    }
750
751    /// Registers a new pointer that might be relevant to this gesture detector.
752    ///
753    /// The owner of this gesture recognizer calls it with the [`PointerDownEvent`]
754    /// of each pointer that should be considered for this gesture.
755    ///
756    /// This is called for each and all pointers being added. In most cases, a leaf
757    /// overrides [`RecognizerLeaf::add_allowed_pointer`] instead.
758    pub fn add_pointer<R: RecognizerLeaf>(this: Handle<R>, app: &mut App, event: PointerDownEvent) {
759        app.get_mut(this)
760            .recognizer_mut()
761            .pointer_to_event_data
762            .insert(
763                event.pointer,
764                RecognizerEventData {
765                    kind: event.kind,
766                    buttons: event.buttons,
767                },
768            );
769        if this.is_pointer_allowed(app, &event) {
770            this.add_allowed_pointer(app, event);
771        } else {
772            this.handle_non_allowed_pointer(app, &event);
773        }
774    }
775
776    /// Checks whether or not a pointer is allowed to be tracked by this
777    /// recognizer.
778    pub fn is_pointer_allowed<R: RecognizerLeaf>(
779        this: Handle<R>,
780        app: &App,
781        event: &PointerDownEvent,
782    ) -> bool {
783        let devices = app.get(this).recognizer().supported_devices.clone();
784        let filter = Rc::clone(&app.get(this).recognizer().allowed_buttons_filter);
785        (devices.is_none()
786            || devices
787                .as_ref()
788                .is_some_and(|set| set.contains(&event.kind)))
789            && filter(event.buttons)
790    }
791
792    /// Checks whether or not a pointer pan/zoom is allowed to be tracked by this
793    /// recognizer.
794    pub fn is_pointer_pan_zoom_allowed<R: RecognizerLeaf>(
795        this: Handle<R>,
796        app: &App,
797        event: &crate::events::PointerPanZoomStartEvent,
798    ) -> bool {
799        let devices = app.get(this).recognizer().supported_devices.clone();
800        devices.is_none()
801            || devices
802                .as_ref()
803                .is_some_and(|set| set.contains(&event.kind))
804    }
805
806    /// For a given pointer ID, returns the device kind associated with it.
807    ///
808    /// The pointer ID is expected to be a valid one, i.e. an event was received
809    /// with that pointer ID.
810    pub fn kind_for_pointer<R: RecognizerLeaf>(
811        this: Handle<R>,
812        app: &App,
813        pointer: i64,
814    ) -> PointerDeviceKind {
815        let data = &app.get(this).recognizer().pointer_to_event_data;
816        debug_assert!(data.contains_key(&pointer));
817        data[&pointer].kind
818    }
819
820    /// For a given pointer ID, returns the buttons associated with it.
821    ///
822    /// The pointer ID is expected to be valid, meaning an event related to it has
823    /// been received.
824    pub fn buttons_for_pointer<R: RecognizerLeaf>(this: Handle<R>, app: &App, pointer: i64) -> i64 {
825        let data = &app.get(this).recognizer().pointer_to_event_data;
826        debug_assert!(data.contains_key(&pointer));
827        data[&pointer].buttons
828    }
829
830    /// Releases any resources used by the object.
831    ///
832    /// Dart's body is a diagnostics assert; the object stays readable while something keeps it.
833    pub fn dispose<R: RecognizerLeaf>(this: Handle<R>, app: &mut App) {
834        app.mark_disposed(this);
835    }
836
837    /// Invoke a callback provided by the application.
838    ///
839    /// The `name` argument is ignored except when
840    /// [`debug_print_recognizer_callbacks_trace`](crate::debug_print_recognizer_callbacks_trace)
841    /// is true.
842    pub fn invoke_callback<R: RecognizerLeaf, T>(
843        this: Handle<R>,
844        app: &mut App,
845        name: &str,
846        callback: impl FnOnce(&mut App) -> T,
847    ) -> Option<T> {
848        if cfg!(debug_assertions) && debug_print_recognizer_callbacks_trace() {
849            let prefix = if debug_print_gesture_arena_diagnostics() {
850                format!("{}❙ ", " ".repeat(19))
851            } else {
852                String::new()
853            };
854            eprintln!("{prefix}{this:?} calling {name} callback.");
855        }
856        Some(callback(app))
857    }
858}
859
860/// Dart's `OneSequenceGestureRecognizer`: the base class for gesture recognizers
861/// that can only recognize one gesture at a time.
862///
863/// Its bodies are associated fns taking the leaf's `Handle`; a leaf's override
864/// calls one where Dart writes `super`. Its fields are [`OneSequenceData`].
865pub struct OneSequenceGestureRecognizer;
866
867impl OneSequenceGestureRecognizer {
868    /// Starts tracking the pointer of the given down event.
869    pub fn add_allowed_pointer<R: RecognizerLeaf + OneSequenceLeafData>(
870        this: Handle<R>,
871        app: &mut App,
872        event: &PointerDownEvent,
873    ) {
874        this.start_tracking_pointer(app, event.pointer, event.transform);
875    }
876
877    /// Rejects the gesture in every arena this recognizer takes part in.
878    pub fn handle_non_allowed_pointer<R: RecognizerLeaf + OneSequenceLeafData>(
879        this: Handle<R>,
880        app: &mut App,
881    ) {
882        this.resolve(app, GestureDisposition::Rejected);
883    }
884
885    /// Resolves this recognizer's participation in each gesture arena with the
886    /// given disposition.
887    pub fn resolve<R: RecognizerLeaf + OneSequenceLeafData>(
888        this: Handle<R>,
889        app: &mut App,
890        disposition: GestureDisposition,
891    ) {
892        let local_entries: Vec<GestureArenaEntry> = app
893            .get(this)
894            .one_sequence()
895            .entries
896            .values()
897            .cloned()
898            .collect();
899        app.get_mut(this).one_sequence_mut().entries.clear();
900        for entry in local_entries {
901            entry.resolve(app, disposition);
902        }
903    }
904
905    /// Resolves this recognizer's participation in the given gesture arena with
906    /// the given disposition.
907    pub fn resolve_pointer<R: RecognizerLeaf + OneSequenceLeafData>(
908        this: Handle<R>,
909        app: &mut App,
910        pointer: i64,
911        disposition: GestureDisposition,
912    ) {
913        let entry = app
914            .get_mut(this)
915            .one_sequence_mut()
916            .entries
917            .remove(&pointer);
918        if let Some(entry) = entry {
919            entry.resolve(app, disposition);
920        }
921    }
922
923    /// Rejects every arena this recognizer takes part in, drops its routes, then
924    /// runs [`GestureRecognizer::dispose`].
925    pub fn dispose<R: RecognizerLeaf + OneSequenceLeafData>(this: Handle<R>, app: &mut App) {
926        this.resolve(app, GestureDisposition::Rejected);
927        let pointers: Vec<i64> = app
928            .get(this)
929            .one_sequence()
930            .tracked_pointers
931            .iter()
932            .copied()
933            .collect();
934        let router = GestureBinding::instance(app).pointer_router(app);
935        for pointer in pointers {
936            router.remove_route(
937                app,
938                pointer,
939                &PointerRoute::handle_method(this, R::handle_event_route),
940            );
941        }
942        app.get_mut(this)
943            .one_sequence_mut()
944            .tracked_pointers
945            .clear();
946        debug_assert!(app.get(this).one_sequence().entries.is_empty());
947        GestureRecognizer::dispose(this, app);
948    }
949
950    pub(crate) fn add_pointer_to_arena<R: RecognizerLeaf + OneSequenceLeafData>(
951        this: Handle<R>,
952        app: &mut App,
953        pointer: i64,
954    ) -> GestureArenaEntry {
955        let team = app.get(this).one_sequence().team.handle();
956        if let Some(team) = team {
957            team.add(app, pointer, this)
958        } else {
959            GestureBinding::instance(app)
960                .gesture_arena(app)
961                .add(app, pointer, this)
962        }
963    }
964
965    /// Causes events related to the given pointer ID to be routed to this
966    /// recognizer, and adds it (or its team) to that pointer's gesture arena.
967    ///
968    /// The pointer events are transformed according to `transform` and then
969    /// delivered to [`RecognizerLeaf::handle_event`]. Use
970    /// [`stop_tracking_pointer`](Self::stop_tracking_pointer) to remove the route.
971    pub fn start_tracking_pointer<R: RecognizerLeaf + OneSequenceLeafData>(
972        this: Handle<R>,
973        app: &mut App,
974        pointer: i64,
975        transform: Option<Matrix4>,
976    ) {
977        let router = GestureBinding::instance(app).pointer_router(app);
978        router.add_route(
979            app,
980            pointer,
981            PointerRoute::handle_method(this, R::handle_event_route),
982            transform,
983        );
984        app.get_mut(this)
985            .one_sequence_mut()
986            .tracked_pointers
987            .insert(pointer);
988        let entry = Self::add_pointer_to_arena(this, app, pointer);
989        app.get_mut(this)
990            .one_sequence_mut()
991            .entries
992            .insert(pointer, entry);
993    }
994
995    /// Stops events related to the given pointer ID from being routed to this
996    /// recognizer.
997    ///
998    /// If this reduces the number of tracked pointers to zero, it calls
999    /// [`RecognizerLeaf::did_stop_tracking_last_pointer`] synchronously.
1000    pub fn stop_tracking_pointer<R: RecognizerLeaf + OneSequenceLeafData>(
1001        this: Handle<R>,
1002        app: &mut App,
1003        pointer: i64,
1004    ) {
1005        if app
1006            .get(this)
1007            .one_sequence()
1008            .tracked_pointers
1009            .contains(&pointer)
1010        {
1011            let router = GestureBinding::instance(app).pointer_router(app);
1012            router.remove_route(
1013                app,
1014                pointer,
1015                &PointerRoute::handle_method(this, R::handle_event_route),
1016            );
1017            app.get_mut(this)
1018                .one_sequence_mut()
1019                .tracked_pointers
1020                .remove(&pointer);
1021            if app.get(this).one_sequence().tracked_pointers.is_empty() {
1022                this.did_stop_tracking_last_pointer(app, pointer);
1023            }
1024        }
1025    }
1026
1027    /// Stops tracking the pointer associated with the given event if the event is
1028    /// a [`PointerUpEvent`](crate::PointerUpEvent), a
1029    /// [`PointerCancelEvent`](crate::PointerCancelEvent) or a
1030    /// [`PointerPanZoomEndEvent`](crate::PointerPanZoomEndEvent).
1031    pub fn stop_tracking_if_pointer_no_longer_down<R: RecognizerLeaf + OneSequenceLeafData>(
1032        this: Handle<R>,
1033        app: &mut App,
1034        event: &PointerEvent,
1035    ) {
1036        if matches!(
1037            event,
1038            PointerEvent::Up(_) | PointerEvent::Cancel(_) | PointerEvent::PanZoomEnd(_)
1039        ) {
1040            Self::stop_tracking_pointer(this, app, event.pointer());
1041        }
1042    }
1043}
1044
1045/// Dart's `PrimaryPointerGestureRecognizer`: the base class for gesture
1046/// recognizers that track a single primary pointer.
1047///
1048/// Gestures based on it stop tracking the gesture if the primary pointer travels
1049/// beyond [`pre_accept_slop_tolerance`](Self::pre_accept_slop_tolerance) or
1050/// [`post_accept_slop_tolerance`](Self::post_accept_slop_tolerance) pixels from
1051/// the original contact point. If the pre-accept tolerance was breached before
1052/// the gesture was accepted in the gesture arena, the gesture is rejected.
1053///
1054/// Its bodies are associated fns taking the leaf's `Handle`; a leaf's override
1055/// calls one where Dart writes `super`. Its fields are [`PrimaryPointerData`].
1056pub struct PrimaryPointerGestureRecognizer;
1057
1058impl PrimaryPointerGestureRecognizer {
1059    /// Starts tracking the pointer, and if the recognizer is
1060    /// [`Ready`](GestureRecognizerState::Ready), makes it the primary pointer and
1061    /// arms the deadline timer.
1062    pub fn add_allowed_pointer<R: PrimaryPointerLeaf>(
1063        this: Handle<R>,
1064        app: &mut App,
1065        event: PointerDownEvent,
1066    ) {
1067        OneSequenceGestureRecognizer::add_allowed_pointer(this, app, &event);
1068        if app.get(this).primary().state == GestureRecognizerState::Ready {
1069            app.get_mut(this).primary_mut().state = GestureRecognizerState::Possible;
1070            app.get_mut(this).primary_mut().primary_pointer = Some(event.pointer);
1071            app.get_mut(this).primary_mut().initial_position =
1072                Some(OffsetPair::new(event.local_position(), event.position));
1073            let deadline = app.get(this).primary().deadline;
1074            if let Some(deadline) = deadline {
1075                app.get_mut(this).primary_mut().deadline_event = Some(event);
1076                let timer = Timer::new(
1077                    app,
1078                    deadline,
1079                    Listener::handle_method(this, R::deadline_fired),
1080                );
1081                app.get_mut(this).primary_mut().timer = Some(timer);
1082            }
1083        }
1084    }
1085
1086    /// Rejects the gesture unless it has already been accepted.
1087    pub fn handle_non_allowed_pointer<R: PrimaryPointerLeaf>(
1088        this: Handle<R>,
1089        app: &mut App,
1090        _event: &PointerDownEvent,
1091    ) {
1092        if !app.get(this).primary().gesture_accepted {
1093            OneSequenceGestureRecognizer::handle_non_allowed_pointer(this, app);
1094        }
1095    }
1096
1097    /// Rejects the gesture once the primary pointer drifts past the slop
1098    /// tolerance, and otherwise hands the event to
1099    /// [`PrimaryPointerLeaf::handle_primary_pointer`].
1100    pub fn handle_event<R: PrimaryPointerLeaf>(
1101        this: Handle<R>,
1102        app: &mut App,
1103        event: PointerEvent,
1104    ) {
1105        debug_assert!(app.get(this).primary().state != GestureRecognizerState::Ready);
1106        let primary = app.get(this).primary().primary_pointer;
1107        if app.get(this).primary().state == GestureRecognizerState::Possible
1108            && Some(event.pointer()) == primary
1109        {
1110            let gesture_accepted = app.get(this).primary().gesture_accepted;
1111            let pre = Self::pre_accept_slop_tolerance(this, app);
1112            let post = Self::post_accept_slop_tolerance(this, app);
1113            let distance = Self::global_distance(this, app, &event);
1114            let is_pre_accept_slop_past_tolerance =
1115                !gesture_accepted && pre.is_some() && distance > pre.unwrap();
1116            let is_post_accept_slop_past_tolerance =
1117                gesture_accepted && post.is_some() && distance > post.unwrap();
1118            if matches!(event, PointerEvent::Move(_))
1119                && (is_pre_accept_slop_past_tolerance || is_post_accept_slop_past_tolerance)
1120            {
1121                this.resolve(app, GestureDisposition::Rejected);
1122                OneSequenceGestureRecognizer::stop_tracking_pointer(this, app, primary.unwrap());
1123            } else {
1124                this.handle_primary_pointer(app, event.clone());
1125            }
1126        }
1127        OneSequenceGestureRecognizer::stop_tracking_if_pointer_no_longer_down(this, app, &event);
1128    }
1129
1130    /// Calls [`PrimaryPointerLeaf::did_exceed_deadline`].
1131    pub fn did_exceed_deadline_with_event<R: PrimaryPointerLeaf>(this: Handle<R>, app: &mut App) {
1132        this.did_exceed_deadline(app);
1133    }
1134
1135    /// Stops the deadline timer and marks the gesture accepted when `pointer` is
1136    /// the primary pointer.
1137    pub fn accept_gesture<R: PrimaryPointerLeaf>(this: Handle<R>, app: &mut App, pointer: i64) {
1138        if Some(pointer) == app.get(this).primary().primary_pointer {
1139            Self::stop_timer(this, app);
1140            app.get_mut(this).primary_mut().gesture_accepted = true;
1141        }
1142    }
1143
1144    /// Stops the deadline timer and makes the recognizer
1145    /// [`Defunct`](GestureRecognizerState::Defunct) when `pointer` is the primary
1146    /// pointer of a still-possible gesture.
1147    pub fn reject_gesture<R: PrimaryPointerLeaf>(this: Handle<R>, app: &mut App, pointer: i64) {
1148        if Some(pointer) == app.get(this).primary().primary_pointer
1149            && app.get(this).primary().state == GestureRecognizerState::Possible
1150        {
1151            Self::stop_timer(this, app);
1152            app.get_mut(this).primary_mut().state = GestureRecognizerState::Defunct;
1153        }
1154    }
1155
1156    /// Returns the recognizer to the [`Ready`](GestureRecognizerState::Ready)
1157    /// state.
1158    pub fn did_stop_tracking_last_pointer<R: PrimaryPointerLeaf>(
1159        this: Handle<R>,
1160        app: &mut App,
1161        _pointer: i64,
1162    ) {
1163        debug_assert!(app.get(this).primary().state != GestureRecognizerState::Ready);
1164        Self::stop_timer(this, app);
1165        app.get_mut(this).primary_mut().state = GestureRecognizerState::Ready;
1166        app.get_mut(this).primary_mut().initial_position = None;
1167        app.get_mut(this).primary_mut().gesture_accepted = false;
1168    }
1169
1170    /// Stops the deadline timer, then runs
1171    /// [`OneSequenceGestureRecognizer::dispose`].
1172    pub fn dispose<R: PrimaryPointerLeaf>(this: Handle<R>, app: &mut App) {
1173        Self::stop_timer(this, app);
1174        OneSequenceGestureRecognizer::dispose(this, app);
1175    }
1176
1177    /// Cancels the deadline timer, if one is running.
1178    pub fn stop_timer<R: PrimaryPointerLeaf>(this: Handle<R>, app: &mut App) {
1179        if let Some(timer) = app.get_mut(this).primary_mut().timer.take() {
1180            timer.cancel(app);
1181        }
1182    }
1183
1184    /// The maximum distance in logical pixels the gesture is allowed to drift
1185    /// from the initial touch down position before the gesture is accepted.
1186    ///
1187    /// `None` means the gesture can drift for any distance.
1188    pub fn pre_accept_slop_tolerance<R: PrimaryPointerLeaf>(
1189        this: Handle<R>,
1190        app: &App,
1191    ) -> Option<f64> {
1192        let stored = app.get(this).primary().pre_accept_slop_tolerance;
1193        if stored == Some(UNSET_TOUCH_SLOP) {
1194            Some(Self::default_touch_slop(this, app))
1195        } else {
1196            stored
1197        }
1198    }
1199
1200    /// The maximum distance in logical pixels the gesture is allowed to drift
1201    /// after the gesture has been accepted.
1202    ///
1203    /// `None` means the gesture can drift for any distance.
1204    pub fn post_accept_slop_tolerance<R: PrimaryPointerLeaf>(
1205        this: Handle<R>,
1206        app: &App,
1207    ) -> Option<f64> {
1208        let stored = app.get(this).primary().post_accept_slop_tolerance;
1209        if stored == Some(UNSET_TOUCH_SLOP) {
1210            Some(Self::default_touch_slop(this, app))
1211        } else {
1212            stored
1213        }
1214    }
1215
1216    /// `gesture_settings.touch_slop`, falling back to
1217    /// [`K_TOUCH_SLOP`](crate::K_TOUCH_SLOP).
1218    pub fn default_touch_slop<R: PrimaryPointerLeaf>(this: Handle<R>, app: &App) -> f64 {
1219        app.get(this)
1220            .recognizer()
1221            .gesture_settings
1222            .and_then(|settings| settings.touch_slop)
1223            .unwrap_or(K_TOUCH_SLOP)
1224    }
1225
1226    /// How far the event is from the primary pointer's initial global position.
1227    pub fn global_distance<R: PrimaryPointerLeaf>(
1228        this: Handle<R>,
1229        app: &App,
1230        event: &PointerEvent,
1231    ) -> f64 {
1232        let initial = app.get(this).primary().initial_position.unwrap();
1233        (event.position() - initial.global).distance()
1234    }
1235}
1236
1237#[cfg(test)]
1238mod tests {
1239    use std::cell::Cell;
1240    use waft_foundation::AppCell;
1241
1242    use super::*;
1243    use waft_embedder::Offset;
1244
1245    use crate::events::{PointerDownEvent, PointerEvent};
1246    use crate::long_press::LongPressGestureRecognizer;
1247    use crate::tap::TapGestureRecognizer;
1248
1249    #[test]
1250    fn an_erased_recognizer_keeps_its_identity_and_type() {
1251        let cell = AppCell::new();
1252        let mut app = cell.borrow_mut();
1253        let tap = TapGestureRecognizer::new(&mut app);
1254        let long_press = LongPressGestureRecognizer::new(&mut app);
1255        let erased = tap.as_recognizer();
1256        assert_eq!(erased, tap.as_recognizer());
1257        assert_ne!(erased, long_press.as_recognizer());
1258        assert_eq!(erased.id(), tap.id());
1259        assert_eq!(erased.type_id(), TypeId::of::<TapGestureRecognizer>());
1260        assert_eq!(
1261            erased.downcast::<TapGestureRecognizer>(&app),
1262            Some(tap.handle())
1263        );
1264        assert_eq!(erased.downcast::<LongPressGestureRecognizer>(&app), None);
1265        assert_eq!(erased.debug_description(), "tap");
1266        assert_eq!(long_press.as_recognizer().debug_description(), "long press");
1267        assert!(format!("{erased:?}").contains("TapGestureRecognizer"));
1268    }
1269
1270    #[test]
1271    fn an_erased_recognizer_adds_pointers_and_the_last_ref_frees_the_slot() {
1272        let cell = AppCell::new();
1273        let mut app = cell.borrow_mut();
1274        let tap = TapGestureRecognizer::new(&mut app);
1275        let recognized = Rc::new(Cell::new(false));
1276        let flag = Rc::clone(&recognized);
1277        tap.set_on_tap(&mut app, Some(Listener::new(move |_app| flag.set(true))));
1278        let erased = tap.as_recognizer();
1279        let down = PointerDownEvent {
1280            pointer: 1,
1281            ..PointerDownEvent::default()
1282        };
1283        assert!(erased.is_pointer_allowed(&app, &down));
1284
1285        erased.add_pointer(&mut app, &down);
1286        let binding = GestureBinding::instance(&mut app);
1287        binding.gesture_arena(&app).close(&mut app, 1);
1288        app.drain_microtasks();
1289        binding.pointer_router(&app).route(
1290            &mut app,
1291            PointerEvent::Up(crate::events::PointerUpEvent {
1292                pointer: 1,
1293                ..crate::events::PointerUpEvent::default()
1294            }),
1295        );
1296        assert!(recognized.get());
1297
1298        erased.dispose(&mut app);
1299        assert!(app.is_disposed(erased.id()), "dispose frees nothing");
1300        drop(tap);
1301        drop(app);
1302        cell.checkpoint();
1303        assert!(!cell.borrow().contains(erased.id()), "the last ref did");
1304    }
1305
1306    #[test]
1307    fn from_event_position_and_delta_and_arithmetic() {
1308        let event = PointerEvent::Down(PointerDownEvent {
1309            position: Offset::new(10.0, 20.0),
1310            delta: Offset::new(1.0, 2.0),
1311            ..PointerDownEvent::default()
1312        });
1313        let position = OffsetPair::from_event_position(&event);
1314        assert_eq!(position.global, Offset::new(10.0, 20.0));
1315        assert_eq!(position.local, Offset::new(10.0, 20.0));
1316        let delta = OffsetPair::from_event_delta(&event);
1317        assert_eq!(delta.global, Offset::new(1.0, 2.0));
1318        let sum = position + delta;
1319        assert_eq!(sum.global, Offset::new(11.0, 22.0));
1320        assert_eq!((sum - delta).global, position.global);
1321        assert_eq!(OffsetPair::ZERO.global, Offset::ZERO);
1322    }
1323}