1use 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
31pub type AllowedButtonsFilter = Rc<dyn Fn(i64) -> bool>;
36
37pub const UNSET_TOUCH_SLOP: f64 = -1.0;
42
43pub(crate) fn default_button_accept_behavior(_buttons: i64) -> bool {
46 true
47}
48
49#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
56pub enum DragStartBehavior {
57 Down,
60
61 #[default]
64 Start,
65}
66
67#[derive(Debug, Clone, Copy, PartialEq, Eq)]
74pub enum MultitouchDragStrategy {
75 LatestPointer,
82
83 AverageBoundaryPointers,
90
91 SumAllPointers,
94}
95
96#[derive(Debug, Clone, Copy, PartialEq, Eq)]
111pub enum GestureRecognizerState {
112 Ready,
114
115 Possible,
119
120 Defunct,
124}
125
126#[derive(Clone, Copy)]
130pub(crate) struct RecognizerEventData {
131 pub kind: PointerDeviceKind,
132 pub buttons: i64,
133}
134
135pub 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 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 pub fn gesture_settings(&self) -> Option<DeviceGestureSettings> {
162 self.gesture_settings
163 }
164
165 pub fn set_gesture_settings(&mut self, settings: Option<DeviceGestureSettings>) {
167 self.gesture_settings = settings;
168 }
169
170 pub fn allowed_buttons_filter(&self) -> &AllowedButtonsFilter {
172 &self.allowed_buttons_filter
173 }
174
175 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
187pub 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 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
214pub 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 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 pub fn primary_pointer(&self) -> Option<i64> {
281 self.primary_pointer
282 }
283}
284
285#[derive(Clone, Copy, Debug)]
291pub struct OffsetPair {
292 pub local: Offset,
294
295 pub global: Offset,
298}
299
300impl OffsetPair {
301 pub const ZERO: OffsetPair = OffsetPair {
303 local: Offset::ZERO,
304 global: Offset::ZERO,
305 };
306
307 pub const fn new(local: Offset, global: Offset) -> OffsetPair {
309 OffsetPair { local, global }
310 }
311
312 pub fn from_event_position(event: &PointerEvent) -> OffsetPair {
315 OffsetPair {
316 local: event.local_position(),
317 global: event.position(),
318 }
319 }
320
321 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
363pub trait RecognizerLeafData {
365 fn recognizer(&self) -> &GestureRecognizerData;
367
368 fn recognizer_mut(&mut self) -> &mut GestureRecognizerData;
370}
371
372pub trait OneSequenceLeafData: RecognizerLeafData {
374 fn one_sequence(&self) -> &OneSequenceData;
376
377 fn one_sequence_mut(&mut self) -> &mut OneSequenceData;
379}
380
381pub trait PrimaryPointerLeafData: OneSequenceLeafData {
383 fn primary(&self) -> &PrimaryPointerData;
385
386 fn primary_mut(&mut self) -> &mut PrimaryPointerData;
388}
389
390pub trait RecognizerLeaf: RecognizerLeafData + Sized + 'static {
396 fn handle_event_route(self: Handle<Self>, app: &mut App, event: PointerEvent) {
399 self.handle_event(app, event);
400 }
401
402 fn add_pointer(self: Handle<Self>, app: &mut App, event: PointerDownEvent) {
408 GestureRecognizer::add_pointer(self, app, event);
409 }
410
411 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 fn add_allowed_pointer(self: Handle<Self>, _app: &mut App, _event: PointerDownEvent) {}
427
428 fn add_allowed_pointer_pan_zoom(
431 self: Handle<Self>,
432 _app: &mut App,
433 _event: crate::events::PointerPanZoomStartEvent,
434 ) {
435 }
436
437 fn handle_non_allowed_pointer(self: Handle<Self>, _app: &mut App, _event: &PointerDownEvent) {}
439
440 fn handle_non_allowed_pointer_pan_zoom(
443 self: Handle<Self>,
444 _app: &mut App,
445 _event: &crate::events::PointerPanZoomStartEvent,
446 ) {
447 }
448
449 fn is_pointer_allowed(self: Handle<Self>, app: &App, event: &PointerDownEvent) -> bool {
452 GestureRecognizer::is_pointer_allowed(self, app, event)
453 }
454
455 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 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 fn handle_event(self: Handle<Self>, app: &mut App, event: PointerEvent);
480
481 fn accept_gesture(self: Handle<Self>, _app: &mut App, _pointer: i64) {}
483
484 fn reject_gesture(self: Handle<Self>, _app: &mut App, _pointer: i64) {}
486
487 fn did_stop_tracking_last_pointer(self: Handle<Self>, _app: &mut App, _pointer: i64) {}
490
491 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 fn dispose(self: Handle<Self>, app: &mut App) {
502 GestureRecognizer::dispose(self, app);
503 }
504
505 fn debug_description(self: Handle<Self>) -> &'static str;
508}
509
510pub trait PrimaryPointerLeaf: RecognizerLeaf + PrimaryPointerLeafData {
512 fn deadline_fired(self: Handle<Self>, app: &mut App) {
514 self.did_exceed_deadline_with_event(app);
515 }
516
517 fn handle_primary_pointer(self: Handle<Self>, app: &mut App, event: PointerEvent);
520
521 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 fn did_exceed_deadline_with_event(self: Handle<Self>, app: &mut App) {
538 PrimaryPointerGestureRecognizer::did_exceed_deadline_with_event(self, app);
539 }
540}
541
542impl<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
558pub trait GestureRecognizerLeaf: Sized + 'static {
565 fn as_recognizer(self: Handle<Self>) -> AnyGestureRecognizer;
571}
572
573pub 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
587pub(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
602fn resolve<R: 'static>(id: HandleId) -> Handle<R> {
604 Handle::from_id(id)
605}
606
607impl GestureRecognizerVTable {
608 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#[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 pub fn id(self) -> HandleId {
655 self.id
656 }
657
658 pub fn type_id(self) -> TypeId {
660 (self.vtable.type_id)()
661 }
662
663 pub fn type_name(self) -> &'static str {
665 bare_type_name((self.vtable.type_name)())
666 }
667
668 pub fn downcast<T: 'static>(self, app: &App) -> Option<Handle<T>> {
670 app.handle::<T>(self.id)
671 }
672
673 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 pub fn add_pointer(self, app: &mut App, event: &PointerDownEvent) {
683 (self.vtable.add_pointer)(app, self.id, event.clone());
684 }
685
686 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 pub fn is_pointer_allowed(self, app: &App, event: &PointerDownEvent) -> bool {
693 (self.vtable.is_pointer_allowed)(app, self.id, event)
694 }
695
696 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 pub fn dispose(self, app: &mut App) {
704 (self.vtable.dispose)(app, self.id);
705 }
706
707 pub fn debug_description(self) -> &'static str {
709 (self.vtable.debug_description)(self.id)
710 }
711}
712
713pub struct GestureRecognizer;
719
720impl GestureRecognizer {
721 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 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 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 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 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 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 pub fn dispose<R: RecognizerLeaf>(this: Handle<R>, app: &mut App) {
834 app.mark_disposed(this);
835 }
836
837 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
860pub struct OneSequenceGestureRecognizer;
866
867impl OneSequenceGestureRecognizer {
868 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 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 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 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 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 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 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 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
1045pub struct PrimaryPointerGestureRecognizer;
1057
1058impl PrimaryPointerGestureRecognizer {
1059 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 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 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 pub fn did_exceed_deadline_with_event<R: PrimaryPointerLeaf>(this: Handle<R>, app: &mut App) {
1132 this.did_exceed_deadline(app);
1133 }
1134
1135 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 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 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 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 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 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 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 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 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}