waft-gestures 0.8.2

Gesture arena and recognizers for Waft
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
//! Flutter counterpart: `gestures/multidrag.dart`.

use std::any::TypeId;
use std::collections::{HashMap, HashSet};
use std::fmt;
use std::rc::Rc;
use std::time::Duration;

use waft_embedder::{Offset, PointerDeviceKind};
use waft_foundation::{App, Handle, HandleId, Listener, Timer};

use crate::arena::{GestureArenaEntry, GestureDisposition};
use crate::binding::GestureBinding;
use crate::constants::K_LONG_PRESS_TIMEOUT;
use crate::drag::Drag;
use crate::drag_details::{DragEndDetails, DragUpdateDetails};
use crate::events::{
    K_PRIMARY_BUTTON, PointerDownEvent, PointerEvent, PointerMoveEvent, compute_hit_slop,
};
use crate::gesture_settings::DeviceGestureSettings;
use crate::pointer_router::PointerRoute;
use crate::recognizer::{
    AllowedButtonsFilter, GestureRecognizer, GestureRecognizerData, RecognizerLeaf,
    RecognizerLeafData,
};
use crate::velocity_tracker::VelocityTracker;
use waft_foundation::Ref;
use waft_foundation::Retained;

/// Signature for when `MultiDragGestureRecognizer` recognizes the start of a drag gesture.
pub type GestureMultiDragStartCallback = Rc<dyn Fn(&mut App, Offset) -> Option<Rc<dyn Drag>>>;

/// Per-pointer state for a `MultiDragGestureRecognizer`.
///
/// A `MultiDragGestureRecognizer` tracks each pointer separately. The state for
/// each pointer is a subclass of `MultiDragPointerState`.
pub struct MultiDragPointerStateData {
    gesture_settings: Option<DeviceGestureSettings>,
    initial_position: Offset,
    velocity_tracker: VelocityTracker,
    kind: PointerDeviceKind,
    client: Option<Rc<dyn Drag>>,
    pending_delta: Option<Offset>,
    last_pending_event_timestamp: Option<Duration>,
    arena_entry: Option<GestureArenaEntry>,
}

impl MultiDragPointerStateData {
    pub fn new(
        initial_position: Offset,
        kind: PointerDeviceKind,
        gesture_settings: Option<DeviceGestureSettings>,
    ) -> Self {
        Self {
            gesture_settings,
            initial_position,
            velocity_tracker: VelocityTracker::with_kind(kind),
            kind,
            client: None,
            pending_delta: Some(Offset::ZERO),
            last_pending_event_timestamp: None,
            arena_entry: None,
        }
    }
}

pub trait MultiDragPointerState: Sized + 'static {
    fn pointer_state(&self) -> &MultiDragPointerStateData;

    fn pointer_state_mut(&mut self) -> &mut MultiDragPointerStateData;

    fn initial_position(self: Handle<Self>, app: &App) -> Offset {
        app.get(self).pointer_state().initial_position
    }

    fn pending_delta(self: Handle<Self>, app: &App) -> Option<Offset> {
        app.get(self).pointer_state().pending_delta
    }

    /// Resolve this pointer's entry in the gesture arena with the given disposition.
    fn resolve(self: Handle<Self>, app: &mut App, disposition: GestureDisposition) {
        let entry = app.get(self).pointer_state().arena_entry.clone().unwrap();
        entry.resolve(app, disposition);
    }

    /// Override this to call resolve() if the drag should be accepted or rejected.
    fn check_for_resolution_after_move(self: Handle<Self>, _app: &mut App) {}

    /// Called when the gesture was accepted. Call `starter` to start the drag.
    fn accepted(self: Handle<Self>, app: &mut App, starter: GestureMultiDragStartCallback);

    fn rejected(self: Handle<Self>, app: &mut App) {
        let state = app.get_mut(self).pointer_state_mut();
        debug_assert!(state.arena_entry.is_some());
        debug_assert!(state.client.is_none());
        debug_assert!(state.pending_delta.is_some());
        state.pending_delta = None;
        state.last_pending_event_timestamp = None;
        state.arena_entry = None;
    }

    fn dispose(self: Handle<Self>, app: &mut App) {
        dispose_pointer_state(self, app);
    }

    fn as_pointer_state(self: Handle<Self>) -> AnyMultiDragPointerState {
        AnyMultiDragPointerState {
            id: self.id(),
            table: const { &PointerStateVTable::of::<Self>() },
        }
    }
}

