1use std::any::{Any, TypeId};
11use std::cell::RefCell;
12use std::hash::{Hash, Hasher};
13use std::rc::Rc;
14use std::time::Duration;
15
16use crate::animation;
17use crate::animation_driver;
18use crate::input::{PointerEvent, PointerEventKind, PointerId};
19use crate::modifier_node::{ModifierNode, ModifierNodeElement};
20use crate::{Vec2, request_frame};
21
22pub trait PointerInputHandler: Any {
27 fn clone_handler(&self) -> Box<dyn PointerInputHandler>;
29 fn sync(&mut self, next: &dyn PointerInputHandler) {
32 let _ = next;
33 }
34 fn on_event(&mut self, event: &PointerEvent) -> bool;
35 fn on_attach(&mut self) {}
36 fn on_detach(&mut self) {}
37 #[doc(hidden)]
38 fn as_any(&self) -> &dyn Any;
39}
40
41struct PointerInputNode {
42 handler: RefCell<Box<dyn PointerInputHandler>>,
43}
44
45impl ModifierNode for PointerInputNode {
46 fn on_attach(&self) {
47 self.handler.borrow_mut().on_attach();
48 }
49 fn on_detach(&self) {
50 self.handler.borrow_mut().on_detach();
51 }
52 fn as_any(&self) -> &dyn Any {
53 self
54 }
55}
56
57struct PointerInputElement {
58 handler: Box<dyn PointerInputHandler>,
59 handler_type: TypeId,
60}
61
62impl ModifierNodeElement for PointerInputElement {
63 fn create(&self) -> Rc<dyn ModifierNode> {
64 Rc::new(PointerInputNode {
65 handler: RefCell::new(self.handler.clone_handler()),
66 })
67 }
68
69 fn update(&self, node: &Rc<dyn ModifierNode>) {
70 if let Some(node) = node.as_any().downcast_ref::<PointerInputNode>() {
71 node.handler.borrow_mut().sync(&*self.handler);
72 }
73 }
74
75 fn key(&self) -> Option<u64> {
76 let mut hasher = rustc_hash::FxHasher::default();
77 self.handler_type.hash(&mut hasher);
78 Some(hasher.finish())
79 }
80}
81
82#[derive(Clone)]
84#[doc(hidden)]
85pub struct PointerInputDispatch {
86 node: Rc<dyn ModifierNode>,
87}
88
89impl PointerInputDispatch {
90 pub(crate) fn new(node: Rc<dyn ModifierNode>) -> Self {
91 Self { node }
92 }
93
94 #[doc(hidden)]
95 pub fn on_event(&self, event: &PointerEvent) -> bool {
96 let Some(node) = self.node.as_any().downcast_ref::<PointerInputNode>() else {
97 return false;
98 };
99 node.handler.borrow_mut().on_event(event)
100 }
101}
102
103pub(crate) fn element(handler: Box<dyn PointerInputHandler>) -> Rc<dyn ModifierNodeElement> {
104 let handler_type = (&*handler as &dyn Any).type_id();
105 Rc::new(PointerInputElement {
106 handler,
107 handler_type,
108 })
109}
110
111fn schedule_once(key: String, delay: Duration, action: impl Fn() + 'static) {
114 let start = animation::now();
115 let action = Rc::new(action);
116 animation_driver::register(
117 key,
118 Rc::new(RefCell::new(move || {
119 if animation::now().duration_since(start) >= delay {
120 action();
121 request_frame();
122 false
123 } else {
124 request_frame();
125 true
126 }
127 })),
128 );
129 request_frame();
130}
131
132fn cancel(key: &str) {
133 animation_driver::unregister(key);
134}
135
136#[derive(Clone, Copy, Debug)]
138pub struct TapEvent {
139 pub id: PointerId,
140 pub position: Vec2,
141}
142
143enum TapPhase {
144 Idle,
145 Pressed {
146 id: PointerId,
147 start: Vec2,
148 long_fired: bool,
149 },
150 WaitingSecond {
151 first: TapEvent,
152 },
153 SecondPressed {
154 id: PointerId,
155 start: Vec2,
156 long_fired: bool,
157 first: TapEvent,
158 },
159}
160
161struct TapConfig {
162 touch_slop_px: f32,
163 double_tap_ms: f32,
164 long_press_ms: f32,
165 on_tap: Option<Rc<dyn Fn(TapEvent)>>,
166 on_double_tap: Option<Rc<dyn Fn(TapEvent)>>,
167 on_long_press: Option<Rc<dyn Fn(TapEvent)>>,
168}
169
170impl Clone for TapConfig {
171 fn clone(&self) -> Self {
172 Self {
173 touch_slop_px: self.touch_slop_px,
174 double_tap_ms: self.double_tap_ms,
175 long_press_ms: self.long_press_ms,
176 on_tap: self.on_tap.clone(),
177 on_double_tap: self.on_double_tap.clone(),
178 on_long_press: self.on_long_press.clone(),
179 }
180 }
181}
182
183#[derive(Clone)]
189pub struct TapGestures {
190 config: Rc<TapConfig>,
191 phase: Rc<RefCell<TapPhase>>,
192 tick_key: String,
193}
194
195impl TapGestures {
196 pub fn new() -> Self {
197 Self {
198 config: Rc::new(TapConfig {
199 touch_slop_px: 12.0,
200 double_tap_ms: 300.0,
201 long_press_ms: 500.0,
202 on_tap: None,
203 on_double_tap: None,
204 on_long_press: None,
205 }),
206 phase: Rc::new(RefCell::new(TapPhase::Idle)),
207 tick_key: format!("tap:{}", next_id()),
208 }
209 }
210
211 pub fn on_tap(mut self, f: impl Fn(TapEvent) + 'static) -> Self {
212 Rc::make_mut(&mut self.config).on_tap = Some(Rc::new(f));
213 self
214 }
215
216 pub fn on_double_tap(mut self, f: impl Fn(TapEvent) + 'static) -> Self {
217 Rc::make_mut(&mut self.config).on_double_tap = Some(Rc::new(f));
218 self
219 }
220
221 pub fn on_long_press(mut self, f: impl Fn(TapEvent) + 'static) -> Self {
222 Rc::make_mut(&mut self.config).on_long_press = Some(Rc::new(f));
223 self
224 }
225
226 pub fn touch_slop(mut self, px: f32) -> Self {
227 Rc::make_mut(&mut self.config).touch_slop_px = px;
228 self
229 }
230
231 pub fn double_tap_window(mut self, ms: f32) -> Self {
232 Rc::make_mut(&mut self.config).double_tap_ms = ms;
233 self
234 }
235
236 pub fn long_press_window(mut self, ms: f32) -> Self {
237 Rc::make_mut(&mut self.config).long_press_ms = ms;
238 self
239 }
240
241 fn arm_long_press(&self, id: PointerId) {
242 let Some(on_long_press) = self.config.on_long_press.clone() else {
243 return;
244 };
245 let phase = self.phase.clone();
246 let delay = Duration::from_secs_f32(self.config.long_press_ms.max(0.0) / 1000.0);
247 schedule_once(self.tick_key.clone(), delay, move || {
248 let mut phase = phase.borrow_mut();
249 let (pressed, long_fired, position) = match &mut *phase {
250 TapPhase::Pressed {
251 id,
252 start,
253 long_fired,
254 }
255 | TapPhase::SecondPressed {
256 id,
257 start,
258 long_fired,
259 ..
260 } => (*id, long_fired, *start),
261 _ => return,
262 };
263 if pressed != id {
264 return;
265 }
266 *long_fired = true;
267 drop(phase);
268 on_long_press(TapEvent { id, position });
269 });
270 }
271
272 fn report_abandoned_first(&self, first: Option<TapEvent>) {
273 if let (Some(first), Some(on_tap)) = (first, &self.config.on_tap) {
274 on_tap(first);
275 }
276 }
277
278 fn schedule_single_tap(&self, first: TapEvent) {
279 let on_tap = self.config.on_tap.clone();
280 let phase = self.phase.clone();
281 let delay = Duration::from_secs_f32(self.config.double_tap_ms.max(0.0) / 1000.0);
282 schedule_once(self.tick_key.clone(), delay, move || {
285 let mut phase = phase.borrow_mut();
286 if !matches!(&*phase, TapPhase::WaitingSecond { first: pending } if pending.id == first.id)
287 {
288 return;
289 }
290 *phase = TapPhase::Idle;
291 drop(phase);
292 if let Some(on_tap) = &on_tap {
293 on_tap(first);
294 }
295 });
296 }
297}
298
299impl Default for TapGestures {
300 fn default() -> Self {
301 Self::new()
302 }
303}
304
305impl PointerInputHandler for TapGestures {
306 fn clone_handler(&self) -> Box<dyn PointerInputHandler> {
307 Box::new(Self {
308 config: self.config.clone(),
309 phase: Rc::new(RefCell::new(TapPhase::Idle)),
310 tick_key: format!("tap:{}", next_id()),
311 })
312 }
313
314 fn sync(&mut self, next: &dyn PointerInputHandler) {
315 if let Some(next) = (next as &dyn Any).downcast_ref::<TapGestures>() {
316 self.config = next.config.clone();
317 }
318 }
319
320 fn on_event(&mut self, event: &PointerEvent) -> bool {
321 let mut phase = self.phase.borrow_mut();
322 match event.event {
323 PointerEventKind::Down(_) => {
324 cancel(&self.tick_key);
325 let previous = std::mem::replace(&mut *phase, TapPhase::Idle);
326 *phase = match previous {
327 TapPhase::WaitingSecond { first } => TapPhase::SecondPressed {
328 id: event.id,
329 start: event.position,
330 long_fired: false,
331 first,
332 },
333 _ => TapPhase::Pressed {
334 id: event.id,
335 start: event.position,
336 long_fired: false,
337 },
338 };
339 drop(phase);
340 self.arm_long_press(event.id);
341 false
342 }
343 PointerEventKind::Move => {
344 let (start, first) = match &*phase {
345 TapPhase::Pressed { start, .. } => (*start, None),
346 TapPhase::SecondPressed { start, first, .. } => (*start, Some(*first)),
347 _ => return false,
348 };
349 let dx = event.position.x - start.x;
350 let dy = event.position.y - start.y;
351 if dx.hypot(dy) > self.config.touch_slop_px {
352 *phase = TapPhase::Idle;
353 drop(phase);
354 cancel(&self.tick_key);
355 self.report_abandoned_first(first);
356 return false;
357 }
358 false
359 }
360 PointerEventKind::Up(_) => {
361 let matches_press = match &*phase {
362 TapPhase::Pressed { id, .. } | TapPhase::SecondPressed { id, .. } => {
363 *id == event.id
364 }
365 TapPhase::WaitingSecond { .. } => true,
366 TapPhase::Idle => false,
367 };
368 if !matches_press {
369 return false;
370 }
371 let previous = std::mem::replace(&mut *phase, TapPhase::Idle);
372 drop(phase);
373 match previous {
374 TapPhase::Pressed { long_fired, .. } => {
375 if long_fired {
376 return true;
377 }
378 let tap = TapEvent {
379 id: event.id,
380 position: event.position,
381 };
382 cancel(&self.tick_key);
383 if self.config.on_double_tap.is_some() {
384 *self.phase.borrow_mut() = TapPhase::WaitingSecond { first: tap };
385 self.schedule_single_tap(tap);
386 } else if let Some(on_tap) = &self.config.on_tap {
387 on_tap(tap);
388 }
389 true
390 }
391 TapPhase::SecondPressed {
392 long_fired, first, ..
393 } => {
394 cancel(&self.tick_key);
395 if !long_fired && let Some(on_double_tap) = &self.config.on_double_tap {
396 on_double_tap(TapEvent {
397 id: first.id,
398 position: event.position,
399 });
400 }
401 true
402 }
403 TapPhase::WaitingSecond { first } => {
404 cancel(&self.tick_key);
405 if let Some(on_tap) = &self.config.on_tap {
406 on_tap(first);
407 }
408 true
409 }
410 TapPhase::Idle => false,
411 }
412 }
413 PointerEventKind::Cancel => {
414 let first = match &*phase {
415 TapPhase::SecondPressed { first, .. } => Some(*first),
416 _ => None,
417 };
418 let had = !matches!(&*phase, TapPhase::Idle);
419 *phase = TapPhase::Idle;
420 drop(phase);
421 cancel(&self.tick_key);
422 self.report_abandoned_first(first);
423 had
424 }
425 PointerEventKind::Enter | PointerEventKind::Leave => false,
426 }
427 }
428
429 fn on_detach(&mut self) {
430 cancel(&self.tick_key);
431 }
432
433 fn as_any(&self) -> &dyn Any {
434 self
435 }
436}
437
438#[derive(Clone, Copy, Debug)]
439pub struct DragStart {
440 pub id: PointerId,
441 pub position: Vec2,
442}
443
444#[derive(Clone, Copy, Debug)]
445pub struct DragUpdate {
446 pub id: PointerId,
447 pub position: Vec2,
448 pub delta: Vec2,
449 pub total: Vec2,
450}
451
452#[derive(Clone, Copy, Debug)]
453pub struct DragEnd {
454 pub id: PointerId,
455 pub position: Vec2,
456 pub total: Vec2,
457}
458
459struct DragConfig {
460 touch_slop_px: f32,
461 on_start: Option<Rc<dyn Fn(DragStart)>>,
462 on_drag: Option<Rc<dyn Fn(DragUpdate)>>,
463 on_end: Option<Rc<dyn Fn(DragEnd)>>,
464 on_cancel: Option<Rc<dyn Fn()>>,
465}
466
467impl Clone for DragConfig {
468 fn clone(&self) -> Self {
469 Self {
470 touch_slop_px: self.touch_slop_px,
471 on_start: self.on_start.clone(),
472 on_drag: self.on_drag.clone(),
473 on_end: self.on_end.clone(),
474 on_cancel: self.on_cancel.clone(),
475 }
476 }
477}
478
479#[derive(Clone, Copy)]
480enum DragPhase {
481 Idle,
482 Pressed {
483 id: PointerId,
484 start: Vec2,
485 },
486 Dragging {
487 id: PointerId,
488 start: Vec2,
489 last: Vec2,
490 },
491}
492
493#[derive(Clone)]
495pub struct DragGestures {
496 config: DragConfig,
497 phase: DragPhase,
498}
499
500impl DragGestures {
501 pub fn new() -> Self {
502 Self {
503 config: DragConfig {
504 touch_slop_px: 8.0,
505 on_start: None,
506 on_drag: None,
507 on_end: None,
508 on_cancel: None,
509 },
510 phase: DragPhase::Idle,
511 }
512 }
513
514 pub fn on_start(mut self, f: impl Fn(DragStart) + 'static) -> Self {
515 self.config.on_start = Some(Rc::new(f));
516 self
517 }
518
519 pub fn on_drag(mut self, f: impl Fn(DragUpdate) + 'static) -> Self {
520 self.config.on_drag = Some(Rc::new(f));
521 self
522 }
523
524 pub fn on_end(mut self, f: impl Fn(DragEnd) + 'static) -> Self {
525 self.config.on_end = Some(Rc::new(f));
526 self
527 }
528
529 pub fn on_cancel(mut self, f: impl Fn() + 'static) -> Self {
530 self.config.on_cancel = Some(Rc::new(f));
531 self
532 }
533
534 pub fn touch_slop(mut self, px: f32) -> Self {
535 self.config.touch_slop_px = px;
536 self
537 }
538}
539
540impl Default for DragGestures {
541 fn default() -> Self {
542 Self::new()
543 }
544}
545
546fn delta(from: Vec2, to: Vec2) -> Vec2 {
547 Vec2 {
548 x: to.x - from.x,
549 y: to.y - from.y,
550 }
551}
552
553impl PointerInputHandler for DragGestures {
554 fn clone_handler(&self) -> Box<dyn PointerInputHandler> {
555 Box::new(Self {
556 config: self.config.clone(),
557 phase: DragPhase::Idle,
558 })
559 }
560
561 fn sync(&mut self, next: &dyn PointerInputHandler) {
562 if let Some(next) = (next as &dyn Any).downcast_ref::<DragGestures>() {
563 self.config = next.config.clone();
564 }
565 }
566
567 fn on_event(&mut self, event: &PointerEvent) -> bool {
568 match event.event {
569 PointerEventKind::Down(_) => {
570 if matches!(self.phase, DragPhase::Idle) {
573 self.phase = DragPhase::Pressed {
574 id: event.id,
575 start: event.position,
576 };
577 }
578 false
579 }
580 PointerEventKind::Move => match self.phase {
581 DragPhase::Pressed { id, start, .. } if id == event.id => {
582 let total = delta(start, event.position);
583 if total.x.hypot(total.y) <= self.config.touch_slop_px {
584 return false;
585 }
586 self.phase = DragPhase::Dragging {
587 id,
588 start,
589 last: event.position,
590 };
591 if let Some(on_start) = &self.config.on_start {
592 on_start(DragStart {
593 id,
594 position: event.position,
595 });
596 }
597 if let Some(on_drag) = &self.config.on_drag {
598 on_drag(DragUpdate {
599 id,
600 position: event.position,
601 delta: total,
602 total,
603 });
604 }
605 true
606 }
607 DragPhase::Dragging { id, start, last } if id == event.id => {
608 let step = delta(last, event.position);
609 self.phase = DragPhase::Dragging {
610 id,
611 start,
612 last: event.position,
613 };
614 if let Some(on_drag) = &self.config.on_drag {
615 on_drag(DragUpdate {
616 id,
617 position: event.position,
618 delta: step,
619 total: delta(start, event.position),
620 });
621 }
622 true
623 }
624 _ => false,
625 },
626 PointerEventKind::Up(_) => {
627 let ours = matches!(self.phase, DragPhase::Dragging { id, .. } if id == event.id);
628 if !ours {
629 return false;
630 }
631 match std::mem::replace(&mut self.phase, DragPhase::Idle) {
632 DragPhase::Dragging { id, start, .. } => {
633 if let Some(on_end) = &self.config.on_end {
634 on_end(DragEnd {
635 id,
636 position: event.position,
637 total: delta(start, event.position),
638 });
639 }
640 true
641 }
642 _ => false,
643 }
644 }
645 PointerEventKind::Cancel => {
646 let was_dragging = matches!(self.phase, DragPhase::Dragging { .. });
647 self.phase = DragPhase::Idle;
648 if was_dragging {
649 if let Some(on_cancel) = &self.config.on_cancel {
650 on_cancel();
651 }
652 true
653 } else {
654 false
655 }
656 }
657 PointerEventKind::Enter | PointerEventKind::Leave => false,
658 }
659 }
660
661 fn as_any(&self) -> &dyn Any {
662 self
663 }
664}
665
666fn next_id() -> u64 {
667 use std::sync::atomic::{AtomicU64, Ordering};
668 static NEXT: AtomicU64 = AtomicU64::new(0);
669 NEXT.fetch_add(1, Ordering::Relaxed)
670}
671
672pub(crate) fn dispatch_from(
674 nodes: &[crate::modifier_node::ModifierNodeHandle],
675) -> Option<PointerInputDispatch> {
676 if nodes.is_empty() {
677 return None;
678 }
679 nodes.iter().find_map(|handle| {
680 let node = handle.node();
681 let is_input = node.as_any().downcast_ref::<PointerInputNode>().is_some();
682 is_input.then(|| PointerInputDispatch::new(node))
683 })
684}