Skip to main content

xrack_runtime/
pointer.rs

1use crate::{KeyModifiers, Length, ListModel, Property, RowKey, RowLifetime, VecModel};
2use std::{
3    cell::{Cell, OnceCell},
4    fmt,
5    ops::Range,
6    rc::Rc,
7};
8
9#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
10pub enum PointerEventKind {
11    Down,
12    Move,
13    Up,
14    #[default]
15    Cancel,
16}
17
18#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
19pub enum PointerButton {
20    #[default]
21    Primary,
22    Secondary,
23    Middle,
24}
25
26/// A set of buttons accepted by a TouchArea.
27#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
28pub struct PointerButtons(u8);
29
30impl PointerButtons {
31    pub fn contains(self, button: PointerButton) -> bool {
32        self.0 & (1 << button as u8) != 0
33    }
34}
35
36impl<const N: usize> From<[PointerButton; N]> for PointerButtons {
37    fn from(buttons: [PointerButton; N]) -> Self {
38        buttons.into_iter().collect()
39    }
40}
41
42impl FromIterator<PointerButton> for PointerButtons {
43    fn from_iter<T: IntoIterator<Item = PointerButton>>(buttons: T) -> Self {
44        Self(
45            buttons
46                .into_iter()
47                .fold(0, |mask, button| mask | (1 << button as u8)),
48        )
49    }
50}
51
52#[derive(Clone, Copy, Debug, Default, PartialEq)]
53pub struct PointerEvent {
54    pub kind: PointerEventKind,
55    pub button: PointerButton,
56    pub x: Length,
57    pub y: Length,
58    pub inside: bool,
59    pub is_touch: bool,
60    /// Positive while a touch contact is active. Mouse events use zero.
61    pub touch_finger_id: i64,
62    pub modifiers: KeyModifiers,
63}
64
65#[derive(Clone, Copy, Debug, Default, PartialEq)]
66pub struct TouchPoint {
67    pub id: i64,
68    pub x: Length,
69    pub y: Length,
70    pub start_x: Length,
71    pub start_y: Length,
72    pub inside: bool,
73}
74
75/// Read-only, reactive rows in contact order. Cloning shares the same rows.
76#[derive(Clone, Debug, Default, PartialEq, Eq)]
77pub struct TouchPoints(VecModel<TouchPoint>);
78
79impl From<Vec<TouchPoint>> for TouchPoints {
80    fn from(points: Vec<TouchPoint>) -> Self {
81        Self(points.into())
82    }
83}
84
85impl TouchPoints {
86    pub fn snapshot(&self) -> Vec<TouchPoint> {
87        self.0.snapshot()
88    }
89
90    #[doc(hidden)]
91    pub fn snapshot_untracked(&self) -> Vec<TouchPoint> {
92        self.0.snapshot_untracked()
93    }
94
95    #[doc(hidden)]
96    pub fn into_snapshot(self) -> Vec<TouchPoint> {
97        self.0.into_snapshot()
98    }
99
100    #[doc(hidden)]
101    pub fn values_eq(&self, other: &Self) -> bool {
102        self.0.values_eq(&other.0)
103    }
104
105    #[doc(hidden)]
106    pub fn values_eq_owned(self, other: Self) -> bool {
107        self.0.values_eq_owned(other.0)
108    }
109}
110
111impl ListModel for TouchPoints {
112    type Item = TouchPoint;
113
114    fn row_count(&self) -> usize {
115        self.0.row_count()
116    }
117
118    fn item(&self, row: usize) -> TouchPoint {
119        self.0.item(row)
120    }
121
122    fn row_key(&self, row: usize) -> RowKey {
123        ListModel::row_key(&self.0, row)
124    }
125
126    fn row_lifetime(&self, key: RowKey) -> RowLifetime {
127        self.0.row_lifetime(key)
128    }
129
130    fn structure_stamp(&self) -> (u64, u64) {
131        self.0.structure_stamp()
132    }
133
134    fn contents_stamp(&self) -> (u64, u64) {
135        self.0.contents_stamp()
136    }
137
138    fn index_of_key(&self, key: RowKey) -> Option<usize> {
139        self.0.index_of_key(key)
140    }
141
142    fn visit_items(&self, visit: impl FnMut(usize, RowKey, &TouchPoint)) {
143        self.0.visit_items(visit);
144    }
145
146    fn visit_row_keys(&self, range: Range<usize>, visit: impl FnMut(RowKey)) {
147        self.0.visit_row_keys(range, visit);
148    }
149}
150
151#[derive(Default)]
152struct PointerState {
153    pressed: Property<bool>,
154    contains_press: Property<bool>,
155    has_hover: Property<bool>,
156    mouse_x: Property<Length>,
157    mouse_y: Property<Length>,
158    pressed_x: Property<Length>,
159    pressed_y: Property<Length>,
160    mouse_press: Cell<Option<bool>>,
161    touch_points: OnceCell<VecModel<TouchPoint>>,
162}
163
164/// Reactive state and identity of a TouchArea in one component instance.
165#[derive(Clone, Default)]
166#[doc(hidden)]
167pub struct PointerHandle(Rc<PointerState>);
168
169impl fmt::Debug for PointerHandle {
170    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
171        f.debug_struct("PointerHandle").finish_non_exhaustive()
172    }
173}
174
175impl PartialEq for PointerHandle {
176    fn eq(&self, other: &Self) -> bool {
177        Rc::ptr_eq(&self.0, &other.0)
178    }
179}
180
181impl PointerHandle {
182    pub fn pressed(&self) -> bool {
183        self.0.pressed.get(|| false)
184    }
185
186    pub fn contains_press(&self) -> bool {
187        self.0.contains_press.get(|| false)
188    }
189
190    pub fn has_hover(&self) -> bool {
191        self.0.has_hover.get(|| false)
192    }
193
194    pub fn mouse_x(&self) -> Length {
195        self.0.mouse_x.get(Length::default)
196    }
197
198    pub fn mouse_y(&self) -> Length {
199        self.0.mouse_y.get(Length::default)
200    }
201
202    pub fn pressed_x(&self) -> Length {
203        self.0.pressed_x.get(Length::default)
204    }
205
206    pub fn pressed_y(&self) -> Length {
207        self.0.pressed_y.get(Length::default)
208    }
209
210    pub fn active_touch_count(&self) -> i64 {
211        self.touch_model().len() as i64
212    }
213
214    pub fn touch_points(&self) -> TouchPoints {
215        TouchPoints(self.touch_model().clone())
216    }
217
218    fn touch_model(&self) -> &VecModel<TouchPoint> {
219        self.0.touch_points.get_or_init(VecModel::default)
220    }
221
222    pub fn publish_hover(&self, position: Option<(Length, Length)>) {
223        if let Some((x, y)) = position {
224            self.0.mouse_x.set_if_changed(x);
225            self.0.mouse_y.set_if_changed(y);
226        }
227        self.0.has_hover.set_if_changed(position.is_some());
228    }
229
230    pub fn publish_event(&self, event: &PointerEvent) {
231        use PointerEventKind::{Cancel, Down, Move, Up};
232
233        if event.kind != Cancel {
234            self.0.mouse_x.set_if_changed(event.x);
235            self.0.mouse_y.set_if_changed(event.y);
236        }
237        if event.kind == Down {
238            self.0.pressed_x.set_if_changed(event.x);
239            self.0.pressed_y.set_if_changed(event.y);
240        }
241        if event.touch_finger_id != 0 {
242            let points = self.touch_model();
243            let mut row = None;
244            points.visit_rows_untracked(usize::MAX, |index, _, point| {
245                if point.id == event.touch_finger_id {
246                    row = Some((index, *point));
247                }
248            });
249            match event.kind {
250                Down | Move => {
251                    if let Some((index, point)) = row {
252                        points.set_row(
253                            index,
254                            TouchPoint {
255                                x: event.x,
256                                y: event.y,
257                                inside: event.inside,
258                                ..point
259                            },
260                        );
261                    } else if event.kind == Down {
262                        points.push(TouchPoint {
263                            id: event.touch_finger_id,
264                            x: event.x,
265                            y: event.y,
266                            start_x: event.x,
267                            start_y: event.y,
268                            inside: event.inside,
269                        });
270                    }
271                }
272                Up | Cancel => {
273                    if let Some((index, _)) = row {
274                        points.remove(index);
275                    }
276                }
277            }
278        } else {
279            match event.kind {
280                Down => self.0.mouse_press.set(Some(event.inside)),
281                Move if self.0.mouse_press.get().is_some() => {
282                    self.0.mouse_press.set(Some(event.inside))
283                }
284                Up | Cancel => self.0.mouse_press.set(None),
285                Move => {}
286            }
287        }
288        let mouse = self.0.mouse_press.get();
289        let mut inside = mouse.unwrap_or(false);
290        let mut pressed = mouse.is_some();
291        if let Some(points) = self.0.touch_points.get() {
292            points.visit_rows_untracked(usize::MAX, |_, _, point| {
293                pressed = true;
294                inside |= point.inside;
295            });
296        }
297        self.0.pressed.set_if_changed(pressed);
298        self.0.contains_press.set_if_changed(inside);
299    }
300}