fn dispose_pointer_state<P: MultiDragPointerState>(this: Handle<P>, app: &mut App) {
    let entry = app.get(this).pointer_state().arena_entry.clone();
    if let Some(entry) = entry {
        entry.resolve(app, GestureDisposition::Rejected);
    }
    let state = app.get_mut(this).pointer_state_mut();
    state.arena_entry = None;
    if cfg!(debug_assertions) {
        state.pending_delta = None;
    }
}

fn move_pointer<P: MultiDragPointerState>(this: Handle<P>, app: &mut App, event: PointerMoveEvent) {
    let now = app.clock();
    let state = app.get_mut(this).pointer_state_mut();
    debug_assert!(state.arena_entry.is_some());
    if !event.synthesized {
        state
            .velocity_tracker
            .add_position(now, event.time_stamp, event.position);
    }
    if let Some(client) = state.client.clone() {
        debug_assert!(state.pending_delta.is_none());
        client.update(
            app,
            DragUpdateDetails::new(
                event.position,
                None,
                Some(event.time_stamp),
                event.delta,
                None,
                None,
            ),
        );
    } else {
        state.pending_delta = Some(state.pending_delta.unwrap() + event.delta);
        state.last_pending_event_timestamp = Some(event.time_stamp);
        this.check_for_resolution_after_move(app);
    }
}

fn start_pointer<P: MultiDragPointerState>(this: Handle<P>, app: &mut App, client: Rc<dyn Drag>) {
    let state = app.get_mut(this).pointer_state_mut();
    debug_assert!(state.arena_entry.is_some());
    debug_assert!(state.client.is_none());
    state.client = Some(client.clone());
    let details = DragUpdateDetails::new(
        state.initial_position,
        None,
        state.last_pending_event_timestamp.take(),
        state.pending_delta.take().unwrap(),
        None,
        None,
    );
    client.update(app, details);
}

fn end_pointer<P: MultiDragPointerState>(this: Handle<P>, app: &mut App, cancel: bool) {
    let now = app.clock();
    let state = app.get_mut(this).pointer_state_mut();
    debug_assert!(state.arena_entry.is_some());
    if let Some(client) = state.client.take() {
        debug_assert!(state.pending_delta.is_none());
        let velocity = state.velocity_tracker.get_velocity(now);
        if cancel {
            client.cancel(app);
        } else {
            client.end(app, DragEndDetails::new(Offset::ZERO, None, velocity, None));
        }
    } else {
        debug_assert!(state.pending_delta.is_some());
        state.pending_delta = None;
        state.last_pending_event_timestamp = None;
    }
}

#[derive(Clone, Copy)]
pub struct AnyMultiDragPointerState {
    id: HandleId,
    table: &'static PointerStateVTable,
}

waft_foundation::erased_handle!(AnyMultiDragPointerState: MultiDragPointerState => MultiDragPointerState::as_pointer_state);

struct PointerStateVTable {
    set_entry: fn(&mut App, HandleId, GestureArenaEntry),
    moved: fn(&mut App, HandleId, PointerMoveEvent),
    accepted: fn(&mut App, HandleId, GestureMultiDragStartCallback),
    start: fn(&mut App, HandleId, Rc<dyn Drag>),
    rejected: fn(&mut App, HandleId),
    end: fn(&mut App, HandleId, bool),
    dispose: fn(&mut App, HandleId),
}

