Skip to main content

cranpose_app_shell/
touch_router.rs

1//! Fingers of a platform that tells them apart, routed to the shell's
2//! pointers: the first finger down drives the primary pointer, and each
3//! finger that joins it a secondary pointer of its own, until the gesture
4//! ends.
5
6use std::fmt::Debug;
7
8use cranpose_foundation::PointerId;
9use cranpose_render_common::Renderer;
10
11use crate::{AppShell, PointerSource};
12
13/// One sample of a finger, or the mouse: where it was, in logical pixels,
14/// and the platform's time of the sample in milliseconds, where the
15/// platform gives one.
16#[derive(Clone, Copy, Debug, PartialEq)]
17pub struct TouchSample {
18    /// Horizontal position, growing to the right.
19    pub x: f32,
20    /// Vertical position, growing downward.
21    pub y: f32,
22    /// The platform's time of the sample, in milliseconds.
23    pub time_ms: Option<i64>,
24}
25
26impl TouchSample {
27    /// A sample at `(x, y)` with no platform time.
28    pub fn new(x: f32, y: f32) -> Self {
29        Self {
30            x,
31            y,
32            time_ms: None,
33        }
34    }
35
36    /// The sample with the platform's time of it, in milliseconds.
37    pub fn with_time_ms(self, time_ms: Option<i64>) -> Self {
38        Self { time_ms, ..self }
39    }
40}
41
42/// Which shell pointer a finger drives.
43enum Route {
44    Primary,
45    Secondary(PointerId),
46    Untracked,
47}
48
49/// Routes the fingers on one surface to the shell's primary and secondary
50/// pointers. `F` is the platform's identity of a finger. `None` stands for
51/// a mouse, which always drives the primary pointer.
52///
53/// Each method returns whether the shell changed and needs a frame.
54#[derive(Debug)]
55pub struct TouchRouter<F> {
56    primary: Option<F>,
57    /// The fingers that joined the primary one, in the order they came,
58    /// with the secondary pointer each drives.
59    secondaries: Vec<(F, PointerId)>,
60    next_secondary_id: PointerId,
61}
62
63impl<F> Default for TouchRouter<F> {
64    fn default() -> Self {
65        Self {
66            primary: None,
67            secondaries: Vec::new(),
68            next_secondary_id: PointerId::PRIMARY,
69        }
70    }
71}
72
73impl<F: Copy + Eq> TouchRouter<F> {
74    /// A finger, or the mouse, went down at `sample`.
75    pub fn press<R: Renderer<Error: Debug>>(
76        &mut self,
77        shell: &mut AppShell<R>,
78        finger: Option<F>,
79        sample: TouchSample,
80    ) -> bool {
81        let TouchSample { x, y, time_ms } = sample;
82        match self.route_press(finger) {
83            Route::Primary => {
84                let event_time = shell.realtime_pointer_event_time(time_ms);
85                shell.set_cursor_at_event_time(x, y, event_time);
86                shell.pointer_pressed_at_event_time(event_time)
87            }
88            Route::Secondary(id) => shell.secondary_pointer_pressed(id, x, y, time_ms),
89            Route::Untracked => false,
90        }
91    }
92
93    /// A finger, or the mouse, moved to `sample`. A finger that is not down
94    /// moves nothing.
95    pub fn moved<R: Renderer<Error: Debug>>(
96        &self,
97        shell: &mut AppShell<R>,
98        finger: Option<F>,
99        sample: TouchSample,
100    ) -> bool {
101        let TouchSample { x, y, time_ms } = sample;
102        match self.route(finger) {
103            Route::Primary => shell.set_cursor_at_time(x, y, time_ms),
104            Route::Secondary(id) => shell.secondary_pointer_moved(id, x, y, time_ms),
105            Route::Untracked => false,
106        }
107    }
108
109    /// A finger, or the mouse, lifted at `sample`. The primary finger's lift
110    /// ends the gesture: the secondary fingers are released first, there, and
111    /// the next finger down drives the primary pointer.
112    pub fn release<R: Renderer<Error: Debug>>(
113        &mut self,
114        shell: &mut AppShell<R>,
115        finger: Option<F>,
116        sample: TouchSample,
117    ) -> bool {
118        let TouchSample { x, y, time_ms } = sample;
119        let Some(finger) = finger else {
120            return release_primary(shell, x, y, time_ms);
121        };
122        if self.primary == Some(finger) {
123            let mut changed = false;
124            for (_, id) in self.secondaries.drain(..) {
125                changed |= shell.secondary_pointer_released(id, x, y, time_ms);
126            }
127            self.end_gesture();
128            return release_primary(shell, x, y, time_ms) | changed;
129        }
130        if let Some(id) = self.take_secondary(finger) {
131            return shell.secondary_pointer_released(id, x, y, time_ms);
132        }
133        // A lift after the gesture ended, as some platforms send one per
134        // finger: only a lift with no gesture running reaches the shell.
135        self.is_idle() && release_primary(shell, x, y, time_ms)
136    }
137
138    /// A finger, or the mouse, left without lifting: the system took the
139    /// touch, or it left the surface. The primary finger's leaving cancels
140    /// the gesture. A secondary finger is released at `position`, or at the
141    /// origin when the platform gives none.
142    pub fn cancel<R: Renderer<Error: Debug>>(
143        &mut self,
144        shell: &mut AppShell<R>,
145        finger: Option<F>,
146        position: Option<(f32, f32)>,
147    ) -> bool {
148        let secondary = finger
149            .filter(|finger| self.primary != Some(*finger))
150            .and_then(|finger| self.take_secondary(finger));
151        if let Some(id) = secondary {
152            shell.set_pointer_source(PointerSource::Touch);
153            let (x, y) = position.unwrap_or((0.0, 0.0));
154            return shell.secondary_pointer_released(id, x, y, None);
155        }
156        let ends_gesture = finger.is_none() || self.primary == finger || self.is_idle();
157        if ends_gesture {
158            self.end_gesture();
159            shell.cancel_gesture();
160        }
161        ends_gesture
162    }
163
164    fn route_press(&mut self, finger: Option<F>) -> Route {
165        let Some(finger) = finger else {
166            return Route::Primary;
167        };
168        match self.primary {
169            None => {
170                self.primary = Some(finger);
171                Route::Primary
172            }
173            Some(primary) if primary == finger => Route::Primary,
174            Some(_) => Route::Secondary(self.secondary_id(finger).unwrap_or_else(|| {
175                self.next_secondary_id = PointerId(self.next_secondary_id.0 + 1);
176                self.secondaries.push((finger, self.next_secondary_id));
177                self.next_secondary_id
178            })),
179        }
180    }
181
182    fn route(&self, finger: Option<F>) -> Route {
183        match finger {
184            None => Route::Primary,
185            Some(finger) if self.primary == Some(finger) => Route::Primary,
186            Some(finger) => self
187                .secondary_id(finger)
188                .map_or(Route::Untracked, Route::Secondary),
189        }
190    }
191
192    fn secondary_id(&self, finger: F) -> Option<PointerId> {
193        self.secondaries
194            .iter()
195            .find(|(tracked, _)| *tracked == finger)
196            .map(|(_, id)| *id)
197    }
198
199    fn take_secondary(&mut self, finger: F) -> Option<PointerId> {
200        let index = self
201            .secondaries
202            .iter()
203            .position(|(tracked, _)| *tracked == finger)?;
204        Some(self.secondaries.remove(index).1)
205    }
206
207    fn is_idle(&self) -> bool {
208        self.primary.is_none() && self.secondaries.is_empty()
209    }
210
211    fn end_gesture(&mut self) {
212        self.primary = None;
213        self.secondaries.clear();
214        self.next_secondary_id = PointerId::PRIMARY;
215    }
216}
217
218fn release_primary<R: Renderer<Error: Debug>>(
219    shell: &mut AppShell<R>,
220    x: f32,
221    y: f32,
222    time_ms: Option<i64>,
223) -> bool {
224    let event_time = shell.realtime_pointer_event_time(time_ms);
225    shell.pointer_released_at_position_event_time(x, y, event_time)
226}