Skip to main content

repose_app/
touch_gesture.rs

1use std::collections::BTreeMap;
2
3use repose_core::Vec2;
4use repose_core::input::PointerButton;
5use repose_core::scroll::{cancel_flings, set_touch_gesture_active};
6
7use crate::runtime::ReposeRuntime;
8use crate::runtime::TAP_SLOP_DP;
9
10#[derive(Clone, Copy, Debug)]
11struct DynGestureState {
12    avg_distance: f32,
13    avg_pos: Vec2,
14    heading: f32,
15}
16
17#[derive(Clone, Debug)]
18struct GestureState {
19    previous: Option<DynGestureState>,
20    current: DynGestureState,
21}
22
23pub struct MultiTouchDelta {
24    pub zoom: f32,
25    pub translation: Vec2,
26    pub rotation: f32,
27    pub center: Vec2,
28    pub num_touches: usize,
29}
30
31pub struct TouchGestureState {
32    active_touches: BTreeMap<u64, (f32, f32)>,
33    primary_touch_id: Option<u64>,
34    prev_touch_px: Option<(f32, f32)>,
35    touch_start: Option<(web_time::Instant, (f32, f32))>,
36    touch_scroll_accum_x_px: f32,
37    touch_scroll_accum_y_px: f32,
38    touch_scrolled: bool,
39    scroll_capture_id: Option<u64>,
40    gesture_state: Option<GestureState>,
41    past_touch_slop: bool,
42    gesture_kind: Option<GestureKind>,
43    accum_pan: Vec2,
44    accum_zoom: f32,
45    accum_rotation: f32,
46    primary_press_focus: Option<Option<u64>>,
47    pending_primary: Option<(Vec2, u64)>,
48}
49
50/// Which motion a multi-finger gesture committed to. Set once, when the gesture
51/// first travels past slop, so a pinch never also pans.
52#[derive(Clone, Copy, PartialEq, Eq)]
53enum GestureKind {
54    Pan,
55    Zoom,
56    Rotate,
57}
58
59impl Default for TouchGestureState {
60    fn default() -> Self {
61        Self {
62            active_touches: BTreeMap::new(),
63            primary_touch_id: None,
64            prev_touch_px: None,
65            touch_start: None,
66            touch_scroll_accum_x_px: 0.0,
67            touch_scroll_accum_y_px: 0.0,
68            touch_scrolled: false,
69            scroll_capture_id: None,
70            gesture_state: None,
71            past_touch_slop: false,
72            gesture_kind: None,
73            accum_pan: Vec2 { x: 0.0, y: 0.0 },
74            accum_zoom: 1.0,
75            accum_rotation: 0.0,
76            primary_press_focus: None,
77            pending_primary: None,
78        }
79    }
80}
81
82pub struct TouchEnded {
83    pub swipe_right: Option<bool>,
84    /// Focus result of a press dispatched on release. `None` when no press
85    /// ran (scroll/pinch release, cancel); `Some` carries the press's
86    /// focused id (`None` inside means the tap explicitly defocused).
87    pub press: Option<Option<u64>>,
88}
89
90impl TouchGestureState {
91    fn calc_dynamic_state(&self) -> Option<DynGestureState> {
92        let n = self.active_touches.len();
93        if n < 2 {
94            return None;
95        }
96        let n_recip = 1.0 / n as f32;
97        let mut avg_pos = Vec2 { x: 0.0, y: 0.0 };
98        for (x, y) in self.active_touches.values() {
99            avg_pos.x += *x;
100            avg_pos.y += *y;
101        }
102        avg_pos.x *= n_recip;
103        avg_pos.y *= n_recip;
104        let mut avg_distance = 0.0;
105        for (x, y) in self.active_touches.values() {
106            let dx = avg_pos.x - *x;
107            let dy = avg_pos.y - *y;
108            avg_distance += (dx * dx + dy * dy).sqrt();
109        }
110        avg_distance *= n_recip;
111        let first = self.active_touches.values().next().copied()?;
112        let heading = (avg_pos.x - first.0).atan2(avg_pos.y - first.1);
113        Some(DynGestureState {
114            avg_distance: avg_distance.max(1.0),
115            avg_pos,
116            heading,
117        })
118    }
119
120    fn update_gesture(&mut self, pointer_pos: Option<Vec2>, added_or_removed: bool) {
121        if let Some(dyn_state) = self.calc_dynamic_state() {
122            if let Some(state) = &mut self.gesture_state {
123                state.previous = Some(state.current);
124                state.current = dyn_state;
125                if added_or_removed {
126                    state.previous = None;
127                    self.past_touch_slop = false;
128                    self.gesture_kind = None;
129                    self.accum_pan = Vec2 { x: 0.0, y: 0.0 };
130                    self.accum_zoom = 1.0;
131                    self.accum_rotation = 0.0;
132                }
133            } else if pointer_pos.is_some() {
134                self.gesture_state = Some(GestureState {
135                    previous: None,
136                    current: dyn_state,
137                });
138                self.past_touch_slop = false;
139                self.gesture_kind = None;
140                self.accum_pan = Vec2 { x: 0.0, y: 0.0 };
141                self.accum_zoom = 1.0;
142                self.accum_rotation = 0.0;
143                if added_or_removed && let Some(s) = &mut self.gesture_state {
144                    s.previous = None;
145                }
146            }
147        } else {
148            self.gesture_state = None;
149            self.past_touch_slop = false;
150            self.gesture_kind = None;
151            self.accum_pan = Vec2 { x: 0.0, y: 0.0 };
152            self.accum_zoom = 1.0;
153            self.accum_rotation = 0.0;
154        }
155    }
156
157    fn multi_touch_delta(&self) -> Option<(Vec2, f32, f32, Vec2)> {
158        let state = self.gesture_state.as_ref()?;
159        let prev = state.previous.unwrap_or(state.current);
160        let curr = state.current;
161        let zoom = curr.avg_distance / prev.avg_distance;
162        let pan = Vec2 {
163            x: curr.avg_pos.x - prev.avg_pos.x,
164            y: curr.avg_pos.y - prev.avg_pos.y,
165        };
166        let rotation = curr.heading - prev.heading;
167        let rotation = rotation.sin().atan2(rotation.cos());
168        Some((pan, zoom, rotation, curr.avg_pos))
169    }
170
171    pub fn touch_started(
172        &mut self,
173        rt: &mut ReposeRuntime,
174        tid: u64,
175        pos_px: (f32, f32),
176    ) -> Option<u64> {
177        rt.mouse_pos_px = pos_px;
178        let pos = Vec2 {
179            x: pos_px.0,
180            y: pos_px.1,
181        };
182        self.active_touches.insert(tid, pos_px);
183        // Every finger dispatches its own press immediately: games stage
184        // per-finger contacts off these events (GML `device_mouse_*`
185        // parity).
186        let press = rt.handle_touch_press(Self::touch_finger(tid), pos, PointerButton::Primary);
187
188        let is_primary = self.primary_touch_id.is_none();
189        if is_primary {
190            set_touch_gesture_active(true);
191            self.primary_touch_id = Some(tid);
192            self.touch_start = Some((web_time::Instant::now(), pos_px));
193            self.touch_scrolled = false;
194            self.scroll_capture_id = None;
195            self.touch_scroll_accum_x_px = 0.0;
196            self.touch_scroll_accum_y_px = 0.0;
197            self.prev_touch_px = Some(pos_px);
198            self.pending_primary = Some((pos, tid));
199            self.primary_press_focus = Some(press.focused);
200            if self.active_touches.len() >= 2 {
201                self.update_gesture(Some(pos), true);
202            }
203            return press.focused;
204        }
205        if let Some(primary_tid) = self.primary_touch_id {
206            rt.suppress_touch_click(primary_tid);
207        }
208        self.pending_primary = None;
209        if self.active_touches.len() >= 2 {
210            let pointer_pos = self
211                .primary_touch_id
212                .and_then(|pid| self.active_touches.get(&pid).copied())
213                .map(|(x, y)| Vec2 { x, y });
214            self.update_gesture(pointer_pos, true);
215        }
216        None
217    }
218
219    pub fn touch_moved(
220        &mut self,
221        rt: &mut ReposeRuntime,
222        tid: u64,
223        pos_px: (f32, f32),
224        scale: f32,
225    ) -> (
226        bool,
227        Option<(f32, Vec2)>,
228        Option<(Vec2, Vec2)>,
229        Option<(f32, Vec2)>,
230    ) {
231        rt.mouse_pos_px = pos_px;
232        let pos = Vec2 {
233            x: pos_px.0,
234            y: pos_px.1,
235        };
236        let mut dirty;
237        let mut pinch: Option<(f32, Vec2)> = None;
238        let mut pan: Option<(Vec2, Vec2)> = None;
239        let mut rotation: Option<(f32, Vec2)> = None;
240        self.active_touches.insert(tid, pos_px);
241        rt.handle_touch_move(Self::touch_finger(tid), pos);
242        dirty = true;
243
244        if self.active_touches.len() >= 2 {
245            let pointer_pos = self
246                .primary_touch_id
247                .and_then(|pid| self.active_touches.get(&pid).copied())
248                .map(|(x, y)| Vec2 { x, y });
249            self.update_gesture(pointer_pos, false);
250            if let Some((raw_pan, raw_zoom, raw_rot, center)) = self.multi_touch_delta() {
251                let centroid_size = self
252                    .gesture_state
253                    .as_ref()
254                    .map(|s| s.current.avg_distance)
255                    .unwrap_or(1.0);
256                let touch_slop = 18.0 * scale;
257                if !self.past_touch_slop {
258                    self.accum_pan.x += raw_pan.x;
259                    self.accum_pan.y += raw_pan.y;
260                    self.accum_zoom *= raw_zoom;
261                    self.accum_rotation += raw_rot;
262                    let zoom_motion = (self.accum_zoom - 1.0).abs() * centroid_size;
263                    let rotation_motion = self.accum_rotation.abs() * centroid_size;
264                    let pan_motion = (self.accum_pan.x * self.accum_pan.x
265                        + self.accum_pan.y * self.accum_pan.y)
266                        .sqrt();
267                    if zoom_motion > touch_slop
268                        || rotation_motion > touch_slop
269                        || pan_motion > touch_slop
270                    {
271                        self.past_touch_slop = true;
272                        // Whichever motion travelled furthest commits the
273                        // gesture. A real pinch also moves its centroid, so
274                        // without this a pinch pans and zooms at once - the
275                        // view lurches while it scales.
276                        self.gesture_kind = Some(
277                            if zoom_motion >= rotation_motion && zoom_motion >= pan_motion {
278                                GestureKind::Zoom
279                            } else if rotation_motion >= pan_motion {
280                                GestureKind::Rotate
281                            } else {
282                                GestureKind::Pan
283                            },
284                        );
285                    }
286                }
287                match self.gesture_kind {
288                    Some(GestureKind::Zoom) => pinch = Some((raw_zoom, center)),
289                    Some(GestureKind::Rotate) => {
290                        if raw_rot != 0.0 {
291                            rotation = Some((raw_rot, center));
292                        }
293                    }
294                    _ => pan = Some((raw_pan, center)),
295                }
296                if self.past_touch_slop {
297                    self.touch_scrolled = true;
298                    dirty = true;
299                } else {
300                    dirty = false;
301                }
302            }
303            if self.primary_touch_id == Some(tid) {
304                self.prev_touch_px = Some(pos_px);
305            }
306            return (dirty, pinch, pan, rotation);
307        }
308
309        if self.primary_touch_id != Some(tid) {
310            return (dirty, None, None, None);
311        }
312
313        // Tap-slop grace period: while the finger stays within slop of the
314        // press point, swallow the move so a tap cannot jitter the page and
315        // the click survives the release. Only travel past slop turns the
316        // gesture into a drag/scroll, matching Compose `detectTapGestures`
317        // (a dwell time alone never cancels a tap).
318        if let Some((pending_pos, pending_tid)) = self.pending_primary {
319            let slop = TAP_SLOP_DP * scale;
320            let dx = pos_px.0 - pending_pos.x;
321            let dy = pos_px.1 - pending_pos.y;
322            if dx * dx + dy * dy <= slop * slop {
323                self.prev_touch_px = Some(pos_px);
324                return (dirty, None, None, None);
325            }
326            rt.suppress_touch_click(pending_tid);
327            self.pending_primary = None;
328            // Compose's touch slop detector reports only the travel beyond
329            // slop as the first drag delta. Without this a single large move
330            // event that jumps past slop makes the list lurch on frame one.
331            let dist = (dx * dx + dy * dy).sqrt();
332            let excess = ((dist - slop) / dist).max(0.0);
333            self.prev_touch_px = Some((pending_pos.x + dx * excess, pending_pos.y + dy * excess));
334        }
335
336        if let Some(prev) = self.prev_touch_px {
337            let dx_px = pos_px.0 - prev.0;
338            let dy_px = pos_px.1 - prev.1;
339
340            if (dx_px.abs() > 0.0 || dy_px.abs() > 0.0) && !rt.touch_owns_drag(tid) {
341                self.touch_scroll_accum_x_px += dx_px;
342                self.touch_scroll_accum_y_px += dy_px;
343
344                let is_scroll = self.touch_scrolled
345                    || self.touch_scroll_accum_x_px.abs() > 6.0 * scale
346                    || self.touch_scroll_accum_y_px.abs() > 6.0 * scale;
347
348                if is_scroll {
349                    if !self.touch_scrolled {
350                        cancel_flings();
351                    }
352                    let (consumed, cap) = rt.handle_scroll_at(
353                        pos,
354                        Vec2 {
355                            x: -dx_px,
356                            y: -dy_px,
357                        },
358                        self.scroll_capture_id,
359                    );
360                    self.scroll_capture_id = cap;
361
362                    if consumed {
363                        self.touch_scrolled = true;
364                    }
365                }
366            }
367            dirty = true;
368        }
369
370        self.prev_touch_px = Some(pos_px);
371        (dirty, None, None, None)
372    }
373
374    pub fn touch_ended(
375        &mut self,
376        rt: &mut ReposeRuntime,
377        tid: u64,
378        pos_px: (f32, f32),
379        cancelled: bool,
380    ) -> TouchEnded {
381        rt.mouse_pos_px = pos_px;
382        let pos = Vec2 {
383            x: pos_px.0,
384            y: pos_px.1,
385        };
386
387        let is_primary = self.primary_touch_id == Some(tid);
388        if cancelled {
389            rt.handle_touch_cancel_at(tid, pos);
390        } else {
391            rt.handle_touch_release(Self::touch_finger(tid), pos, PointerButton::Primary);
392        }
393        let press = if is_primary && !cancelled {
394            self.pending_primary.take();
395            self.primary_press_focus.take()
396        } else {
397            if is_primary && cancelled {
398                self.pending_primary = None;
399                self.primary_press_focus = None;
400            }
401            None
402        };
403
404        self.active_touches.remove(&tid);
405        if self.active_touches.len() >= 2 {
406            let pointer_pos = self
407                .primary_touch_id
408                .and_then(|pid| self.active_touches.get(&pid).copied())
409                .map(|(x, y)| Vec2 { x, y });
410            self.update_gesture(pointer_pos, true);
411        } else {
412            self.gesture_state = None;
413            self.past_touch_slop = false;
414            self.gesture_kind = None;
415            self.accum_pan = Vec2 { x: 0.0, y: 0.0 };
416            self.accum_zoom = 1.0;
417            self.accum_rotation = 0.0;
418        }
419
420        let mut swipe_right = None;
421        if is_primary {
422            set_touch_gesture_active(false);
423            self.primary_touch_id = None;
424            if let Some((t0, p0)) = self.touch_start.take() {
425                let dt = (web_time::Instant::now() - t0).as_secs_f32();
426                let dx = pos_px.0 - p0.0;
427                let dy = pos_px.1 - p0.1;
428
429                if dt < 0.35 && dy.abs() < 40.0 && dx.abs() > 80.0 && !self.touch_scrolled {
430                    swipe_right = Some(dx > 0.0);
431                }
432            }
433            self.scroll_capture_id = None;
434            self.prev_touch_px = None;
435        }
436        TouchEnded { swipe_right, press }
437    }
438
439    /// Live touch contacts in physical px, keyed by winit touch id.
440    /// Single source for game touch zones (unlike the press
441    /// edge, which fires once and is gone).
442    /// Finger id carried on gesture-dispatched pointer events, so
443    /// game viewports can attribute each touch to its finger.
444    fn touch_finger(tid: u64) -> Option<u64> {
445        Some(tid)
446    }
447
448    pub fn active_touches(&self) -> &BTreeMap<u64, (f32, f32)> {
449        &self.active_touches
450    }
451
452    /// Record a live contact (Started/Moved). Called from
453    /// `handle_touch_raw` before the gesture layer runs.
454    pub fn contact_down(&mut self, tid: u64, pos_px: (f32, f32)) {
455        self.active_touches.insert(tid, pos_px);
456    }
457
458    /// Drop a live contact (Ended/Cancelled). Called from
459    /// `handle_touch_raw` before the gesture layer runs.
460    pub fn contact_up(&mut self, tid: u64) {
461        self.active_touches.remove(&tid);
462    }
463
464    pub fn multi_touch_info(&self) -> Option<MultiTouchDelta> {
465        let state = self.gesture_state.as_ref()?;
466        let prev = state.previous.unwrap_or(state.current);
467        let curr = state.current;
468        let zoom = curr.avg_distance / prev.avg_distance;
469        let translation = Vec2 {
470            x: curr.avg_pos.x - prev.avg_pos.x,
471            y: curr.avg_pos.y - prev.avg_pos.y,
472        };
473        let rotation = curr.heading - prev.heading;
474        let rotation = rotation.sin().atan2(rotation.cos());
475        Some(MultiTouchDelta {
476            zoom,
477            translation,
478            rotation,
479            center: curr.avg_pos,
480            num_touches: self.active_touches.len(),
481        })
482    }
483}
484
485#[cfg(test)]
486mod tests {
487    use super::*;
488    use std::cell::RefCell;
489    use std::rc::Rc;
490
491    /// A twist travels furthest around the centroid, so it must commit the
492    /// gesture to rotation and report nothing else. When the channels were
493    /// independent a twist also zoomed and panned, so the view lurched while
494    /// it turned.
495    #[test]
496    fn twist_reports_rotation_once_past_slop() {
497        let mut rt = ReposeRuntime::new();
498        let mut g = TouchGestureState::default();
499        g.touch_started(&mut rt, 0, (0.0, 0.0));
500        g.touch_started(&mut rt, 1, (100.0, 0.0));
501        let (_, _, _, rotation) = g.touch_moved(&mut rt, 1, (100.0, 20.0), 1.0);
502        let _ = rotation;
503        let (_, _, _, _) = g.touch_moved(&mut rt, 1, (50.0, 80.0), 1.0);
504        let (dirty, pinch, pan, rotation) = g.touch_moved(&mut rt, 1, (0.0, 100.0), 1.0);
505        assert!(dirty, "twist past slop must mark dirty");
506        assert!(pinch.is_none(), "a twist must not also zoom");
507        assert!(pan.is_none(), "a twist must not also pan");
508        let (delta_rot, center) = rotation.expect("rotation must be propagated, not dropped");
509        assert!(
510            delta_rot.abs() > 0.1,
511            "expected non-trivial twist, got {delta_rot}"
512        );
513        assert!(center.x.is_finite() && center.y.is_finite());
514        let info = g.multi_touch_info().expect("info mirrors deltas");
515        assert!(info.rotation.abs() > 0.0);
516    }
517
518    /// The mirror image: a pure pinch (fingers moving apart without the
519    /// centroid following) must commit to zoom and not slide the view.
520    #[test]
521    fn pinch_reports_zoom_once_past_slop() {
522        let mut rt = ReposeRuntime::new();
523        let mut g = TouchGestureState::default();
524        g.touch_started(&mut rt, 0, (40.0, 50.0));
525        g.touch_started(&mut rt, 1, (60.0, 50.0));
526        // Spread the fingers to 3x their separation while the centroid holds.
527        let (dirty, pinch, pan, _) = g.touch_moved(&mut rt, 1, (70.0, 50.0), 1.0);
528        g.touch_moved(&mut rt, 0, (30.0, 50.0), 1.0);
529        let (dirty, pinch, pan, _) = g.touch_moved(&mut rt, 1, (90.0, 50.0), 1.0);
530        assert!(dirty, "pinch past slop must mark dirty");
531        assert!(pinch.is_some(), "pinch must report zoom");
532        assert!(pan.is_none(), "a pinch must not also pan");
533    }
534
535    #[test]
536    fn pure_pinch_reports_no_rotation_spam() {
537        let mut rt = ReposeRuntime::new();
538        let mut g = TouchGestureState::default();
539        g.touch_started(&mut rt, 0, (0.0, 0.0));
540        g.touch_started(&mut rt, 1, (100.0, 0.0));
541        let (_, _, _, _) = g.touch_moved(&mut rt, 1, (140.0, 0.0), 1.0);
542        let (dirty, pinch, _, rotation) = g.touch_moved(&mut rt, 1, (180.0, 0.0), 1.0);
543        assert!(dirty);
544        assert!(pinch.is_some());
545        assert!(
546            rotation.is_none(),
547            "exact-zero rotation must not spam Rotate gestures"
548        );
549    }
550
551    #[test]
552    fn second_finger_down_registers_before_any_move() {
553        let mut rt = ReposeRuntime::new();
554        let mut g = TouchGestureState::default();
555        g.contact_down(1, (10.0, 10.0));
556        g.touch_started(&mut rt, 1, (10.0, 10.0));
557        g.contact_down(2, (200.0, 200.0));
558        g.touch_started(&mut rt, 2, (200.0, 200.0));
559        assert_eq!(
560            g.active_touches().len(),
561            2,
562            "both fingers visible while held still"
563        );
564        assert!(
565            g.active_touches().contains_key(&1) && g.active_touches().contains_key(&2),
566            "no finger dropped before its first move"
567        );
568    }
569
570    #[test]
571    fn every_finger_dispatches_its_own_press_move_release() {
572        use repose_core::input::{PointerEvent, PointerEventKind, PointerKind};
573        use std::collections::HashMap;
574        let mut rt = ReposeRuntime::new();
575        let seen: Rc<RefCell<HashMap<u64, Vec<PointerEventKind>>>> =
576            Rc::new(RefCell::new(HashMap::new()));
577        let seen_down = seen.clone();
578        let mk = move |_kind: PointerKind| {
579            let seen_down = seen_down.clone();
580            Rc::new(move |ev: PointerEvent| {
581                seen_down
582                    .borrow_mut()
583                    .entry(ev.id.0)
584                    .or_default()
585                    .push(ev.event);
586            })
587        };
588        rt.cache_frame(repose_core::runtime::Frame {
589            scene: Default::default(),
590            hit_regions: vec![repose_core::HitRegion {
591                id: 1,
592                rect: repose_core::Rect {
593                    x: 0.0,
594                    y: 0.0,
595                    w: 400.0,
596                    h: 400.0,
597                },
598                on_pointer_down: Some(mk(PointerKind::Touch)),
599                on_pointer_move: Some(mk(PointerKind::Touch)),
600                on_pointer_up: Some(mk(PointerKind::Touch)),
601                ..Default::default()
602            }],
603            semantics_nodes: Vec::new(),
604            focus_chain: Vec::new(),
605        });
606        let mut g = TouchGestureState::default();
607        g.touch_started(&mut rt, 1, (10.0, 10.0));
608        g.touch_started(&mut rt, 2, (200.0, 200.0));
609        g.touch_moved(&mut rt, 1, (12.0, 10.0), 1.0);
610        g.touch_moved(&mut rt, 2, (200.0, 202.0), 1.0);
611        g.touch_ended(&mut rt, 1, (12.0, 10.0), false);
612        g.touch_ended(&mut rt, 2, (200.0, 202.0), false);
613        let seen = seen.borrow();
614        for fid in [1u64, 2u64] {
615            let kinds: Vec<_> = seen.get(&fid).cloned().unwrap_or_default();
616            assert!(
617                kinds.iter().any(|k| matches!(k, PointerEventKind::Down(_))),
618                "finger {fid} must dispatch its own press, got {kinds:?}"
619            );
620            assert!(
621                kinds.iter().any(|k| matches!(k, PointerEventKind::Move)),
622                "finger {fid} must dispatch its own move, got {kinds:?}"
623            );
624            assert!(
625                kinds.iter().any(|k| matches!(k, PointerEventKind::Up(_))),
626                "finger {fid} must dispatch its own release, got {kinds:?}"
627            );
628        }
629        assert!(
630            rt.touch_paths.is_empty(),
631            "both finger paths must drop on release"
632        );
633    }
634}