impl PointerStateVTable {
    const fn of<P: MultiDragPointerState>() -> Self {
        Self {
            set_entry: |app, id, entry| {
                let state = app.get_mut(Handle::<P>::from_id(id)).pointer_state_mut();
                debug_assert!(state.arena_entry.is_none());
                state.arena_entry = Some(entry);
            },
            moved: |app, id, event| move_pointer(Handle::<P>::from_id(id), app, event),
            accepted: |app, id, start| P::accepted(Handle::from_id(id), app, start),
            start: |app, id, client| start_pointer(Handle::<P>::from_id(id), app, client),
            rejected: |app, id| P::rejected(Handle::from_id(id), app),
            end: |app, id, cancel| end_pointer(Handle::<P>::from_id(id), app, cancel),
            dispose: |app, id| P::dispose(Handle::from_id(id), app),
        }
    }
}

/// Recognizes movement on a per-pointer basis.
///
/// Unlike one-sequence recognizers, multiple drags can be recognized concurrently.
pub struct MultiDragGestureRecognizerData {
    on_start: Option<GestureMultiDragStartCallback>,
    pointers: Option<HashMap<i64, Retained<AnyMultiDragPointerState>>>,
}

impl Default for MultiDragGestureRecognizerData {
    fn default() -> Self {
        Self {
            on_start: None,
            pointers: Some(HashMap::new()),
        }
    }
}

pub trait MultiDragGestureRecognizer: RecognizerLeaf {
    fn multi_drag(&self) -> &MultiDragGestureRecognizerData;

    fn multi_drag_mut(&mut self) -> &mut MultiDragGestureRecognizerData;

    /// Create per-pointer state to track the pointer associated with the given event.
    fn create_new_pointer_state(
        self: Handle<Self>,
        app: &mut App,
        event: PointerDownEvent,
    ) -> Retained<AnyMultiDragPointerState>;

    fn on_start(self: Handle<Self>, app: &App) -> Option<GestureMultiDragStartCallback> {
        app.get(self).multi_drag().on_start.clone()
    }

    fn set_on_start(
        self: Handle<Self>,
        app: &mut App,
        value: Option<GestureMultiDragStartCallback>,
    ) {
        app.get_mut(self).multi_drag_mut().on_start = value;
    }

    fn set_gesture_settings(
        self: Handle<Self>,
        app: &mut App,
        value: Option<DeviceGestureSettings>,
    ) {
        app.get_mut(self)
            .recognizer_mut()
            .set_gesture_settings(value);
    }

    fn set_supported_devices(
        self: Handle<Self>,
        app: &mut App,
        value: Option<HashSet<PointerDeviceKind>>,
    ) {
        app.get_mut(self).recognizer_mut().supported_devices = value;
    }

    fn set_allowed_buttons_filter(self: Handle<Self>, app: &mut App, value: AllowedButtonsFilter) {
        app.get_mut(self)
            .recognizer_mut()
            .set_allowed_buttons_filter(value);
    }

    /// This recognizer as the erased [`AnyMultiDragGestureRecognizer`] — what to pass where a
    /// Dart API takes a `MultiDragGestureRecognizer`.
    ///
    /// The object is untouched; this mints an erased second handle to it, so concrete members
    /// stay reachable through the typed one.
    fn as_multi_drag_recognizer(self: Handle<Self>) -> AnyMultiDragGestureRecognizer {
        AnyMultiDragGestureRecognizer {
            id: self.id(),
            vtable: const { &MultiDragGestureRecognizerVTable::of::<Self>() },
        }
    }
}

/// A field Dart types as `MultiDragGestureRecognizer`, kept: the erased recognizer with its
/// count.
pub type MultiDragRecognizerRef = Retained<AnyMultiDragGestureRecognizer>;

waft_foundation::erased_handle!(AnyMultiDragGestureRecognizer: MultiDragGestureRecognizer => MultiDragGestureRecognizer::as_multi_drag_recognizer);

/// The vtable of an erased [`AnyMultiDragGestureRecognizer`]: one `&'static` table per leaf
/// type, built by [`MultiDragGestureRecognizerVTable::of`]. Copied out of the handle before a
/// virtual call, so the slot is not borrowed across it.
struct MultiDragGestureRecognizerVTable {
    type_id: fn() -> TypeId,
    type_name: fn() -> &'static str,
    add_pointer: fn(&mut App, HandleId, PointerDownEvent),
    set_on_start: fn(&mut App, HandleId, Option<GestureMultiDragStartCallback>),
    set_allowed_buttons_filter: fn(&mut App, HandleId, AllowedButtonsFilter),
    set_gesture_settings: fn(&mut App, HandleId, Option<DeviceGestureSettings>),
    dispose: fn(&mut App, HandleId),
    debug_description: fn(HandleId) -> &'static str,
}

