1use crate::{Interaction, LayoutNode, Point, Target};
2use std::time::{Duration, Instant};
3use xrack_runtime::{
4 Component, KeyModifiers, Length, Node, PointerButton, PointerEvent, PointerEventKind,
5 PointerHandle,
6};
7
8pub(crate) const PRESS_AND_HOLD_SLOP: f32 = 6.0;
9
10pub fn pointer_click_follows(previous: (Point, Instant), current: (Point, Instant)) -> bool {
11 current
12 .1
13 .checked_duration_since(previous.1)
14 .is_some_and(|elapsed| elapsed <= Duration::from_millis(450))
15 && (current.0.x - previous.0.x).hypot(current.0.y - previous.0.y) <= 6.0
16}
17
18#[doc(hidden)]
20pub struct ButtonClick<Device> {
21 target: Target,
22 kind: &'static str,
23 device: Device,
24 sample: (Point, Instant),
25}
26
27impl<Device: PartialEq> ButtonClick<Device> {
28 pub fn new(
29 scene: &Node,
30 target: &Target,
31 device: Device,
32 sample: (Point, Instant),
33 ) -> Option<Self> {
34 let kind = target.node_in(scene)?.kind;
35 matches!(kind, "Button" | "RoundButton" | "ToolButton").then(|| Self {
36 target: target.clone(),
37 kind,
38 device,
39 sample,
40 })
41 }
42
43 pub fn follows(&self, previous: &Self) -> bool {
44 self.device == previous.device
45 && self.kind == previous.kind
46 && self.target == previous.target
47 && pointer_click_follows(previous.sample, self.sample)
48 }
49
50 pub fn deliver(
52 self,
53 component: &mut impl Component,
54 input: &Interaction,
55 scene: &Node,
56 layout: &LayoutNode,
57 ) -> bool {
58 !input.menu_open()
59 && !input.choice_open()
60 && self
61 .target
62 .node_in(scene)
63 .is_some_and(|node| node.kind == self.kind)
64 && crate::input::valid(&self.target, scene, layout)
65 && input
66 .accessibility_target(scene, layout, &self.target.path)
67 .as_ref()
68 == Some(&self.target)
69 && component.dispatch_at(scene, &self.target.path, "double-clicked")
70 }
71}
72
73#[cfg(test)]
74mod button_click_tests {
75 use super::*;
76 use xrack_runtime::VecModel;
77
78 #[test]
79 fn button_click_pairs_respect_time_distance_device_and_virtual_row() {
80 let rows = VecModel::from(vec![10_i64, 20]);
81 let mut scene = Node::new("Window", None);
82 let mut row = Node::new("ListRow", None);
83 row.children.push(Node::new("Button", Some("button")));
84 scene.children.push(row);
85 let path = &[0, 0];
86 let start = Instant::now();
87 let point = Point { x: 10.0, y: 10.0 };
88 let click = |scene: &Node, device, point, time| {
89 let button = scene.at_path(path).unwrap();
90 let target = Target::from_node(path.to_vec(), button, true, scene.row_key_at(path));
91 ButtonClick::new(scene, &target, device, (point, time)).unwrap()
92 };
93 scene.children[0].set_row_key(rows.row_key(0));
94 let first = click(&scene, false, point, start);
95 let edge = start + Duration::from_millis(450);
96 assert!(click(&scene, false, Point { x: 16.0, ..point }, edge).follows(&first));
97 assert!(!click(&scene, false, Point { x: 16.1, ..point }, edge).follows(&first));
98 assert!(!click(&scene, false, point, edge + Duration::from_millis(1)).follows(&first));
99 assert!(!click(&scene, true, point, edge).follows(&first));
100 scene.children[0].set_row_key(rows.row_key(1));
101 assert!(!click(&scene, false, point, edge).follows(&first));
102 }
103}
104
105enum PressAndHold {
106 Pending {
107 origin: Point,
108 point: Point,
109 deadline: Instant,
110 },
111 Triggered,
112}
113
114pub struct PointerSequence {
116 target: Target,
117 handle: PointerHandle,
118 last: PointerEvent,
119 press_and_hold: Option<PressAndHold>,
120}
121
122pub struct PointerDelivery {
123 target: Target,
124 handle: PointerHandle,
125 pub event: PointerEvent,
126}
127
128impl PointerDelivery {
129 pub fn apply(self, component: &mut impl Component, scene: &Node) -> bool {
130 let live = live_handler(scene, &self.target, &self.handle);
131 if live || self.event.kind == PointerEventKind::Cancel {
132 self.handle.publish_event(&self.event);
133 }
134 if live {
135 component.pointer_event_at(scene, &self.target.path, &self.event);
136 if self.event.kind == PointerEventKind::Move {
137 component.dispatch_at(scene, &self.target.path, "moved");
138 }
139 }
140 live
141 }
142}
143
144pub(crate) fn local_position(item: &LayoutNode, point: Point) -> Option<(Point, Length, Length)> {
145 let local = item.map_from_window(point)?;
146 (local.x.is_finite() && local.y.is_finite()).then(|| {
147 (
148 local,
149 Length(f64::from(local.x - item.bounds.x)),
150 Length(f64::from(local.y - item.bounds.y)),
151 )
152 })
153}
154
155fn live_handler(scene: &Node, target: &Target, handle: &PointerHandle) -> bool {
156 target
157 .node_in(scene)
158 .is_some_and(|node| node.pointer_handle.as_ref() == Some(handle))
159}
160
161impl PointerSequence {
162 pub(crate) fn begin(
163 target: Target,
164 input: &Interaction,
165 scene: &Node,
166 layout: &LayoutNode,
167 point: Point,
168 event: PointerEvent,
169 now: Instant,
170 ) -> Option<(Self, PointerDelivery)> {
171 let node = scene.interactive_at_path(&target.path)?;
172 if node.kind != "TouchArea" {
173 return None;
174 }
175 let mut sequence = Self {
176 handle: node.pointer_handle.clone()?,
177 target,
178 last: event,
179 press_and_hold: None,
180 };
181 let delivery = sequence.sample(
182 input,
183 scene,
184 layout,
185 point,
186 PointerEventKind::Down,
187 event.modifiers,
188 )?;
189 if node.press_and_hold_handler && event.button == PointerButton::Primary {
190 let interval = node.int("press-and-hold-interval").unwrap_or(800);
191 if interval > 0
192 && let Some(deadline) = now.checked_add(Duration::from_millis(interval as u64))
193 {
194 sequence.press_and_hold = Some(PressAndHold::Pending {
195 origin: point,
196 point,
197 deadline,
198 });
199 }
200 }
201 Some((sequence, delivery))
202 }
203
204 pub fn target(&self) -> &Target {
205 &self.target
206 }
207
208 pub fn is_live(&self, input: &Interaction, scene: &Node, layout: &LayoutNode) -> bool {
209 let path = &self.target.path;
210 live_handler(scene, &self.target, &self.handle)
211 && scene
212 .interactive_at_path(path)
213 .is_some_and(|node| node.accepts_pointer_button(self.last.button))
214 && layout
215 .at_path(path)
216 .is_some_and(|item| item.visible && item.enabled)
217 && input.allows_popup(layout, path)
218 && !input.menu_open()
219 && !input.choice_open()
220 }
221
222 pub fn press_and_hold_deadline(&self) -> Option<Instant> {
223 match self.press_and_hold {
224 Some(PressAndHold::Pending { deadline, .. }) => Some(deadline),
225 _ => None,
226 }
227 }
228
229 pub fn disable_press_and_hold(&mut self) {
230 if self.press_and_hold_deadline().is_some() {
231 self.press_and_hold = None;
232 }
233 }
234
235 pub fn press_and_hold_triggered(&self) -> bool {
236 matches!(self.press_and_hold, Some(PressAndHold::Triggered))
237 }
238
239 fn update_hold_position(&mut self, point: Point, inside: bool) {
240 if let Some(PressAndHold::Pending {
241 origin,
242 point: previous,
243 ..
244 }) = &mut self.press_and_hold
245 {
246 if inside && (point.x - origin.x).hypot(point.y - origin.y) <= PRESS_AND_HOLD_SLOP {
247 *previous = point;
248 } else {
249 self.press_and_hold = None;
250 }
251 }
252 }
253
254 pub fn constrain_press_and_hold(&mut self, layout: &LayoutNode, position: Option<Point>) {
255 if let Some(PressAndHold::Pending { point, .. }) = self.press_and_hold {
256 let point = position.unwrap_or(point);
257 let inside = layout.at_path(&self.target.path).is_some_and(|item| {
258 item.contains_clip_point(point)
259 && item
260 .map_from_window(point)
261 .is_some_and(|local| item.bounds.contains(local))
262 });
263 self.update_hold_position(point, inside);
264 }
265 }
266
267 pub fn advance_press_and_hold(
268 &mut self,
269 input: &Interaction,
270 scene: &Node,
271 layout: &LayoutNode,
272 component: &mut impl Component,
273 now: Instant,
274 ) -> bool {
275 if self
276 .press_and_hold_deadline()
277 .is_none_or(|deadline| now < deadline)
278 {
279 return false;
280 }
281 self.constrain_press_and_hold(layout, None);
282 let pending = self.press_and_hold.take().is_some();
283 if pending
284 && !input.direct_pointer_claimed()
285 && input.drag_position().is_none()
286 && self.is_live(input, scene, layout)
287 && component.dispatch_at(scene, &self.target.path, "press-and-hold")
288 {
289 self.press_and_hold = Some(PressAndHold::Triggered);
290 true
291 } else {
292 false
293 }
294 }
295
296 pub fn sample(
297 &mut self,
298 input: &Interaction,
299 scene: &Node,
300 layout: &LayoutNode,
301 point: Point,
302 kind: PointerEventKind,
303 modifiers: KeyModifiers,
304 ) -> Option<PointerDelivery> {
305 if !self.is_live(input, scene, layout) {
306 return None;
307 }
308 let item = layout.at_path(&self.target.path)?;
309 let (local, x, y) = local_position(item, point)?;
310 self.last = PointerEvent {
311 kind,
312 x,
313 y,
314 inside: item.bounds.contains(local) && item.contains_clip_point(point),
315 modifiers,
316 ..self.last
317 };
318 if matches!(kind, PointerEventKind::Up | PointerEventKind::Cancel) {
319 if self.press_and_hold_deadline().is_some() {
320 self.press_and_hold = None;
321 }
322 } else {
323 self.update_hold_position(point, self.last.inside);
324 }
325 Some(PointerDelivery {
326 target: self.target.clone(),
327 handle: self.handle.clone(),
328 event: self.last,
329 })
330 }
331
332 pub fn cancel(self, modifiers: KeyModifiers) -> PointerDelivery {
333 PointerDelivery {
334 target: self.target,
335 handle: self.handle,
336 event: PointerEvent {
337 kind: PointerEventKind::Cancel,
338 inside: false,
339 modifiers,
340 ..self.last
341 },
342 }
343 }
344}