impl MultiDragGestureRecognizerVTable {
    const fn of<R: MultiDragGestureRecognizer>() -> MultiDragGestureRecognizerVTable {
        MultiDragGestureRecognizerVTable {
            type_id: TypeId::of::<R>,
            type_name: std::any::type_name::<R>,
            add_pointer: |app, id, event| {
                RecognizerLeaf::add_pointer(Handle::<R>::from_id(id), app, event)
            },
            set_on_start: |app, id, value| {
                MultiDragGestureRecognizer::set_on_start(Handle::<R>::from_id(id), app, value)
            },
            set_allowed_buttons_filter: |app, id, value| {
                MultiDragGestureRecognizer::set_allowed_buttons_filter(
                    Handle::<R>::from_id(id),
                    app,
                    value,
                )
            },
            set_gesture_settings: |app, id, value| {
                MultiDragGestureRecognizer::set_gesture_settings(
                    Handle::<R>::from_id(id),
                    app,
                    value,
                )
            },
            dispose: |app, id| RecognizerLeaf::dispose(Handle::<R>::from_id(id), app),
            debug_description: |id| RecognizerLeaf::debug_description(Handle::<R>::from_id(id)),
        }
    }
}

/// Erased `MultiDragGestureRecognizer`: what a field or parameter Dart types as
/// `MultiDragGestureRecognizer` becomes.
///
/// The leaf stays in the [`App`] under its own type; [`downcast`](Self::downcast) gets the
/// typed handle back, and [`type_id`](Self::type_id) is Dart's `runtimeType`.
///
/// Equality is Dart's `==` on an object reference.
#[derive(Clone, Copy)]
pub struct AnyMultiDragGestureRecognizer {
    id: HandleId,
    vtable: &'static MultiDragGestureRecognizerVTable,
}

impl fmt::Debug for AnyMultiDragGestureRecognizer {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "{}({:?})", (self.vtable.type_name)(), self.id)
    }
}

impl AnyMultiDragGestureRecognizer {
    /// The arena id behind this handle.
    pub fn id(self) -> HandleId {
        self.id
    }

    /// Dart's `runtimeType`: the leaf type this handle was minted from.
    pub fn type_id(self) -> TypeId {
        (self.vtable.type_id)()
    }

    /// Dart's `recognizer as T`: the typed handle when this recognizer is a `T`, else `None`.
    pub fn downcast<T: 'static>(self, app: &App) -> Option<Handle<T>> {
        app.handle::<T>(self.id)
    }

    /// Registers a new pointer that might be relevant to this gesture recognizer.
    pub fn add_pointer(self, app: &mut App, event: &PointerDownEvent) {
        (self.vtable.add_pointer)(app, self.id, event.clone());
    }

    /// Sets the callback that starts the drag when the gesture is accepted.
    pub fn set_on_start(self, app: &mut App, value: Option<GestureMultiDragStartCallback>) {
        (self.vtable.set_on_start)(app, self.id, value);
    }

    /// Sets the filter that decides whether a pointer's buttons may start this gesture.
    pub fn set_allowed_buttons_filter(self, app: &mut App, value: AllowedButtonsFilter) {
        (self.vtable.set_allowed_buttons_filter)(app, self.id, value);
    }

    /// Optional device-specific configuration for device gestures.
    pub fn set_gesture_settings(self, app: &mut App, value: Option<DeviceGestureSettings>) {
        (self.vtable.set_gesture_settings)(app, self.id, value);
    }

    /// Releases any resources used by the object and frees its arena slot. Every handle to it
    /// is stale afterwards.
    pub fn dispose(self, app: &mut App) {
        (self.vtable.dispose)(app, self.id);
    }

    /// Returns a very short pretty description of the gesture that the recognizer looks for.
    pub fn debug_description(self) -> &'static str {
        (self.vtable.debug_description)(self.id)
    }
}

fn add_allowed_pointer<R: MultiDragGestureRecognizer>(
    this: Handle<R>,
    app: &mut App,
    event: PointerDownEvent,
) {
    let pointer = event.pointer;
    debug_assert!(
        !app.get(this)
            .multi_drag()
            .pointers
            .as_ref()
            .unwrap()
            .contains_key(&pointer)
    );
    let state = this.create_new_pointer_state(app, event);
    let state_handle = state.handle();
    app.get_mut(this)
        .multi_drag_mut()
        .pointers
        .as_mut()
        .unwrap()
        .insert(pointer, state);
    let state = state_handle;
    let binding = GestureBinding::instance(app);
    binding.pointer_router(app).add_route(
        app,
        pointer,
        PointerRoute::handle_method(this, R::handle_event_route),
        None,
    );
    let entry = binding.gesture_arena(app).add(app, pointer, this);
    (state.table.set_entry)(app, state.id, entry);
}

fn handle_event<R: MultiDragGestureRecognizer>(
    this: Handle<R>,
    app: &mut App,
    event: PointerEvent,
) {
    let pointer = event.pointer();
    let state = app.get(this).multi_drag().pointers.as_ref().unwrap()[&pointer].handle();
    // Dart keeps the receiver alive if a client's callback disposes the recognizer.
    match event {
        PointerEvent::Move(event) => (state.table.moved)(app, state.id, event),
        PointerEvent::Up(_) | PointerEvent::Cancel(_) => {
            (state.table.end)(app, state.id, matches!(event, PointerEvent::Cancel(_)));
            remove_state(this, app, pointer);
        }
        PointerEvent::Down(_) => {}
        _ => debug_assert!(false),
    }
}

fn accept_gesture<R: MultiDragGestureRecognizer>(this: Handle<R>, app: &mut App, pointer: i64) {
    let state = app
        .get(this)
        .multi_drag()
        .pointers
        .as_ref()
        .unwrap()
        .get(&pointer)
        .map(|state| state.handle());
    if let Some(state) = state {
        (state.table.accepted)(
            app,
            state.id,
            Rc::new(move |app, position| start_drag(this, app, position, pointer)),
        );
    }
}

fn start_drag<R: MultiDragGestureRecognizer>(
    this: Handle<R>,
    app: &mut App,
    position: Offset,
    pointer: i64,
) -> Option<Rc<dyn Drag>> {
    let state = app.get(this).multi_drag().pointers.as_ref().unwrap()[&pointer].handle();
    let drag = this.on_start(app).and_then(|callback| {
        GestureRecognizer::invoke_callback(this, app, "onStart", |app| callback(app, position))
            .flatten()
    });
    if let Some(drag) = drag.clone() {
        (state.table.start)(app, state.id, drag);
    } else {
        remove_state(this, app, pointer);
    }
    drag
}

fn reject_gesture<R: MultiDragGestureRecognizer>(this: Handle<R>, app: &mut App, pointer: i64) {
    let state = app
        .get(this)
        .multi_drag()
        .pointers
        .as_ref()
        .unwrap()
        .get(&pointer)
        .map(|state| state.handle());
    if let Some(state) = state {
        (state.table.rejected)(app, state.id);
        remove_state(this, app, pointer);
    }
}

fn remove_state<R: MultiDragGestureRecognizer>(this: Handle<R>, app: &mut App, pointer: i64) {
    let Some(pointers) = app.get_mut(this).multi_drag_mut().pointers.as_mut() else {
        return;
    };
    let state = pointers.remove(&pointer).expect("tracked pointer");
    let router = GestureBinding::instance(app).pointer_router(app);
    router.remove_route(
        app,
        pointer,
        &PointerRoute::handle_method(this, R::handle_event_route),
    );
    (state.table.dispose)(app, state.id);
}

fn dispose_recognizer<R: MultiDragGestureRecognizer>(this: Handle<R>, app: &mut App) {
    let pointers: Vec<_> = app
        .get(this)
        .multi_drag()
        .pointers
        .as_ref()
        .unwrap()
        .keys()
        .copied()
        .collect();
    for pointer in pointers {
        remove_state(this, app, pointer);
    }
    app.get_mut(this).multi_drag_mut().pointers = None;
    GestureRecognizer::dispose(this, app);
}

macro_rules! pointer_state {
    ($name:ident, $distance:expr) => {
        struct $name {
            state: MultiDragPointerStateData,
        }

        impl MultiDragPointerState for $name {
            fn pointer_state(&self) -> &MultiDragPointerStateData {
                &self.state
            }

            fn pointer_state_mut(&mut self) -> &mut MultiDragPointerStateData {
                &mut self.state
            }

            fn check_for_resolution_after_move(self: Handle<Self>, app: &mut App) {
                let state = &app.get(self).state;
                if ($distance)(state.pending_delta.unwrap())
                    > compute_hit_slop(state.kind, state.gesture_settings)
                {
                    self.resolve(app, GestureDisposition::Accepted);
                }
            }

            fn accepted(self: Handle<Self>, app: &mut App, starter: GestureMultiDragStartCallback) {
                starter(app, self.initial_position(app));
            }
        }
    };
}

pointer_state!(ImmediatePointerState, |offset: Offset| offset.distance());
pointer_state!(HorizontalPointerState, |offset: Offset| offset.dx().abs());
pointer_state!(VerticalPointerState, |offset: Offset| offset.dy().abs());

struct DelayedPointerState {
    state: MultiDragPointerStateData,
    timer: Option<Timer>,
    starter: Option<GestureMultiDragStartCallback>,
}

impl DelayedPointerState {
    fn new(
        app: &mut App,
        initial_position: Offset,
        delay: Duration,
        kind: PointerDeviceKind,
        settings: Option<DeviceGestureSettings>,
    ) -> Ref<Self> {
        let this = app.create(Self {
            state: MultiDragPointerStateData::new(initial_position, kind, settings),
            timer: None,
            starter: None,
        });
        let timer = Timer::new(
            app,
            delay,
            Listener::handle_method(this.handle(), Self::delay_passed),
        );
        app.get_mut(&this).timer = Some(timer);
        this
    }

    fn delay_passed(self: Handle<Self>, app: &mut App) {
        debug_assert!(app.get(self).timer.is_some());
        app.get_mut(self).timer = None;
        if let Some(starter) = app.get(self).starter.clone() {
            starter(app, self.initial_position(app));
            app.get_mut(self).starter = None;
        } else {
            self.resolve(app, GestureDisposition::Accepted);
        }
    }

    fn ensure_timer_stopped(self: Handle<Self>, app: &mut App) {
        if let Some(timer) = app.get_mut(self).timer.take() {
            timer.cancel(app);
        }
    }
}

impl MultiDragPointerState for DelayedPointerState {
    fn pointer_state(&self) -> &MultiDragPointerStateData {
        &self.state
    }

    fn pointer_state_mut(&mut self) -> &mut MultiDragPointerStateData {
        &mut self.state
    }

    fn accepted(self: Handle<Self>, app: &mut App, starter: GestureMultiDragStartCallback) {
        debug_assert!(app.get(self).starter.is_none());
        if app.get(self).timer.is_none() {
            starter(app, self.initial_position(app));
        } else {
            app.get_mut(self).starter = Some(starter);
        }
    }

    fn check_for_resolution_after_move(self: Handle<Self>, app: &mut App) {
        if app.get(self).timer.is_none() {
            debug_assert!(app.get(self).starter.is_some());
            return;
        }
        let state = &app.get(self).state;
        if state.pending_delta.unwrap().distance()
            > compute_hit_slop(state.kind, state.gesture_settings)
        {
            self.resolve(app, GestureDisposition::Rejected);
            self.ensure_timer_stopped(app);
        }
    }

    fn dispose(self: Handle<Self>, app: &mut App) {
        self.ensure_timer_stopped(app);
        dispose_pointer_state(self, app);
    }
}

macro_rules! recognizer {
    ($name:ident, $description:literal, $create:expr $(, $field:ident: $ty:ty = $default:expr)*) => {
        pub struct $name {
            recognizer: GestureRecognizerData,
            multi_drag: MultiDragGestureRecognizerData,
            $($field: $ty,)*
        }

        impl $name {
            pub fn new(app: &mut App) -> Ref<Self> {
                let mut recognizer = GestureRecognizerData::new();
                recognizer.set_allowed_buttons_filter(Rc::new(|buttons| buttons == K_PRIMARY_BUTTON));
                app.create(Self {
                    recognizer,
                    multi_drag: MultiDragGestureRecognizerData::default(),
                    $($field: $default,)*
                })
            }
        }

        impl RecognizerLeafData for $name {
            fn recognizer(&self) -> &GestureRecognizerData {
                &self.recognizer
            }

            fn recognizer_mut(&mut self) -> &mut GestureRecognizerData {
                &mut self.recognizer
            }
        }

        impl MultiDragGestureRecognizer for $name {
            fn multi_drag(&self) -> &MultiDragGestureRecognizerData {
                &self.multi_drag
            }

            fn multi_drag_mut(&mut self) -> &mut MultiDragGestureRecognizerData {
                &mut self.multi_drag
            }

            fn create_new_pointer_state(
                self: Handle<Self>,
                app: &mut App,
                event: PointerDownEvent,
            ) -> Retained<AnyMultiDragPointerState> {
                ($create)(self, app, event)
            }
        }

        impl RecognizerLeaf for $name {
            fn add_allowed_pointer(self: Handle<Self>, app: &mut App, event: PointerDownEvent) {
                add_allowed_pointer(self, app, event);
            }

            fn handle_event(self: Handle<Self>, app: &mut App, event: PointerEvent) {
                handle_event(self, app, event);
            }

            fn accept_gesture(self: Handle<Self>, app: &mut App, pointer: i64) {
                accept_gesture(self, app, pointer);
            }

            fn reject_gesture(self: Handle<Self>, app: &mut App, pointer: i64) {
                reject_gesture(self, app, pointer);
            }

            fn dispose(self: Handle<Self>, app: &mut App) {
                dispose_recognizer(self, app);
            }

            fn debug_description(self: Handle<Self>) -> &'static str {
                $description
            }
        }
    };
}

recognizer!(
    ImmediateMultiDragGestureRecognizer,
    "multidrag",
    |this: Handle<ImmediateMultiDragGestureRecognizer>, app: &mut App, event: PointerDownEvent| {
        let state = MultiDragPointerStateData::new(
            event.position,
            event.kind,
            app.get(this).recognizer.gesture_settings,
        );
        app.create(ImmediatePointerState { state }).into_erased()
    }
);

recognizer!(
    HorizontalMultiDragGestureRecognizer,
    "horizontal multidrag",
    |this: Handle<HorizontalMultiDragGestureRecognizer>, app: &mut App, event: PointerDownEvent| {
        let state = MultiDragPointerStateData::new(
            event.position,
            event.kind,
            app.get(this).recognizer.gesture_settings,
        );
        app.create(HorizontalPointerState { state }).into_erased()
    }
);

recognizer!(
    VerticalMultiDragGestureRecognizer,
    "vertical multidrag",
    |this: Handle<VerticalMultiDragGestureRecognizer>, app: &mut App, event: PointerDownEvent| {
        let state = MultiDragPointerStateData::new(
            event.position,
            event.kind,
            app.get(this).recognizer.gesture_settings,
        );
        app.create(VerticalPointerState { state }).into_erased()
    }
);

recognizer!(
    DelayedMultiDragGestureRecognizer,
    "long multidrag",
    |this: Handle<DelayedMultiDragGestureRecognizer>, app: &mut App, event: PointerDownEvent| {
        DelayedPointerState::new(
            app,
            event.position,
            app.get(this).delay,
            event.kind,
            app.get(this).recognizer.gesture_settings,
        )
        .into_erased()
    },
    delay: Duration = K_LONG_PRESS_TIMEOUT
);

impl DelayedMultiDragGestureRecognizer {
    pub fn delay(self: Handle<Self>, app: &App) -> Duration {
        app.get(self).delay
    }

    pub fn set_delay(self: Handle<Self>, app: &mut App, value: Duration) {
        app.get_mut(self).delay = value;
    }
}