teksilo_core/widget_tree/pointer_state.rs
1// SPDX-License-Identifier: MPL-2.0
2// SPDX-FileCopyrightText: 2026 FernTech
3
4//! Pointer / hover / capture / gesture-owner state: the per-node probes
5//! the router consults, the per-pointer `PointerSequence` arbitration that
6//! enrols the competing ancestors, and the gesture-recognizer tick that
7//! drives them.
8
9use super::*;
10use crate::pointer::touch_action::{Axis, PanClaim, TouchAction};
11
12impl WidgetTree {
13 /// This tree's input clock — the one source of
14 /// [`EventTime`](crate::pointer::EventTime)s for everything the pointer
15 /// path does.
16 ///
17 /// A [`MonotonicClock`](crate::pointer::clock::MonotonicClock) anchored at
18 /// the tree epoch by default. The epoch is the same `Instant`
19 /// [`simulated_now`](Self::simulated_now) starts at, so the input timeline
20 /// and the simulated animation timeline are one axis rather than two.
21 pub fn input_clock(&self) -> std::rc::Rc<dyn crate::pointer::clock::InputClock> {
22 self.input_clock.clone()
23 }
24
25 /// Replace the input clock.
26 ///
27 /// A headless test installs a
28 /// [`ManualClock`](crate::pointer::clock::ManualClock) here so gesture
29 /// deadlines fire exactly when it says, with no sleeping and no dependence
30 /// on how long the test itself took.
31 pub fn set_input_clock(&mut self, clock: std::rc::Rc<dyn crate::pointer::clock::InputClock>) {
32 self.input_clock = clock;
33 // The axis just changed underneath. Any offset carried forward from a
34 // hand-back belongs to the *old* clock's readings and means nothing
35 // against the new one, so it goes with it; then re-anchor the simulated
36 // origin against the new clock (or drop it, if the new clock is itself
37 // the virtual axis).
38 self.sim_input_offset = std::time::Duration::ZERO;
39 self.sim_input_origin = None;
40 self.rearm_sim_input_origin();
41 }
42
43 /// Put this tree on the simulated clock, if it is not already.
44 ///
45 /// Called from the one door that moves simulated time, and it moves **both**
46 /// axes together:
47 ///
48 /// * the animation scheduler's stored instants are rebased from the wall
49 /// clock onto [`simulated_now`](Self::simulated_now), so an animation
50 /// in flight when the freeze happens keeps the phase it had. Without the
51 /// rebase every such animation would be measured from a start lying in
52 /// the simulated clock's future — the simulated clock reads the tree's
53 /// epoch plus whatever has been advanced, which on a live window is far
54 /// behind the wall clock — and its elapsed time would clamp to zero for
55 /// good;
56 /// * the input axis is anchored where it stood — see the
57 /// `sim_input_origin` field — so no stamp taken before the switch lands
58 /// in the virtual future.
59 ///
60 /// Re-entrant on purpose: [`resume_real_time`](Self::resume_real_time) may
61 /// have handed time back since the last call, and the next advance has to
62 /// take it again.
63 pub(super) fn enter_simulated_mode(&mut self) {
64 if !self.sim_time_frozen {
65 self.sim_time_frozen = true;
66 self.animation_scheduler
67 .rebase(std::time::Instant::now(), self.sim_clock);
68 }
69 if self.sim_input_origin.is_none() {
70 self.rearm_sim_input_origin();
71 }
72 }
73
74 /// Hand time back to the wall clock, carrying forward everything that was
75 /// advanced while it was simulated.
76 ///
77 /// **Who calls this.** A host that shares a live tree with a real event
78 /// loop — the debug automation bridge — after each operation that may have
79 /// advanced the clock. A headless test does not: a test wants the freeze,
80 /// and wants it to survive between calls, so that two samples it dispatches
81 /// without advancing are stamped the *same* instant rather than however
82 /// many microseconds apart the machine happened to run them.
83 ///
84 /// **The animation axis** is handed back by rebasing the scheduler's stored
85 /// instants the other way, the exact inverse of what
86 /// `enter_simulated_mode` did. An animation half-way through when the
87 /// operation ends is half-way through on the wall clock too, and the next
88 /// real layout pass advances it from there — neither snapped to its end
89 /// (which is what ticking at the wall clock against a start stamped on the
90 /// simulated one gives) nor stuck (which is what ticking a live tree at a
91 /// simulated clock nothing is advancing any more gives).
92 ///
93 /// **The input axis cannot simply drop its origin.** A frozen axis that has
94 /// been advanced reads *ahead* of the raw clock; dropping the origin would
95 /// send [`input_now`](Self::input_now) backwards, and a monotone
96 /// [`EventTime`](crate::pointer::EventTime) is a platform conformance
97 /// invariant every velocity tracker, tap streak and hold relies on. So the
98 /// gap is measured — afresh, against this hand-back's own readings, never
99 /// added to what a previous one measured, and floored at zero for the case
100 /// where the raw clock is already the later of the two — and kept in
101 /// `sim_input_offset`: the reading at this instant is the later of the
102 /// frozen reading and the raw one, and it moves with the wall clock from
103 /// here.
104 ///
105 /// A no-op on a tree that is not simulating time, so calling it after every
106 /// operation costs nothing.
107 pub fn resume_real_time(&mut self) {
108 if !self.sim_time_frozen {
109 return;
110 }
111 self.sim_time_frozen = false;
112 self.animation_scheduler
113 .rebase(self.sim_clock, std::time::Instant::now());
114 let Some((base, base_at)) = self.sim_input_origin.take() else {
115 // An unanchored clock — a `ManualClock` — *is* the virtual axis and
116 // was never frozen against the wall clock, so there is nothing to
117 // carry forward.
118 return;
119 };
120 let frozen = base + self.sim_clock.saturating_duration_since(base_at);
121 // `saturating_since` rather than `-`: on a tree advanced by less than
122 // it spent on the wall clock the raw reading is already ahead, and the
123 // right offset is then none at all.
124 self.sim_input_offset = frozen.saturating_since(self.input_clock.now());
125 }
126
127 /// Anchor (or drop) the simulated input origin against the current clock.
128 fn rearm_sim_input_origin(&mut self) {
129 self.sim_input_origin = if self.sim_time_frozen && self.input_clock.epoch().is_some() {
130 // `input_now`, not the raw clock: after a hand-back the axis runs
131 // an offset ahead of the clock, and re-freezing at the raw reading
132 // would step it backwards by exactly that offset.
133 Some((self.input_now(), self.sim_clock))
134 } else {
135 // Either the tree still runs on real time, or its clock has no
136 // wall-clock anchor and is moved directly by `advance_time`.
137 None
138 };
139 }
140
141 /// The current time on this tree's input timeline.
142 ///
143 /// While the axis is frozen this is a reading of
144 /// [`sim_clock`](Self::simulated_now), not of the wall clock, so a deadline
145 /// can only be reached by advancing the clock. Once
146 /// [`resume_real_time`](Self::resume_real_time) has handed it back it is
147 /// the clock again, plus everything that was advanced.
148 pub fn input_now(&self) -> crate::pointer::EventTime {
149 match self.sim_input_origin {
150 Some((base, base_at)) => base + self.sim_clock.saturating_duration_since(base_at),
151 None => self.input_clock.now() + self.sim_input_offset,
152 }
153 }
154
155 /// Everything a recognizer on `id` is allowed to know beyond the event in
156 /// front of it: now, the profile for the pointer being dispatched, the
157 /// node's own bounds, and the pointer itself.
158 ///
159 /// Rebuilt per dispatch rather than cached, so a theme change, a density
160 /// change or a different pointer kind reaches the recognizers without any
161 /// of them holding a copy of a threshold.
162 pub(crate) fn recognizer_context(
163 &self,
164 id: WidgetId,
165 ) -> crate::gesture::RecognizerContext<'static> {
166 let pointer = self.current_input.pointer;
167 let profile = *self.effective_theme.input.profile(pointer.kind);
168 let size = self.bounds(id).size();
169 // A dispatch that carries no timestamp of its own (a hand-built
170 // `WidgetEvent` from a test) reads the tree clock instead.
171 let now = if pointer.time == crate::pointer::EventTime::ZERO {
172 self.input_now()
173 } else {
174 pointer.time
175 };
176 crate::gesture::RecognizerContext::new(
177 now,
178 profile,
179 Rect::new(0.0, 0.0, size.width, size.height),
180 pointer,
181 )
182 }
183
184 // -----------------------------------------------------------------
185 // The pointer table
186 // -----------------------------------------------------------------
187
188 /// The pointer this dispatch is serving.
189 ///
190 /// Outside a pointer dispatch the input snapshot holds its default — the
191 /// mouse — which is exactly what every legacy `WidgetEvent` has always
192 /// meant, so a caller that names no pointer keeps naming the mouse.
193 pub(crate) fn current_pointer_id(&self) -> crate::pointer::PointerId {
194 self.current_input.pointer.id
195 }
196
197 /// The widget holding the capture of the pointer this dispatch is serving.
198 ///
199 /// Capture is **per pointer**: two contacts hold independent captures and
200 /// each is released only by its own Up or Cancel. For the mouse — the only
201 /// pointer that existed before the touch programme — this is the old
202 /// singular `pointer_captured_by`, unchanged.
203 pub(crate) fn current_pointer_capture(&self) -> Option<WidgetId> {
204 self.pointers
205 .get(self.current_pointer_id())
206 .and_then(|e| e.captured_by)
207 }
208
209 /// Set (or clear) the capture of the pointer this dispatch is serving.
210 pub(crate) fn set_current_pointer_capture(&mut self, captor: Option<WidgetId>) {
211 let id = self.current_pointer_id();
212 if let Some(entry) = self.pointers.get_mut(id) {
213 entry.captured_by = captor;
214 }
215 }
216
217 /// Set (or clear) the capture of a *named* pointer — the door
218 /// [`EventContext::capture_pointer_id`](crate::widget::EventContext::capture_pointer_id)
219 /// opens for a handler driving a pointer other than the one it is serving.
220 ///
221 /// A capture asked for on a pointer that is not live is dropped, not
222 /// invented: no sample will ever be delivered to it, so an entry conjured
223 /// to hold it would be a capture nothing can release. Reaching this means
224 /// the handler ran outside a pointer dispatch entirely (an assistive
225 /// technology action, a timer), where there is no pointer to capture.
226 pub(crate) fn set_pointer_capture(
227 &mut self,
228 pointer: crate::pointer::PointerId,
229 captor: Option<WidgetId>,
230 ) {
231 if let Some(entry) = self.pointers.get_mut(pointer) {
232 entry.captured_by = captor;
233 }
234 }
235
236 /// Release the capture a drag session was holding.
237 ///
238 /// A drag owns one pointer, but which one is not recorded on the session
239 /// yet (arbitration lands with the gesture package), so this releases both
240 /// the pointer being dispatched and anything the drag's source widget
241 /// still holds. For the mouse those are the same capture, which is why
242 /// this is a faithful stand-in for the old blanket clear.
243 pub(super) fn release_drag_capture(&mut self, source: Option<WidgetId>) {
244 self.set_current_pointer_capture(None);
245 if let Some(src) = source {
246 self.pointers.release_captures_of(src);
247 }
248 }
249
250 /// The widget the **hover owner** is over.
251 ///
252 /// Hover belongs to the hover owner and to nobody else: a contact never
253 /// produces hover, so a finger arriving beside a hovering mouse leaves
254 /// this — and every `on_hover` handler, tooltip dwell and cursor shape —
255 /// exactly where it was.
256 pub(crate) fn hovered_id(&self) -> Option<WidgetId> {
257 self.pointers.hover_owner().and_then(|e| e.hovered)
258 }
259
260 /// Where the hover owner is, if one is live.
261 ///
262 /// The position hover recovery must re-hit-test at. Distinct from
263 /// [`last_pointer_position`](Self::last_pointer_position), which reports
264 /// the *primary* pointer and so answers for a touch-only device too —
265 /// where re-deriving hover from it would invent a hover no finger ever
266 /// produced.
267 pub(crate) fn hover_owner_position(&self) -> Option<teksilo_canvas::Point> {
268 self.pointers.hover_owner().map(|e| e.position)
269 }
270
271 /// Admit the sample being dispatched into the pointer table, refreshing
272 /// its position and its [`PointerInfo`](crate::pointer::PointerInfo), and
273 /// publish the modality.
274 ///
275 /// Returns `false` when the table refused the pointer (a palm, or the
276 /// contact cap), in which case the sample must not be dispatched at all.
277 pub(super) fn admit_current_pointer(
278 &mut self,
279 position: teksilo_canvas::Point,
280 is_down: bool,
281 is_move: bool,
282 ) -> bool {
283 let info = self.current_input.pointer;
284 // Where this pointer was *before* this sample. Only a move of the
285 // hover owner updates `previous_pointer_position`, because the one
286 // reader — the overlay safe triangle — wants the last sample that was
287 // still over the anchor the pointer is leaving, and a press or a
288 // second contact is not that.
289 let was_hover_owner = self.pointers.hover_owner_id() == Some(info.id);
290 let before = self.pointers.get(info.id).map(|e| e.position);
291 if self.pointers.admit(info, position, is_down).is_none() {
292 return false;
293 }
294 if is_move && was_hover_owner {
295 self.previous_pointer_position = before;
296 }
297 if self.last_pointer_kind_signal.get() != info.kind {
298 self.last_pointer_kind_signal.set(info.kind);
299 }
300 true
301 }
302
303 /// Hand the hover-owner role to the pointer being dispatched, and take
304 /// hover away from whoever held it.
305 ///
306 /// The later sample wins: on a machine with both a mouse and a pen, the
307 /// device the user just moved owns hover, and the one that lost it is sent
308 /// a [`PointerLeave`](crate::event::WidgetEvent::PointerLeave) for the
309 /// widget it was over — otherwise that widget stays lit for a pointer that
310 /// is no longer pointing at it. A contact is refused outright.
311 pub(super) fn claim_hover_owner_for_current(&mut self, ops: &mut dyn crate::window::WindowOps) {
312 let id = self.current_pointer_id();
313 let Some(displaced) = self.pointers.claim_hover_owner(id) else {
314 return;
315 };
316 let stale = self
317 .pointers
318 .get_mut(displaced)
319 .and_then(|entry| entry.hovered.take());
320 if let Some(old) = stale {
321 // Credited to the pointer that just *lost* the role — it is the one
322 // no longer pointing at `old` — not to the claimant.
323 let leave = WidgetEvent::PointerLeave {
324 pointer: self
325 .pointers
326 .get(displaced)
327 .map(|entry| entry.info)
328 .unwrap_or_else(|| crate::pointer::PointerInfo::mouse(self.input_now())),
329 };
330 self.dispatch_to_widget(old, &leave, &mut *ops);
331 self.tooltip_pointer_leave(old, &mut *ops);
332 }
333 // The new owner starts with no hover of its own; the move that gave it
334 // the role establishes one immediately afterwards.
335 self.update_hover_within_signals(stale, None);
336 self.set_hovered(None);
337 }
338
339 /// Whether `id` carries a drag or swipe handler (hence gets a drag/swipe
340 /// recognizer once its arena is built).
341 fn widget_has_drag(&self, id: WidgetId) -> bool {
342 self.arena
343 .get(id)
344 .map(|n| n.any_handler(|h| h.on_drag.is_some() || h.on_swipe.is_some()))
345 .unwrap_or(false)
346 }
347
348 /// Whether `id` is a gesture dead-zone boundary — a press inside its
349 /// subtree must not arm a drag/swipe on any ancestor above it. See
350 /// [`WidgetNode::gesture_dead_zone`](crate::arena::WidgetNode::gesture_dead_zone).
351 fn is_gesture_dead_zone(&self, id: WidgetId) -> bool {
352 self.arena
353 .get(id)
354 .map(|n| n.gesture_dead_zone)
355 .unwrap_or(false)
356 }
357
358 /// Whether `id` is a keyboard-capture surface — while focused it
359 /// receives every `KeyDown` raw, bypassing shortcut resolution. See
360 /// [`WidgetNode::keyboard_capture`](crate::arena::WidgetNode::keyboard_capture).
361 pub(super) fn is_keyboard_capture(&self, id: WidgetId) -> bool {
362 self.arena
363 .get(id)
364 .map(|n| n.keyboard_capture)
365 .unwrap_or(false)
366 }
367
368 // -----------------------------------------------------------------
369 // The arbitration spine: one `PointerSequence` per live pointer
370 // -----------------------------------------------------------------
371
372 /// The frozen hit path for `target`: target → root.
373 fn hit_path(&self, target: WidgetId) -> Vec<WidgetId> {
374 let mut path = Vec::new();
375 let mut current = Some(target);
376 while let Some(id) = current {
377 path.push(id);
378 current = self.arena.parent(id);
379 }
380 path
381 }
382
383 /// The **innermost** gesture dead zone on `path`.
384 ///
385 /// Nothing at or above it may be enrolled — for a mouse exactly as for a
386 /// finger. A dead zone is deliberately *not* sugar for
387 /// [`TouchAction::NONE`]: a mouse ignores touch actions entirely, so the
388 /// substitution would delete the mouse behaviour the flag exists for, and
389 /// on a direct pointer it would drop the latch to `slop_precise` and turn
390 /// the `DeadZone` widget's own regression into a 2 px hair trigger.
391 fn dead_zone_on(&self, path: &[WidgetId]) -> Option<WidgetId> {
392 path.iter()
393 .copied()
394 .find(|id| self.is_gesture_dead_zone(*id))
395 }
396
397 /// The gesture profile for the pointer this dispatch is serving.
398 pub(super) fn current_profile(&self) -> teksilo_tokens::GestureProfile {
399 *self
400 .effective_theme
401 .input
402 .profile(self.current_input.pointer.kind)
403 }
404
405 /// The sequence for the pointer this dispatch is serving.
406 pub(crate) fn current_sequence(&self) -> Option<&crate::gesture::PointerSequence> {
407 self.pointers
408 .get(self.current_pointer_id())
409 .and_then(|e| e.sequence.as_ref())
410 }
411
412 /// Run `f` against the current pointer's sequence, taking it out of the
413 /// table for the duration so `self` stays fully borrowable.
414 ///
415 /// The sequence is put back only if the pointer is still live afterwards —
416 /// a handler that ended the pointer must not have its sequence resurrected.
417 fn with_sequence<R>(
418 &mut self,
419 f: impl FnOnce(&mut Self, &mut crate::gesture::PointerSequence) -> R,
420 ) -> Option<R> {
421 let pointer = self.current_pointer_id();
422 let mut sequence = self.pointers.get_mut(pointer)?.sequence.take()?;
423 let result = f(self, &mut sequence);
424 if let Some(entry) = self.pointers.get_mut(pointer) {
425 entry.sequence = Some(sequence);
426 }
427 Some(result)
428 }
429
430 /// Open the arbitration for the press being dispatched, **before** any
431 /// handler runs.
432 ///
433 /// It has to be before: `ctx.touch_action()` reports the frozen value from
434 /// inside the press handler, and an explicit `capture_pointer()` made there
435 /// needs a sequence to enrol into. Pan claimants are enrolled here too, so
436 /// that the `DragActivation::Auto` question — "is anything else already
437 /// claiming this axis?" — has an answer during the press.
438 ///
439 /// A direct pointer forms **no sequence at all** when
440 /// [`InputTokens::touch_enabled`](teksilo_tokens::InputTokens::touch_enabled)
441 /// is off: the kill switch means the framework arbitrates nothing for a
442 /// contact, and the sample takes the legacy route unchanged.
443 pub(super) fn begin_sequence(&mut self, target: WidgetId, position: teksilo_canvas::Point) {
444 use crate::gesture::{MemberRole, PointerSequence};
445
446 let pointer = self.current_input.pointer;
447 if pointer.kind.is_direct() && !self.effective_theme.input.touch_enabled {
448 crate::trace_input!(
449 Gestures,
450 "no sequence for {:?}: touch_enabled=false",
451 pointer.id
452 );
453 return;
454 }
455 let path = self.hit_path(target);
456 let touch_action = self.effective_touch_action(target);
457 let boundary = self.dead_zone_on(&path);
458 let now = self.recognizer_context(target).now;
459 let mut sequence =
460 PointerSequence::new(pointer, path, touch_action, boundary, position, now);
461
462 // Pan claimants: direct pointers only. `PanClaim::devices` defaults to
463 // DIRECT and the mouse profile has no `pan_slop` at all, so this loop
464 // adds nothing for a mouse — which is what keeps every mouse sequence
465 // arbitrating exactly as `drag_observers` did.
466 let profile = self.current_profile();
467 if pointer.kind.is_direct() {
468 for (id, claim) in self.pan_candidates(target, touch_action) {
469 if sequence.pan_is_eligible(&claim, &profile) {
470 sequence.enrol(id, MemberRole::Pan(claim));
471 }
472 }
473 }
474
475 crate::trace_input!(
476 Gestures,
477 "sequence opened for {:?}: action={:?} dead_zone={:?} pan_members={}",
478 pointer.id,
479 touch_action,
480 boundary,
481 sequence.members().len()
482 );
483 if let Some(entry) = self.pointers.get_mut(pointer.id) {
484 entry.sequence = Some(sequence);
485 }
486 }
487
488 /// Enrol the competitors that only become knowable once the press has been
489 /// dispatched, and feed each of them the `Down`.
490 ///
491 /// The gesture members are the pre-existing drag observers, expressed on
492 /// the sequence and with the same three rules:
493 ///
494 /// * the captured widget's own drag owns the gesture — it is enrolled as
495 /// the innermost member and no ancestor is;
496 /// * a dead-zone boundary stops the walk;
497 /// * only nodes carrying `on_drag` / `on_swipe` compete.
498 ///
499 /// The captured widget's arena has already seen this `Down` through the
500 /// normal bubble, so only the ancestors are fed here.
501 ///
502 /// **Both enrolment doors have a dual-role fallback.** A node that declares
503 /// a [`PanClaim`] is already a member by the time this runs —
504 /// `begin_sequence` enrols pan claimants before any handler does anything —
505 /// so if that same node also carries `on_drag`, `enrol` (captured) and
506 /// `enrol_drag` (ancestor) both refuse it. Neither refusal is a decision: it
507 /// is a slot collision. Each falls through to
508 /// [`PointerSequence::defer_own_drag`](crate::gesture::PointerSequence::defer_own_drag),
509 /// which attaches the drag's activation to the member the node already has.
510 ///
511 /// The ancestor door additionally **feeds** the deferred node its `Down`,
512 /// exactly as an ordinarily-enrolled drag ancestor is fed: the press bubble
513 /// stops at the captor (`try_handler_bubble`'s `Down` arm answers `Handled`
514 /// the moment a node has an arena), so without that feed the ancestor's
515 /// `DragRecognizer` has no origin and could never latch however the
516 /// arbitration ruled. The *move* bubble has no such stop, so nothing
517 /// afterwards needs feeding.
518 pub(super) fn enrol_sequence_members(
519 &mut self,
520 down_event: &WidgetEvent,
521 ops: &mut dyn crate::window::WindowOps,
522 ) {
523 use crate::gesture::MemberRole;
524
525 let captured = self.current_pointer_capture();
526 let profile = self.current_profile();
527
528 // Which ancestors compete, decided against the frozen path.
529 let Some(to_enrol) = self.with_sequence(|tree, sequence| {
530 sequence.set_capture(captured);
531 sequence.set_pressed_owner(captured);
532 // A decided sequence still enrols its competitors — as **rejected**
533 // ones. Enrolling them is what lets the router stop their
534 // recognizers from being fed at all: an ancestor that never becomes
535 // a member is invisible to the arbitration, and an explicit captor
536 // would lose the press to it on the very next move.
537 let decided = sequence.is_decided();
538 let Some(captured) = captured else {
539 // Nothing took the press, so there is nothing for an ancestor
540 // to observe *through* — the pre-existing gate, kept verbatim.
541 return Vec::new();
542 };
543 if tree.widget_has_drag(captured) {
544 // The innermost drag owns the gesture: it is the member, and no
545 // ancestor is. Its own arena drives it through the capture
546 // route, so it is never fed here.
547 if sequence.enrol(captured, MemberRole::Gesture) {
548 if decided {
549 sequence.reject(captured);
550 }
551 } else {
552 // Already enrolled — today only as the pan claimant
553 // `begin_sequence` put there before any handler ran. One
554 // node, one member, so its drag does not get a slot of its
555 // own; `defer_own_drag` gives it a say on the member it
556 // has, resolving its `DragActivation` against the pan it is
557 // competing with. A mouse enrols no pan member, so it never
558 // reaches this arm.
559 let activation = Self::sequence_drag_activation(tree, sequence, captured);
560 sequence.defer_own_drag(captured, activation, &profile);
561 }
562 return Vec::new();
563 }
564 if !sequence.may_enrol(captured) {
565 // The press landed inside a dead zone (the captured control
566 // *is* the dead zone) — arm no ancestor at all.
567 return Vec::new();
568 }
569 let mut out = Vec::new();
570 let mut current = tree.arena.parent(captured);
571 while let Some(id) = current {
572 if !sequence.may_enrol(id) {
573 break;
574 }
575 if tree.widget_has_drag(id) {
576 let activation = Self::sequence_drag_activation(tree, sequence, id);
577 if sequence.enrol_drag(id, MemberRole::Gesture, activation, &profile) {
578 if decided {
579 sequence.reject(id);
580 } else {
581 out.push((id, true));
582 }
583 } else if sequence.defer_own_drag(id, activation, &profile) {
584 // The second door to the same refusal, and the one a
585 // *heavyweight* child's press goes through: `enrol_drag`
586 // opens with `enrol`, which declines an ancestor already
587 // enrolled as this sequence's pan claimant. Without this
588 // arm that ancestor's drag is never fed the press at all
589 // — so a dual-role container could not be dragged from
590 // anywhere its own content took the capture.
591 //
592 // No `decided` guard, unlike the branch above: a decided
593 // sequence is `defer_own_drag`'s own first refusal, so
594 // this arm is unreachable once one exists.
595 out.push((id, true));
596 }
597 }
598 current = tree.arena.parent(id);
599 }
600 out
601 }) else {
602 return;
603 };
604
605 for (id, feed) in to_enrol {
606 if !feed {
607 continue;
608 }
609 // Build the arena (the bubble never reached this ancestor) and feed
610 // it the press so its DragRecognizer records the origin.
611 {
612 let WidgetTree {
613 arena,
614 gesture_owners,
615 ..
616 } = self;
617 if let Some(node) = arena.get_mut(id) {
618 Self::ensure_gesture_arena(node, id, gesture_owners);
619 }
620 }
621 self.feed_member_arena(id, down_event, &mut *ops);
622 }
623 }
624
625 /// The [`DragActivation`](teksilo_tokens::DragActivation) that governs
626 /// `id`'s own drag for **this** press: the per-press override a handler
627 /// queued with
628 /// [`set_drag_activation`](crate::widget::EventContext::set_drag_activation),
629 /// or failing that the node's build-time declaration.
630 ///
631 /// The override is read off the sequence rather than the node because a
632 /// press handler answers per *press*, not per node — see
633 /// `PointerSequence::drag_activation_overrides`.
634 fn sequence_drag_activation(
635 tree: &WidgetTree,
636 sequence: &crate::gesture::PointerSequence,
637 id: WidgetId,
638 ) -> teksilo_tokens::DragActivation {
639 sequence.drag_activation_override(id).unwrap_or_else(|| {
640 tree.arena
641 .get(id)
642 .map(|n| n.drag_activation)
643 .unwrap_or(teksilo_tokens::DragActivation::Auto)
644 })
645 }
646
647 /// A handler chose a [`DragActivation`](teksilo_tokens::DragActivation) for
648 /// **this press** with
649 /// [`set_drag_activation`](crate::widget::EventContext::set_drag_activation).
650 ///
651 /// Stashed on the sequence, so it dies with the press. Writing it back onto
652 /// the node would outlive the press it was chosen for — and
653 /// `on_pointer_event` previews root-first over every strict ancestor of the
654 /// target, so a node that answers here also answers for presses it does not
655 /// own.
656 pub(super) fn note_drag_activation_override(
657 &mut self,
658 source: WidgetId,
659 activation: teksilo_tokens::DragActivation,
660 ) {
661 self.with_sequence(|_, sequence| {
662 sequence.set_drag_activation_override(source, activation);
663 });
664 }
665
666 /// Record where the pointer is, so every positional threshold reads one
667 /// number rather than each member tracking its own.
668 pub(super) fn note_sequence_position(&mut self, position: teksilo_canvas::Point) {
669 let pointer = self.current_pointer_id();
670 if let Some(entry) = self.pointers.get_mut(pointer)
671 && let Some(sequence) = entry.sequence.as_mut()
672 {
673 sequence.set_last_position(position);
674 }
675 }
676
677 /// Now, on the input timeline, for the sample being dispatched.
678 ///
679 /// A hand-built `WidgetEvent` carries no timestamp, so it reads the tree
680 /// clock — which is what lets a test drive a deadline with a
681 /// [`ManualClock`](crate::pointer::clock::ManualClock).
682 pub(super) fn sequence_now(&self) -> crate::pointer::EventTime {
683 let stamped = self.current_input.pointer.time;
684 if stamped == crate::pointer::EventTime::ZERO {
685 self.input_now()
686 } else {
687 stamped
688 }
689 }
690
691 /// **Timers before positional thresholds** — step 4 of the decision
692 /// procedure, run before the move is dispatched anywhere.
693 ///
694 /// It has to be before: a member reached through the ordinary capture
695 /// bubble would otherwise recognize on this very sample, and a deferred
696 /// drag that should have withdrawn — or a peer that should have been frozen
697 /// by a hold — would already have won by the time the arbitration was
698 /// consulted.
699 ///
700 /// Three rules, all no-ops for a press that stayed where it landed:
701 ///
702 /// * a hold older than `profile.max_hold` is released, because the
703 /// framework never trusts a holder to answer — the one rule here that is
704 /// *also* driven by the clock, through
705 /// [`expire_sequence_holds`](Self::expire_sequence_holds), so a contact
706 /// that never moves is released on time too;
707 /// * a member armed by [`DragActivation::AfterLongPress`](teksilo_tokens::DragActivation::AfterLongPress) withdraws once
708 /// the press leaves the tap boundary — that travel is a pan, not a
709 /// considered grab — and so does the *self-drag* half of a dual-role
710 /// member, which is deferred by the same resolution but cannot withdraw
711 /// the member itself (the member is a pan claimant and goes on competing).
712 /// The self-drag has a **second** positional rule the whole-member case
713 /// does not: travel past `long_press_slop` before the deadline, the rule
714 /// [`LongPressRecognizer`](crate::gesture::LongPressRecognizer) applies to
715 /// itself, which is what makes its deferral a hold rather than a timer;
716 /// * the pressed node's **tap family** is revoked, once, when the press
717 /// leaves the tap boundary — WCAG 2.2 SC 2.5.2's "slide off to abort":
718 /// the activation is abandoned, a drag the same press started is not.
719 ///
720 /// All of them but that second self-drag rule read the one
721 /// [`TapBoundary`](crate::gesture::TapBoundary) predicate, which is also
722 /// what `TapRecognizer` fails on, so the router and the recognizer cannot
723 /// disagree about whether a press has slid off.
724 pub(super) fn tick_sequence_timers(&mut self) {
725 use crate::gesture::MemberState;
726
727 let profile = self.current_profile();
728 let now = self.sequence_now();
729 let Some(revoke) = self.with_sequence(|tree, sequence| {
730 sequence.expire_holds(now, &profile);
731 if sequence.is_decided() {
732 return None;
733 }
734 let origin = sequence.press_origin();
735 let position = sequence.last_position();
736 let boundary = crate::gesture::TapBoundary::for_pointer(&sequence.pointer(), &profile);
737 let left = |id: WidgetId| {
738 let bounds = tree.arena.is_active(id).then(|| tree.arena.bounds(id));
739 boundary.left(origin, position, bounds, &profile)
740 };
741 let rejects: Vec<WidgetId> = sequence
742 .members()
743 .iter()
744 .filter(|m| m.state == MemberState::Possible && m.rejects_on_tap_slop)
745 .filter(|m| left(m.id))
746 .map(|m| m.id)
747 .collect();
748 for id in rejects {
749 sequence.reject(id);
750 }
751 // The *self*-drag half of a dual-role member withdraws on either
752 // positional rule, because the member itself is a pan claimant and
753 // goes on competing — only its drag half can be taken out.
754 //
755 // `long_press_slop` is the load-bearing one, and it is the rule
756 // `LongPressRecognizer` applies to itself: it fails on the first
757 // move past that slop rather than waiting for its timer. Arming the
758 // self-drag on the clock alone made the deferral a *timer*, so a
759 // deliberate, slow pan — a finger positioning precisely, which is
760 // exactly when a scene is panned slowly — crossed the deadline
761 // mid-travel, armed the grab and lost the pan for the rest of the
762 // press. A hold that has already wandered 18 dp is not a hold.
763 //
764 // `TapBoundary` stays beside it and is not redundant: it is the
765 // node's own rect for a coarse pointer, so it bites on a small node
766 // the finger slides off without travelling far, where the radius
767 // does not. Conversely a viewport-filling claimant is never left, so
768 // on that shape the radius is the only positional rule there is.
769 //
770 // Both apply only while the self-drag is still unripe. Once the hold
771 // has been served the grab is live, and travel is the grab doing its
772 // job.
773 let travelled_past_hold = sequence.travel() > profile.long_press_slop;
774 let withdraw: Vec<WidgetId> = sequence
775 .unripe_own_drag_members(now)
776 .into_iter()
777 .filter(|id| travelled_past_hold || left(*id))
778 .collect();
779 for id in withdraw {
780 sequence.withdraw_own_drag(id);
781 }
782 let owner = sequence.pressed_owner()?;
783 if sequence.taps_cancelled() || !left(owner) {
784 return None;
785 }
786 sequence.set_taps_cancelled();
787 Some(owner)
788 }) else {
789 return;
790 };
791 let Some(owner) = revoke else {
792 return;
793 };
794 let pointer = self.current_pointer_id();
795 if let Some(node) = self.arena.get_mut(owner)
796 && let Some(set) = node.handlers.gesture_arena.as_mut()
797 {
798 set.cancel_taps(pointer);
799 }
800 }
801
802 /// Advance an undecided sequence with a move: **timers before positional
803 /// thresholds**, then members innermost-first.
804 ///
805 /// * a `RawDrag` member wins past the sequence's latch slop;
806 /// * a `Gesture` member wins when its own recognizer recognizes — which for
807 /// a mouse is at `drag_slop`, the 5.0 it has always been;
808 /// * a `Pan` member wins only on an axis the frozen `TouchAction` permits
809 /// and only past `pan_slop`, which a mouse profile does not have;
810 /// * a member deferred by [`DragActivation::AfterLongPress`](teksilo_tokens::DragActivation::AfterLongPress) cannot win
811 /// before its timer and self-rejects once the press leaves the tap
812 /// boundary.
813 ///
814 /// A `Gesture` member whose id is the press owner is skipped **and stops
815 /// the walk**: its recognizer is already being driven by the capture
816 /// dispatch, and letting an ancestor past it would break the "innermost
817 /// drag owns the gesture" rule. A `RawDrag` and a `Pan` are not, because
818 /// this walk is the *only* place either is ever evaluated — the press owner
819 /// is very often a pan claimant, since an implicit arena capture makes any
820 /// node with a tap handler the owner, and an editing surface has both.
821 /// `RawPreview` rides along in the same match and is dead there: a preview
822 /// claim decides the sequence as it is enrolled, and a decided sequence
823 /// yields no candidates at all.
824 ///
825 /// A **dual-role** member — one whose node also owns `on_drag`, so
826 /// [`PointerSequence::defer_own_drag`](crate::gesture::PointerSequence::defer_own_drag)
827 /// attached its self-drag to the same slot — is evaluated here **only** as
828 /// the pan it is enrolled as. Its own recognizers are driven by the ordinary
829 /// move bubble and gated there by `sequence_blocks_arena`, which reads the
830 /// same deferral, so its drag half needs nothing from this walk.
831 ///
832 /// That asymmetry is the bubble's, not this walk's, and it is worth stating
833 /// because it decides where a dual-role node's press and its moves each come
834 /// from. `try_handler_bubble`'s **`Down`** arm returns `Handled` the moment a
835 /// node has an arena, so the press bubble stops at the captor and an
836 /// *ancestor*'s recognizers never see the origin — which is why
837 /// `enrol_sequence_members` feeds the `Down` explicitly, for a dual-role
838 /// ancestor exactly as for an ordinary drag ancestor. Its **`Move`** arm
839 /// returns `Ignored` when nothing recognized, so the move bubble carries on
840 /// past the captor and reaches every ancestor by itself.
841 pub(super) fn advance_sequence(
842 &mut self,
843 move_event: &WidgetEvent,
844 ops: &mut dyn crate::window::WindowOps,
845 ) {
846 use crate::gesture::MemberRole;
847
848 let profile = self.current_profile();
849 let now = self.sequence_now();
850
851 let Some(candidates) = self.with_sequence(|_, sequence| {
852 if sequence.is_decided() || sequence.is_held() {
853 // No peer may win while a member is deferring its own answer.
854 return Vec::new();
855 }
856 sequence
857 .members()
858 .iter()
859 .filter(|m| m.is_eligible_at(now))
860 .map(|m| (m.id, m.role))
861 .collect()
862 }) else {
863 return;
864 };
865
866 // The stop rule reads the node whose arena took the **press**, not the
867 // live captor: a member that wins mid-dispatch takes the capture, and
868 // keying on the live value would make the winner look like the thing
869 // that stops the walk.
870 let owner = self.current_sequence().and_then(|s| s.pressed_owner());
871 for (id, role) in candidates {
872 // The stop rule is about the roles the **capture dispatch** drives,
873 // and only those. A `Gesture` member's recognizer is fed through the
874 // ordinary capture bubble, so evaluating it here would double-drive
875 // it, and letting an ancestor past it would break "the innermost
876 // drag owns the gesture" — it stops the walk.
877 //
878 // A `RawDrag` and a `Pan` are both decided *here* and nowhere else:
879 // a raw drag on the sequence's own travel, a pan on
880 // `pan_axis_past_slop`, whose product is a synthesised `Scroll`
881 // rather than a `GestureEvent` fed to an arena. Breaking at either
882 // would mean a member that also owns the press arena could never
883 // win — and for a pan claimant that is every editing surface, which
884 // takes the press for its caret (so the implicit arena capture makes
885 // it the `pressed_owner`) and scrolls itself under a finger.
886 if Some(id) == owner && matches!(role, MemberRole::Gesture | MemberRole::RawPreview) {
887 break;
888 }
889 let won = match role {
890 MemberRole::Gesture => self.feed_member_arena(id, move_event, &mut *ops),
891 MemberRole::RawDrag => self
892 .current_sequence()
893 .is_some_and(|s| s.travel() >= s.latch_slop(&profile)),
894 // A **dual-role** member is evaluated here only as the pan it is
895 // enrolled as; its own recognizers ride the ordinary move
896 // bubble, which reaches them either way. See this function's
897 // doc comment for why that asymmetry is the bubble's.
898 MemberRole::Pan(claim) => self
899 .current_sequence()
900 .and_then(|s| s.pan_axis_past_slop(&claim, &profile))
901 .is_some(),
902 MemberRole::RawPreview => false,
903 };
904 // The `active_drag` half is a **guard**, not a second way in. The
905 // router enters this walk only while no drag is in flight (both
906 // call sites in `pointer_router.rs` test `active_drag.is_none()`),
907 // and the only thing here that can raise one is
908 // `feed_member_arena` on this very candidate — which reports it as
909 // `won` in the same breath. So the `else` winner below is not
910 // reachable on today's call paths, and the winner recorded is
911 // always the member that won. What DOES happen when a surface
912 // raises its own drag from the capture dispatch is that this walk
913 // is not entered at all, leaving the sequence undecided:
914 // `a_drag_raised_by_the_press_owner_takes_the_press_out_of_the_arbitration`
915 // (`pan_arbiter/tests.rs`) pins that.
916 if won || self.active_drag.is_some() {
917 let winner = if won { id } else { owner.unwrap_or(id) };
918 self.decide_sequence(winner);
919 // A pan claimant that won owns the rest of the press as a
920 // *scroll*: from here every sample for this contact is
921 // synthesised onto the claimant chain rather than delivered as
922 // a pointer move. Recorded only for a genuine pan win.
923 if won && matches!(role, MemberRole::Pan(_)) {
924 let pointer = self.current_pointer_id();
925 self.note_pan_claimed(pointer, winner);
926 // The pan half of a dual-role member won, so its self-drag
927 // is out for the rest of the press. Without this the
928 // member's `Won` state would unblock its arena and a
929 // deferral ripening mid-pan would start its drag under a
930 // scrolling finger. Inert for a claimant that carries no
931 // drag of its own.
932 self.with_sequence(|_, sequence| sequence.withdraw_own_drag(winner));
933 // …and the claimant's own **tap family** goes with it. A pan
934 // that won IS the press; leaving the winner's
935 // `TapRecognizer` armed fires its `on_tap` on the release as
936 // well, and on a viewport-filling claimant the slide-off
937 // sweep never revokes it — a coarse pointer's tap boundary
938 // is the node's own rect, and a finger panning a full-window
939 // surface never leaves it. Tap-family only: the same
940 // `cancel_taps` grain WCAG 2.2 SC 2.5.2's slide-off rule
941 // uses, so a drag the same press started is untouched and
942 // the winner receives no `PointerCancel`.
943 self.cancel_member_taps(winner, pointer);
944 }
945 return;
946 }
947 }
948 }
949
950 /// Declare `winner` the owner of the current sequence and cancel every
951 /// competitor it knocked out — each exactly once.
952 ///
953 /// "Exactly once" is structural rather than bookkept:
954 /// [`PointerSequence::decide`](crate::gesture::PointerSequence::decide)
955 /// reports only the members that were still live and flips them to
956 /// `Rejected` as it goes, and a decided sequence returns early above — so a
957 /// loser knocked out in an earlier sample cannot be knocked out again.
958 pub(super) fn decide_sequence(&mut self, winner: WidgetId) {
959 let mut noop = crate::window::NoopWindowOps;
960 self.decide_sequence_with_ops(winner, &mut noop);
961 }
962
963 /// [`decide_sequence`](Self::decide_sequence) with the caller's
964 /// [`WindowOps`](crate::window::WindowOps), so a loser's
965 /// `on_pointer_cancel` can reach the multi-window API like any other
966 /// handler.
967 pub(super) fn decide_sequence_with_ops(
968 &mut self,
969 winner: WidgetId,
970 ops: &mut dyn crate::window::WindowOps,
971 ) {
972 let Some(losers) = self.with_sequence(|_, sequence| {
973 if sequence.is_decided() {
974 return Vec::new();
975 }
976 crate::trace_input!(
977 Gestures,
978 "sequence for {:?} decided: {:?}",
979 sequence.pointer().id,
980 winner
981 );
982 sequence.decide(winner)
983 }) else {
984 return;
985 };
986 let pointer = self.current_pointer_id();
987 for id in losers {
988 // Member-level, not pointer-level: the pointer is very much alive
989 // and its winner is about to go on using it.
990 self.revoke_sequence_member(
991 pointer,
992 id,
993 crate::pointer::CancelReason::PeerClaimed,
994 &mut *ops,
995 );
996 }
997 }
998
999 /// Revoke only `id`'s **tap family** for `pointer` — tap, double tap,
1000 /// triple tap, long press — and leave everything else on the node running.
1001 ///
1002 /// The [`cancel_taps`](crate::gesture::GestureArenaSet::cancel_taps) grain,
1003 /// not [`cancel`](crate::gesture::GestureArenaSet::cancel): the node has not
1004 /// had an interaction taken away, so it is sent no `PointerCancel`, and a
1005 /// drag the same press is driving survives.
1006 pub(super) fn cancel_member_taps(&mut self, id: WidgetId, pointer: crate::pointer::PointerId) {
1007 if let Some(node) = self.arena.get_mut(id)
1008 && let Some(set) = node.handlers.gesture_arena.as_mut()
1009 {
1010 set.cancel_taps(pointer);
1011 }
1012 }
1013
1014 /// Take a member out of the running and revoke whatever its recognizers had
1015 /// accumulated for this contact.
1016 pub(super) fn cancel_member_arena(&mut self, id: WidgetId, pointer: crate::pointer::PointerId) {
1017 if let Some(node) = self.arena.get_mut(id)
1018 && let Some(set) = node.handlers.gesture_arena.as_mut()
1019 {
1020 set.cancel(pointer);
1021 }
1022 }
1023
1024 /// Re-check every member against the arena, once per sample.
1025 ///
1026 /// A member whose node was destroyed is cancelled **individually** and
1027 /// dropped; the sequence itself dies only when its winner or its captor
1028 /// goes away, because those are the two nodes the press actually belongs
1029 /// to.
1030 pub(super) fn revalidate_sequence(&mut self, ops: &mut dyn crate::window::WindowOps) {
1031 let pointer = self.current_pointer_id();
1032 let capture = self.current_pointer_capture();
1033 let Some((dead, lost_owner)) = self.with_sequence(|tree, sequence| {
1034 sequence.set_capture(capture);
1035 let dead = sequence.revalidate(&tree.arena);
1036 // Which owner died decides how the cancel reads: a winner that went
1037 // away had won the press outright, a captor that went away leaves
1038 // the capture with nobody holding it.
1039 let lost_owner = sequence
1040 .lost_owner(&tree.arena)
1041 .then(|| match sequence.winner() {
1042 Some(winner) if !tree.arena.is_active(winner) => {
1043 crate::pointer::CancelReason::WidgetDestroyed
1044 }
1045 _ => crate::pointer::CancelReason::CaptureOrphaned,
1046 });
1047 if lost_owner.is_some() {
1048 // The cancel that finishes the teardown is queued behind this
1049 // sample, so the sequence outlives this line by one dispatch.
1050 // Nothing may win a press whose owner is already gone in the
1051 // meantime — withdraw every competitor now, which also silences
1052 // their recognizers for the rest of the sample
1053 // (`sequence_blocks_arena`).
1054 let live: Vec<WidgetId> = sequence.members().iter().map(|m| m.id).collect();
1055 for id in live {
1056 sequence.reject(id);
1057 }
1058 }
1059 (dead, lost_owner)
1060 }) else {
1061 return;
1062 };
1063 for id in dead {
1064 self.revoke_sequence_member(
1065 pointer,
1066 id,
1067 crate::pointer::CancelReason::WidgetDestroyed,
1068 &mut *ops,
1069 );
1070 }
1071 if let Some(reason) = lost_owner {
1072 crate::trace_input!(
1073 Gestures,
1074 "sequence for {pointer:?} cancelled: its owner is gone ({reason:?})"
1075 );
1076 self.cancel_pointer(pointer, reason, &mut *ops);
1077 }
1078 }
1079
1080 /// The release sweep. The pointer sequence ended without a positional
1081 /// competitor latching, so feed the terminating `Up` to every member that
1082 /// is still following the press.
1083 ///
1084 /// This is what stops an ancestor `DragRecognizer` — armed on the press
1085 /// while an interactive descendant held the capture — from staying armed
1086 /// indefinitely and starting a phantom drag on the next *hover* move.
1087 pub(super) fn end_sequence(
1088 &mut self,
1089 up_event: &WidgetEvent,
1090 ops: &mut dyn crate::window::WindowOps,
1091 ) {
1092 use crate::gesture::MemberRole;
1093
1094 let pointer = self.current_pointer_id();
1095 let capture = self.current_pointer_capture();
1096 let Some(members) = self.with_sequence(|_, sequence| {
1097 sequence.set_terminating(true);
1098 sequence.live_ids_with(|role| matches!(role, MemberRole::Gesture))
1099 }) else {
1100 return;
1101 };
1102 for id in members {
1103 if Some(id) == capture {
1104 // Its own arena is about to see this `Up` through the capture
1105 // dispatch; feeding it twice would count the release twice.
1106 continue;
1107 }
1108 // An `Up` while the recognizer is not mid-drag resolves it to
1109 // `Failed` and clears `down_position` — no gesture is produced, so
1110 // this only tidies recognizer state.
1111 self.feed_member_arena(id, up_event, &mut *ops);
1112 }
1113 if let Some(entry) = self.pointers.get_mut(pointer) {
1114 entry.sequence = None;
1115 }
1116 }
1117
1118 /// Stop every gesture arena that is still following `pointer`.
1119 ///
1120 /// A press ends at exactly one node — the captor — and the release is
1121 /// delivered only there, so any *other* arena that saw the `Down` is left
1122 /// following a contact that no longer exists. It happens on the ordinary
1123 /// path: an ancestor drag that wins a press a tapping descendant was
1124 /// holding takes the capture with it, and the descendant's arena never
1125 /// sees the `Up`.
1126 ///
1127 /// A stale entry is not inert. The next press reuses it instead of
1128 /// instantiating fresh recognizers, so a contact starts mid-gesture on
1129 /// state left over from the previous one. Ended rather than cancelled: the
1130 /// press was completed, not revoked, and the node's
1131 /// [`TapStreak`](crate::gesture::TapStreak) — which lives outside the live
1132 /// set precisely so it can outlive a contact — must survive, or touch
1133 /// double-tap would be impossible.
1134 pub(super) fn release_arenas_following(&mut self, pointer: crate::pointer::PointerId) {
1135 let owners: Vec<WidgetId> = self.gesture_owners.iter().copied().collect();
1136 for id in owners {
1137 if let Some(node) = self.arena.get_mut(id)
1138 && let Some(set) = node.handlers.gesture_arena.as_mut()
1139 {
1140 set.end(pointer);
1141 }
1142 }
1143 }
1144
1145 /// Apply the arbitration acts a handler queued on its context.
1146 pub(super) fn apply_gesture_acts(
1147 &mut self,
1148 acts: &[crate::widget::GestureAct],
1149 source: WidgetId,
1150 ) {
1151 use crate::widget::GestureAct;
1152
1153 let now = self.sequence_now();
1154 let mut claim = false;
1155 self.with_sequence(|_, sequence| {
1156 for act in acts {
1157 match act {
1158 GestureAct::Claim => claim = true,
1159 GestureAct::Reject => {
1160 claim = false;
1161 sequence.reject(source);
1162 }
1163 GestureAct::Hold => {
1164 claim = false;
1165 if !sequence.has_member(source) {
1166 sequence.enrol(source, crate::gesture::MemberRole::Gesture);
1167 }
1168 sequence.hold(source, now);
1169 }
1170 GestureAct::Release => {
1171 sequence.release_hold(source);
1172 }
1173 }
1174 }
1175 });
1176 if claim {
1177 self.with_sequence(|_, sequence| {
1178 if !sequence.has_member(source) {
1179 sequence.enrol(source, crate::gesture::MemberRole::Gesture);
1180 }
1181 });
1182 self.decide_sequence(source);
1183 }
1184 }
1185
1186 /// A handler took the pointer with an explicit
1187 /// [`capture_pointer`](crate::widget::EventContext::capture_pointer).
1188 ///
1189 /// That is an arbitration act, not plumbing: the caller is enrolled as a
1190 /// [`MemberRole::RawDrag`](crate::gesture::MemberRole::RawDrag) competitor,
1191 /// and for a precise pointer with no eligible pan competitor the sequence
1192 /// is decided there and then — which is what makes the splitter handle, the
1193 /// dock resize handle and the table column grip win their own presses
1194 /// instead of losing them to an ancestor that happens to carry `on_drag`.
1195 pub(super) fn note_explicit_capture(&mut self, source: WidgetId) {
1196 use crate::gesture::MemberRole;
1197
1198 let Some(decide) = self.with_sequence(|_, sequence| {
1199 if sequence.is_decided() {
1200 return false;
1201 }
1202 if !sequence.enrol(source, MemberRole::RawDrag) && !sequence.has_member(source) {
1203 return false;
1204 }
1205 // A precise pointer has no pan competitor by construction
1206 // (`GestureProfile::pan_slop` is `None` for a mouse), so this is a
1207 // decision at press. A contact defers to `drag_slop` instead, which
1208 // is what lets a scroller still beat it at `pan_slop`.
1209 !sequence.pointer().kind.is_direct() && !sequence.has_eligible_pan()
1210 }) else {
1211 return;
1212 };
1213 if decide {
1214 self.decide_sequence(source);
1215 }
1216 }
1217
1218 /// A recognizer on `source` produced a gesture that owns the rest of the
1219 /// press (a drag or a swipe). That is the observable act of winning, so it
1220 /// decides the sequence — whether the recognizer was reached through the
1221 /// ordinary capture bubble or fed by the arbitration itself.
1222 pub(super) fn note_gesture_recognized(&mut self, source: WidgetId) {
1223 use crate::gesture::MemberRole;
1224
1225 let now = self.sequence_now();
1226 let claimed = self
1227 .with_sequence(|_, sequence| {
1228 if sequence.is_decided() {
1229 return false;
1230 }
1231 // A self-drag still inside its deferral cannot claim. The arena
1232 // gate normally makes this unreachable — a blocked recognizer
1233 // produces nothing to report — but the guard is what makes "the
1234 // deferral binds every route" true by *reading* it rather than
1235 // by enumerating the routes.
1236 if sequence.own_drag_blocked(source, now) {
1237 return false;
1238 }
1239 if !sequence.has_member(source) {
1240 sequence.enrol(source, MemberRole::Gesture);
1241 }
1242 // The self-drag half of a dual-role member won: say so, so
1243 // `sequence_members` names the half that took the press rather
1244 // than the pan claim the node was also holding.
1245 sequence.promote_own_drag(source);
1246 sequence.has_member(source)
1247 })
1248 .unwrap_or(false);
1249 if claimed {
1250 self.decide_sequence(source);
1251 }
1252 }
1253
1254 /// Whether `id`'s gesture recognizers must be kept out of this pointer
1255 /// event.
1256 ///
1257 /// A member that lost — because a peer won, because it withdrew, or because
1258 /// another member is holding — must not go on recognizing through the
1259 /// ordinary bubble. Only its *recognizers* are silenced: its
1260 /// `on_pointer_event`, `on_hover` and everything else still run, because
1261 /// losing an arbitration is not the same as being removed from the tree.
1262 ///
1263 /// Inert for every sequence nothing has decided, held or rejected — which
1264 /// is every plain mouse tap.
1265 ///
1266 /// Asked of the sequence belonging to the pointer being dispatched. The
1267 /// timer-driven path has no pointer being dispatched and asks
1268 /// [`sequence_blocks_arena_for`](Self::sequence_blocks_arena_for) instead,
1269 /// naming the contact whose gesture is in hand.
1270 pub(super) fn sequence_blocks_arena(&self, id: WidgetId) -> bool {
1271 match self.current_sequence() {
1272 Some(sequence) => Self::sequence_blocks_member(sequence, id, self.sequence_now()),
1273 None => false,
1274 }
1275 }
1276
1277 /// [`sequence_blocks_arena`](Self::sequence_blocks_arena) for a named
1278 /// contact and a named instant, rather than for whatever sample is being
1279 /// dispatched.
1280 ///
1281 /// The timer path needs both: nothing is being dispatched during a tick, so
1282 /// `current_sequence` would answer about the wrong contact (or about none),
1283 /// and `sequence_now` would answer with the timestamp of the last sample
1284 /// dispatched — which for a contact resting on a control is its own press.
1285 pub(super) fn sequence_blocks_arena_for(
1286 &self,
1287 pointer: crate::pointer::PointerId,
1288 id: WidgetId,
1289 now: crate::pointer::EventTime,
1290 ) -> bool {
1291 match self.pointers.get(pointer).and_then(|e| e.sequence.as_ref()) {
1292 Some(sequence) => Self::sequence_blocks_member(sequence, id, now),
1293 None => false,
1294 }
1295 }
1296
1297 /// The rule itself, shared by both doors above.
1298 fn sequence_blocks_member(
1299 sequence: &crate::gesture::PointerSequence,
1300 id: WidgetId,
1301 now: crate::pointer::EventTime,
1302 ) -> bool {
1303 use crate::gesture::MemberState;
1304
1305 let Some(member) = sequence.members().iter().find(|m| m.id == id) else {
1306 return false;
1307 };
1308 // A node that also claims a pan has its *own* drag recognizers gated
1309 // separately from its membership: the member goes on competing as a pan
1310 // while its self-drag waits out the deferral its `DragActivation` asked
1311 // for, and stays silenced for good once that self-drag is withdrawn —
1312 // which is why the clause is read in the `Won` arm too. A withdrawal
1313 // means the pan took the press, and a pan that owns the press owns the
1314 // node's recognizers with it. Inert for every member carrying no
1315 // self-drag, which is every member a mouse ever enrols.
1316 let own_drag_armed = member.own_drag_armed_at(now);
1317 match member.state {
1318 MemberState::Rejected => true,
1319 MemberState::Won => !own_drag_armed,
1320 _ => {
1321 if !own_drag_armed {
1322 return true;
1323 }
1324 if let Some(winner) = sequence.winner() {
1325 return winner != id;
1326 }
1327 // A hold freezes every peer: no one may win while a member is
1328 // still deciding.
1329 if sequence.is_held() && member.state != MemberState::Held {
1330 return true;
1331 }
1332 // A member deferred by `DragActivation::AfterLongPress` cannot
1333 // win before its timer, and that has to hold on the ordinary
1334 // bubble too — otherwise the deferral would only bind the
1335 // arbitration's own walk.
1336 !member.is_eligible_at(now)
1337 }
1338 }
1339 }
1340
1341 /// A preview handler answered `Handled` on a press. The **root-first**
1342 /// preview pass is the first step of the decision procedure, so this claims
1343 /// the sequence outright.
1344 pub(super) fn note_preview_claim(&mut self, source: WidgetId) {
1345 use crate::gesture::MemberRole;
1346
1347 let claimed = self
1348 .with_sequence(|_, sequence| {
1349 if sequence.is_decided() {
1350 return false;
1351 }
1352 sequence.enrol(source, MemberRole::RawPreview)
1353 })
1354 .unwrap_or(false);
1355 if claimed {
1356 self.decide_sequence(source);
1357 }
1358 }
1359
1360 /// The winner of `pointer`'s sequence, if one has been decided.
1361 pub fn sequence_winner(&self, pointer: crate::pointer::PointerId) -> Option<WidgetId> {
1362 self.pointers
1363 .get(pointer)
1364 .and_then(|e| e.sequence.as_ref())
1365 .and_then(|s| s.winner())
1366 }
1367
1368 /// Every competitor for `pointer`'s press, innermost first.
1369 ///
1370 /// The observable form of the cross-widget arbitration, and the successor
1371 /// to the old `armed_drag_observers()`: an app can assert that a press on a
1372 /// control inside a draggable container enrols no ancestor at all.
1373 pub fn sequence_members(
1374 &self,
1375 pointer: crate::pointer::PointerId,
1376 ) -> Vec<(
1377 WidgetId,
1378 crate::gesture::MemberRole,
1379 crate::gesture::MemberState,
1380 )> {
1381 self.pointers
1382 .get(pointer)
1383 .and_then(|e| e.sequence.as_ref())
1384 .map(|s| s.member_report())
1385 .unwrap_or_default()
1386 }
1387
1388 /// The [`TouchAction`] frozen for the pointer this dispatch is serving —
1389 /// what [`EventContext::touch_action`](crate::widget::EventContext::touch_action)
1390 /// reports.
1391 pub(crate) fn current_frozen_touch_action(&self) -> TouchAction {
1392 self.current_sequence()
1393 .map(|s| s.touch_action())
1394 .unwrap_or(TouchAction::AUTO)
1395 }
1396
1397 /// The [`TouchAction`] frozen for `pointer`'s press.
1398 pub fn sequence_touch_action(&self, pointer: crate::pointer::PointerId) -> TouchAction {
1399 self.pointers
1400 .get(pointer)
1401 .and_then(|e| e.sequence.as_ref())
1402 .map(|s| s.touch_action())
1403 .unwrap_or(TouchAction::AUTO)
1404 }
1405
1406 /// Feed one raw pointer event to `id`'s gesture arena set WITHOUT firing
1407 /// its `on_pointer_event` or taking the implicit capture (another node
1408 /// already holds it). Returns `true` if a gesture was recognized, in which
1409 /// case it is dispatched so the `on_drag` handler's `start_drag` runs and
1410 /// `active_drag` takes over.
1411 fn feed_member_arena(
1412 &mut self,
1413 id: WidgetId,
1414 event: &WidgetEvent,
1415 ops: &mut dyn crate::window::WindowOps,
1416 ) -> bool {
1417 let localized = self.localize_event(id, event);
1418 let event = localized.as_ref().unwrap_or(event);
1419 let cx = self.recognizer_context(id);
1420 let raw = match event {
1421 WidgetEvent::PointerDown {
1422 position,
1423 button,
1424 modifiers,
1425 ..
1426 } => crate::gesture::RawPointerEvent::Down {
1427 position: *position,
1428 button: *button,
1429 modifiers: *modifiers,
1430 pointer: cx.pointer,
1431 time: cx.now,
1432 },
1433 WidgetEvent::PointerMove { position, .. } => crate::gesture::RawPointerEvent::Move {
1434 position: *position,
1435 pointer: cx.pointer,
1436 time: cx.now,
1437 },
1438 WidgetEvent::PointerUp {
1439 position,
1440 button,
1441 modifiers,
1442 ..
1443 } => crate::gesture::RawPointerEvent::Up {
1444 position: *position,
1445 button: *button,
1446 modifiers: *modifiers,
1447 pointer: cx.pointer,
1448 time: cx.now,
1449 },
1450 _ => return false,
1451 };
1452 let mut ctx = self.make_event_context(&mut *ops);
1453 let WidgetTree { arena, .. } = self;
1454 let recognized = if let Some(node) = arena.get_mut(id) {
1455 if let Some(arena_ref) = node.handlers.gesture_arena.as_mut() {
1456 if let Some(gesture) = arena_ref.process(&raw, &cx) {
1457 Self::dispatch_recognized_gesture(node, gesture, &mut ctx);
1458 true
1459 } else {
1460 false
1461 }
1462 } else {
1463 false
1464 }
1465 } else {
1466 false
1467 };
1468 self.collect_from_ctx(ctx, id);
1469 recognized
1470 }
1471
1472 /// The clock a newly promoted animation must be stamped with: the same one
1473 /// the scheduler will later be ticked against.
1474 ///
1475 /// The wall clock, unless [`advance_time`](Self::advance_time) has taken
1476 /// this tree onto its simulated one and not yet handed it back — see
1477 /// [`resume_real_time`](Self::resume_real_time), which is what returns the
1478 /// answer to the wall clock, rebasing the scheduler as it goes.
1479 ///
1480 /// Everything that reads a time on the animation axis has to read it here,
1481 /// promotion and tick alike, or the two drift apart and the drift *is* the
1482 /// elapsed time the animation is measured by. Promoting at
1483 /// `Instant::now()` while ticking at [`Self::sim_clock`] gave every
1484 /// animation a start in the scheduler's future and froze its progress
1485 /// completely, with no number of further ticks recovering it — a failure
1486 /// that reproduced as a function of machine load rather than of behaviour,
1487 /// green when the suite ran alone and red once the runner filled the cores
1488 /// and each test's wall-clock time stretched past the simulated time it was
1489 /// asking for. The overlay manager keeps its real and simulated timestamps
1490 /// apart for the same reason.
1491 pub(super) fn animation_clock(&self) -> std::time::Instant {
1492 if self.sim_time_frozen {
1493 self.sim_clock
1494 } else {
1495 std::time::Instant::now()
1496 }
1497 }
1498
1499 /// Advance time-driven gesture recognizers (currently only
1500 /// [`crate::gesture::LongPressRecognizer`]) across every widget that
1501 /// has a gesture arena. Must be called by the event loop on each
1502 /// wake-up; otherwise long-press will never fire during an idle hold.
1503 ///
1504 /// When a recognizer transitions to `Recognized`, the corresponding
1505 /// handler on the owning widget is invoked with a fresh
1506 /// [`EventContext`], and any commands / overlay requests it emits are
1507 /// collected through the normal post-event path.
1508 /// Release every hold that has stood for `profile.max_hold`, across every
1509 /// contact — the time-driven half of
1510 /// [`tick_sequence_timers`](Self::tick_sequence_timers), lifted out so the
1511 /// gesture tick can run it too.
1512 ///
1513 /// Two things separate it from its move-driven sibling and are why it is a
1514 /// distinct function rather than a call to that one.
1515 ///
1516 /// * **It reads the caller's `now`, not the sample's.** `sequence_now`
1517 /// answers with the timestamp of the last event *dispatched*, which
1518 /// during a tick is the press — so calling `tick_sequence_timers` from
1519 /// here would expire holds against the instant they were taken and never
1520 /// expire anything at all.
1521 /// * **It is not scoped to the current pointer.** The rest of the sequence
1522 /// machinery serves the contact being dispatched; a tick serves the whole
1523 /// tree, and two fingers each holding on their own node must both be
1524 /// released.
1525 ///
1526 /// The other two rules in `tick_sequence_timers` — the deferred member's
1527 /// withdrawal and the tap family's revocation — stay behind, because both
1528 /// are decided by the [`TapBoundary`](crate::gesture::TapBoundary)
1529 /// against where the pointer now is. A contact that has not moved cannot
1530 /// have left the boundary, so running them here could only ever repeat the
1531 /// answer the last move already gave.
1532 pub(super) fn expire_sequence_holds(&mut self, now: crate::pointer::EventTime) {
1533 let Self {
1534 pointers,
1535 effective_theme,
1536 ..
1537 } = self;
1538 for entry in pointers.iter_mut() {
1539 let Some(sequence) = entry.sequence.as_mut() else {
1540 continue;
1541 };
1542 let profile = effective_theme.input.profile(sequence.pointer().kind);
1543 sequence.expire_holds(now, profile);
1544 }
1545 }
1546
1547 pub fn tick_gestures(&mut self, now: std::time::Instant) {
1548 let mut noop = crate::window::NoopWindowOps;
1549 self.tick_gestures_with_ops(now, &mut noop);
1550 }
1551
1552 /// App-facing variant of [`tick_gestures`](Self::tick_gestures)
1553 /// that accepts a real [`WindowOps`](crate::window::WindowOps)
1554 /// sink so gesture-recognized handlers can call the multi-window
1555 /// API synchronously.
1556 pub fn tick_gestures_with_ops(
1557 &mut self,
1558 now: std::time::Instant,
1559 ops: &mut dyn crate::window::WindowOps,
1560 ) {
1561 // Snapshot the gesture-owners set into the reusable scratch.
1562 // Previously this iterated every active widget; in practice
1563 // only a tiny fraction carry a gesture arena, so visiting the
1564 // rest was pure overhead.
1565 // `mem::take` lets the loop borrow `&mut self` for
1566 // `make_event_context` etc. without conflicting with the
1567 // scratch buffer; we put the storage back at the end.
1568 // The fling pump rides the same pass. It is an input deadline like a
1569 // long press, it is folded into the same `WaitUntil`
1570 // (`next_input_deadline`), and giving it its own call site would mean
1571 // every host had to learn a second one.
1572 self.tick_flings_with_ops(now, &mut *ops);
1573 // …and so does the press-feedback delay, for the same reason: it is an
1574 // input deadline folded into the same `WaitUntil`, and a finger resting
1575 // on a control produces no further samples to resolve it from.
1576 self.resolve_press_delays(self.event_time_for(now));
1577 // …and so does a standing hold's expiry, for the third time for the same
1578 // reason: a contact resting on a control produces no further samples,
1579 // and the framework's promise is that it stops trusting a holder after
1580 // `max_hold` — not that it stops trusting one after `max_hold` *and* a
1581 // move. See `expire_sequence_holds`.
1582 self.expire_sequence_holds(self.event_time_for(now));
1583 // …and so does the tree-owned long press, for the fourth time for the
1584 // same reason. It is not a recognizer: the affordances it reaches (a
1585 // context-menu factory the router walks up to, a tooltip on a node that
1586 // may be **disabled** and so has no arena at all) are the tree's, not a
1587 // widget's. See `super::touch_route`.
1588 self.resolve_touch_routes(self.event_time_for(now), &mut *ops);
1589
1590 let mut ids = std::mem::take(&mut self.active_ids_scratch);
1591 ids.clear();
1592 ids.extend(
1593 self.gesture_owners
1594 .iter()
1595 .copied()
1596 .filter(|id| self.arena.is_active(*id)),
1597 );
1598 let now = self.event_time_for(now);
1599 for &id in &ids {
1600 let cx = self.recognizer_context(id);
1601 let cx = crate::gesture::RecognizerContext { now, ..cx };
1602 let gestures = match self.arena.get_mut(id) {
1603 Some(node) => node
1604 .handlers
1605 .gesture_arena
1606 .as_mut()
1607 .map(|arena| arena.tick(&cx))
1608 .unwrap_or_default(),
1609 None => Vec::new(),
1610 };
1611 if gestures.is_empty() {
1612 continue;
1613 }
1614
1615 // One entry per contact: two fingers holding on the same node both
1616 // long-press, and neither may be dropped.
1617 for (pointer, gesture) in gestures {
1618 // The arbitration binds the timer path exactly as it binds the
1619 // sample path: a member that has been rejected, or that a peer's
1620 // hold has frozen, does not get to deliver a gesture just
1621 // because its own timer came due. Asked per contact, since two
1622 // fingers on one node are two independent sequences.
1623 //
1624 // It comes out one step later than on the sample path, which
1625 // withholds the *feed* — a tick is not addressed to a member,
1626 // so the whole node's recognizers advance and the gesture is
1627 // then dropped rather than deferred. That is what `Rejected`
1628 // wants anyway; for the transient `Held` case it means a peer
1629 // silenced at the instant its timer ripened loses that gesture
1630 // rather than firing it late, and the hold that silenced it is
1631 // released in this same pass (`expire_sequence_holds`, above)
1632 // once it reaches `max_hold`.
1633 if self.sequence_blocks_arena_for(pointer, id, now) {
1634 continue;
1635 }
1636 // One hold cannot mean two things. Where the hold is what arms
1637 // a grab — a reorderable row under a finger, whose drag member
1638 // was deferred to this very deadline, or one inside a node that
1639 // declared `LongPressRole::DragHandle` — the row's own long
1640 // press does not also fire.
1641 //
1642 // A mouse keeps its hold wherever the claim was *inferred*: it
1643 // enrols no pan competitor, so `DragActivation::Auto` is never
1644 // resolved to `AfterLongPress` on its sequence and nothing is
1645 // deferred by that route, and the `DragHandle` walk is gated on
1646 // a direct pointer because a mouse spends no hold arming a drag
1647 // it never asked for. A node that *declares*
1648 // `DragActivation::AfterLongPress` has asked: the declaration
1649 // passes through `resolve_activation` untouched, so the grab is
1650 // deferred to the hold for every pointer kind and that node's
1651 // own long press is spent under a mouse too. See
1652 // `long_press_is_a_grab` for the three doors.
1653 if matches!(gesture, crate::gesture::GestureEvent::LongPress(_))
1654 && self.long_press_is_a_grab(pointer, id)
1655 {
1656 continue;
1657 }
1658 // Install the contact this gesture belongs to for the length
1659 // of the dispatch. A hold is recognised here, by a deadline,
1660 // not by a sample — and `current_input` is saved-and-restored
1661 // around every dispatch (`run_one_dispatch`), so without this
1662 // it holds `InputSnapshot::default()` and every handler reached
1663 // from a hold is told it is serving **the mouse**, whatever the
1664 // device was.
1665 //
1666 // The snapshot is more than the device: it is the key
1667 // `make_event_context` builds the rest of the context from, so
1668 // every answer looked up by `current_pointer_id()` comes out
1669 // for the wrong pointer without it. What the context carries
1670 // in, and all of it: the device and the id the snapshot holds
1671 // outright (`EventContext::pointer_kind`, `pointer`), the
1672 // captor (`current_pointer_capture`), the frozen `TouchAction`
1673 // (`current_frozen_touch_action`, keyed through the contact's
1674 // sequence) and the press snapshot (`current_press_snapshot`).
1675 // What the context carries back out is a separate list, below.
1676 // The fling pump resolves its pointer from the table the same
1677 // way (`dispatch_chained_scroll`).
1678 let installed = self
1679 .pointers
1680 .get(pointer)
1681 .map(|entry| entry.info)
1682 .unwrap_or(self.current_input.pointer);
1683 let previous_input = std::mem::replace(
1684 &mut self.current_input,
1685 crate::pointer::InputSnapshot::for_recognized_gesture(installed),
1686 );
1687 let mut ctx = self.make_event_context(&mut *ops);
1688 if let Some(node) = self.arena.get_mut(id) {
1689 Self::dispatch_recognized_gesture(node, gesture, &mut ctx);
1690 }
1691 // `collect_from_ctx` **after** the restore would be wrong:
1692 // two of the requests a handler can queue name no pointer and
1693 // are applied to whichever one `current_pointer_id()` answers
1694 // with at collection time — an unnamed
1695 // `capture_pointer()`/`release_pointer()`, and
1696 // `cancel_pointer_sequence()`. Collected after the restore,
1697 // a hold that captured would have captured the mouse and a
1698 // hold that cancelled would have cancelled it. The sample path
1699 // has the same order — `run_one_dispatch` restores only once
1700 // `dispatch_event_impl`, collection included, has returned.
1701 self.collect_from_ctx(ctx, id);
1702 self.current_input = previous_input;
1703 }
1704 self.arena.mark_needs_paint(id);
1705 }
1706 self.active_ids_scratch = ids;
1707 }
1708
1709 /// Read an `Instant` handed in by the event loop on this tree's input
1710 /// timeline.
1711 ///
1712 /// Three answers, and not one of them is unconditionally the plain
1713 /// subtraction from the shared epoch (see
1714 /// [`input_clock`](Self::input_clock)) that a single axis would suggest:
1715 /// two ignore the caller's instant outright, and the third subtracts and
1716 /// then adds back whatever was advanced before the axis was handed back.
1717 ///
1718 /// * **Time is simulated.** The argument is discarded: the tree has one
1719 /// now, and it is not the caller's — an `Instant` handed in by a real
1720 /// event loop is on an axis this tree has stopped following.
1721 /// * **Time is real, under an anchored clock.** The caller's instant is
1722 /// honoured, as the distance from the shared epoch, *plus* whatever was
1723 /// advanced before the axis was handed back — a subtraction and then an
1724 /// addition, because the axis runs `sim_input_offset` ahead of the clock
1725 /// the caller read.
1726 /// * **A clock with no wall-clock anchor** — a
1727 /// [`ManualClock`](crate::pointer::clock::ManualClock) in a test — also
1728 /// ignores the argument and answers with its own reading, which is the
1729 /// whole point of installing one.
1730 pub(super) fn event_time_for(&self, now: std::time::Instant) -> crate::pointer::EventTime {
1731 match self.input_clock.epoch() {
1732 // While the axis is frozen the tree has one now, and it is not the
1733 // caller's: an `Instant` handed in by a real event loop is on an
1734 // axis this tree has stopped following for the length of the
1735 // advance.
1736 Some(_) if self.sim_input_origin.is_some() => self.input_now(),
1737 // Otherwise the caller's instant is honoured — two real events
1738 // milliseconds apart must not be stamped the same moment — shifted
1739 // by whatever was advanced before the axis was handed back.
1740 Some(epoch) => {
1741 crate::pointer::EventTime::from_duration(now.saturating_duration_since(epoch))
1742 + self.sim_input_offset
1743 }
1744 None => self.input_now(),
1745 }
1746 }
1747
1748 /// Turn an input-timeline deadline back into an `Instant` for the event
1749 /// loop, which schedules in wall-clock terms.
1750 pub(super) fn instant_for(&self, time: crate::pointer::EventTime) -> std::time::Instant {
1751 match self.input_clock.epoch() {
1752 // Inverse of the frozen branch of `event_time_for`: a deadline on
1753 // the virtual axis is reported against the virtual clock, so what
1754 // comes back is comparable with `simulated_now()` and not with a
1755 // wall clock this tree is not following for the length of the
1756 // advance.
1757 Some(_) if self.sim_input_origin.is_some() => {
1758 self.sim_clock + time.saturating_since(self.input_now())
1759 }
1760 // Inverse of the offset branch. Subtracting what was advanced is
1761 // what keeps this in the future: the deadline was stamped on an
1762 // axis running `sim_input_offset` ahead of the clock the event loop
1763 // schedules against, and reporting it unshifted would hand back an
1764 // instant already past — a `WaitUntil` that can never ripen and a
1765 // loop that spins on it.
1766 Some(epoch) => epoch + time.as_duration().saturating_sub(self.sim_input_offset),
1767 // An unanchored clock has no wall-clock answer; the best available
1768 // one is "as far from now as it is from the clock's reading".
1769 None => std::time::Instant::now() + time.saturating_since(self.input_now()),
1770 }
1771 }
1772
1773 /// Earliest wall-clock deadline at which any active gesture arena
1774 /// needs [`WidgetTree::tick_gestures`] called — typically a pending
1775 /// long-press timeout. Returns `None` when no recognizer is waiting.
1776 pub fn next_gesture_deadline(&self) -> Option<std::time::Instant> {
1777 // Iterate just the widgets that actually carry a gesture arena.
1778 // `filter` for `is_active` skips dormant entries that may still
1779 // be in the set after a hide-without-detach.
1780 self.gesture_owners
1781 .iter()
1782 .copied()
1783 .filter(|id| self.arena.is_active(*id))
1784 .filter_map(|id| self.arena.get(id))
1785 .filter_map(|node| node.handlers.gesture_arena.as_ref())
1786 .filter_map(|arena| arena.next_deadline())
1787 .min()
1788 .map(|deadline| self.instant_for(deadline))
1789 }
1790
1791 /// The earliest instant at which a standing hold reaches its
1792 /// `max_hold` and [`expire_sequence_holds`](Self::expire_sequence_holds)
1793 /// has work.
1794 ///
1795 /// Folded into [`next_input_deadline`](Self::next_input_deadline) beside
1796 /// the gesture, fling and press-feedback terms. A deadline the tick can
1797 /// serve but nothing reports is a wake the event loop never takes, which
1798 /// leaves the hold standing exactly as long as it did before the tick knew
1799 /// how to release it.
1800 pub(super) fn next_sequence_hold_deadline(&self) -> Option<crate::pointer::EventTime> {
1801 self.pointers
1802 .iter()
1803 .filter_map(|entry| entry.sequence.as_ref())
1804 .filter_map(|sequence| {
1805 let profile = self.effective_theme.input.profile(sequence.pointer().kind);
1806 sequence.next_hold_deadline(profile)
1807 })
1808 .min()
1809 }
1810
1811 /// The [`TouchAction`] permitted for `target`: every node's own
1812 /// declaration from the root down to `target` (inclusive), intersected.
1813 /// An ancestor's `NONE` wins no matter what a descendant declares —
1814 /// intersection is absorbing at `NONE` (see
1815 /// `crate::pointer::touch_action`), so this needs no early exit to get
1816 /// that right; it just folds the whole chain.
1817 ///
1818 /// One of the two path folds the arbitration reads: `begin_sequence` asks
1819 /// it what a press may do, and `feed_pinch` asks it whether a subtree
1820 /// admits a two-contact pinch.
1821 pub(crate) fn effective_touch_action(&self, target: WidgetId) -> TouchAction {
1822 let mut chain = Vec::new();
1823 let mut current = Some(target);
1824 while let Some(id) = current {
1825 chain.push(id);
1826 current = self.arena.parent(id);
1827 }
1828 // `chain` is target..=root (innermost first); fold root-to-target so
1829 // the read matches the CSS `touch-action` model this mirrors — an
1830 // ancestor's declaration is applied before a descendant's narrows it
1831 // further. `intersect` is commutative and associative, so the fold
1832 // order can never change the *answer*, only which step "loses" reads
1833 // as the natural one.
1834 chain
1835 .iter()
1836 .rev()
1837 .map(|&id| {
1838 self.arena
1839 .get(id)
1840 .map(|n| n.touch_action)
1841 .unwrap_or(TouchAction::AUTO)
1842 })
1843 .fold(TouchAction::AUTO, TouchAction::intersect)
1844 }
1845
1846 /// Every [`PanClaim`] from `target` up to the root, **innermost first**
1847 /// — the order a boundary pan chains along (a nested scrollable hits its
1848 /// edge and hands off to its container), so it is normative. A claimant
1849 /// is excluded entirely — never narrowed — when `allowed` forbids any
1850 /// axis it declares.
1851 ///
1852 /// The second of the two path folds the arbitration reads, and the chain
1853 /// a synthesised pan is delivered along — see `widget_tree::pan_arbiter`.
1854 pub(crate) fn pan_candidates(
1855 &self,
1856 target: WidgetId,
1857 allowed: TouchAction,
1858 ) -> Vec<(WidgetId, PanClaim)> {
1859 let mut result = Vec::new();
1860 let mut current = Some(target);
1861 while let Some(id) = current {
1862 if let Some(claim) = self.arena.get(id).and_then(|n| n.pan_claim) {
1863 let x_ok = !claim.axes.contains(Axis::X) || allowed.allows_pan_x();
1864 let y_ok = !claim.axes.contains(Axis::Y) || allowed.allows_pan_y();
1865 if x_ok && y_ok {
1866 result.push((id, claim));
1867 }
1868 }
1869 current = self.arena.parent(id);
1870 }
1871 result
1872 }
1873}
1874
1875#[cfg(test)]
1876mod tests {
1877 use super::*;
1878 use crate::test_widgets::FillWidget;
1879 use crate::widget_builder::WidgetBuilder;
1880
1881 #[test]
1882 fn destroy_subtree_clears_dangling_pointer_capture() {
1883 use crate::event::{EventResponse, Modifiers, PointerButton};
1884 use crate::test_widgets::StackWidget;
1885
1886 let mut tree = WidgetTree::new();
1887 let child = tree.add(FillWidget::new().on_pointer_event(|event, ctx| {
1888 if matches!(event, WidgetEvent::PointerDown { .. }) {
1889 ctx.capture_pointer();
1890 }
1891 EventResponse::Ignored
1892 }));
1893 let parent = tree.add(StackWidget::new().child(child));
1894 tree.layout(SizeProposal::exact(100.0, 50.0));
1895
1896 // A press inside the child captures the pointer to it.
1897 tree.dispatch_event(WidgetEvent::pointer_down(
1898 Point::new(50.0, 25.0),
1899 PointerButton::Primary,
1900 Modifiers::NONE,
1901 ));
1902 assert_eq!(
1903 tree.pointer_captured_by(),
1904 Some(child),
1905 "PointerDown handler should have captured the pointer"
1906 );
1907
1908 // Tearing down the capturing subtree (e.g. mid-gesture rebuild) must
1909 // release the capture eagerly rather than leaving a dangling id that
1910 // swallows every later Move/Up until the next layout pass heals it.
1911 tree.destroy_subtree(parent);
1912 assert_eq!(
1913 tree.pointer_captured_by(),
1914 None,
1915 "destroy_subtree must clear a capture anchored at a destroyed widget"
1916 );
1917 }
1918}
1919
1920/// The two path folds `effective_touch_action` / `pan_candidates` declare
1921/// for the arbitration package (P08) — exercised here in isolation, apart
1922/// from the dispatch paths that now read them (`begin_sequence`,
1923/// `feed_pinch`, and the pan arbiter).
1924#[cfg(test)]
1925mod touch_action_tests {
1926 use super::*;
1927 use crate::pointer::touch_action::PanAxes;
1928 use crate::test_widgets::FillWidget;
1929 use crate::widget_builder::WidgetBuilder;
1930
1931 /// A 20-deep chain, root to target, where one mid-level node declares
1932 /// `PAN_Y` and another declares `PINCH_ZOOM`. Neither permission is
1933 /// shared by the other, so the intersection collapses to `NONE` — the
1934 /// clearest possible demonstration that the fold really intersects the
1935 /// *whole* chain rather than reading only the nearest declaration.
1936 #[test]
1937 fn effective_touch_action_intersects_the_whole_root_to_target_chain() {
1938 let mut tree = WidgetTree::new();
1939 let mut chain = vec![tree.add(FillWidget::new())]; // depth 0: the root
1940 for depth in 1..20usize {
1941 let parent = *chain.last().expect("root was pushed");
1942 let id = if depth == 5 {
1943 tree.add_child(parent, FillWidget::new().touch_action(TouchAction::PAN_Y))
1944 } else if depth == 12 {
1945 tree.add_child(
1946 parent,
1947 FillWidget::new().touch_action(TouchAction::PINCH_ZOOM),
1948 )
1949 } else {
1950 tree.add_child(parent, FillWidget::new())
1951 };
1952 chain.push(id);
1953 }
1954 assert_eq!(chain.len(), 20, "the path must be 20 nodes deep");
1955 let target = *chain.last().expect("chain is non-empty");
1956 tree.layout(SizeProposal::exact(50.0, 50.0));
1957
1958 assert_eq!(
1959 tree.effective_touch_action(target),
1960 TouchAction::NONE,
1961 "PAN_Y at depth 5 and PINCH_ZOOM at depth 12 share no permission"
1962 );
1963
1964 // Every node above depth 5 (inclusive) is untouched: the plain
1965 // `AUTO` prefix intersects down to exactly `PAN_Y`.
1966 assert_eq!(tree.effective_touch_action(chain[5]), TouchAction::PAN_Y);
1967 }
1968
1969 /// `pan_candidates` walks target-to-root (innermost first) and drops a
1970 /// claimant whose declared axes the allowed action forbids, rather than
1971 /// narrowing it.
1972 #[test]
1973 fn pan_candidates_orders_innermost_first_and_filters_by_allowed_axes() {
1974 let mut tree = WidgetTree::new();
1975 // root claims X; an unclaimed node in between; target (innermost)
1976 // claims Y.
1977 let root = tree.add(FillWidget::new().scroll_container(PanAxes::X));
1978 let mid = tree.add_child(root, FillWidget::new());
1979 let target = tree.add_child(mid, FillWidget::new().scroll_container(PanAxes::Y));
1980 tree.layout(SizeProposal::exact(50.0, 50.0));
1981
1982 let x_claim = PanClaim {
1983 axes: PanAxes::X,
1984 devices: teksilo_tokens::PointerKindMask::DIRECT,
1985 kinetic: true,
1986 };
1987 let y_claim = PanClaim {
1988 axes: PanAxes::Y,
1989 devices: teksilo_tokens::PointerKindMask::DIRECT,
1990 kinetic: true,
1991 };
1992
1993 // Both axes allowed: both claims survive, innermost (target) first.
1994 assert_eq!(
1995 tree.pan_candidates(target, TouchAction::PAN),
1996 vec![(target, y_claim), (root, x_claim)]
1997 );
1998
1999 // Only PAN_X allowed: target's Y-axis claim is forbidden and
2000 // excluded outright; root's X-axis claim still survives.
2001 assert_eq!(
2002 tree.pan_candidates(target, TouchAction::PAN_X),
2003 vec![(root, x_claim)]
2004 );
2005
2006 // Only PAN_Y allowed: the reverse — root's claim is excluded,
2007 // target's survives.
2008 assert_eq!(
2009 tree.pan_candidates(target, TouchAction::PAN_Y),
2010 vec![(target, y_claim)]
2011 );
2012 }
2013}
2014
2015/// The one-clock rule: the input timeline and the tree's simulated clock are
2016/// one axis, seeded from one epoch.
2017#[cfg(test)]
2018mod clock_tests {
2019 use super::*;
2020 use crate::pointer::EventTime;
2021 use crate::pointer::clock::ManualClock;
2022
2023 /// The whole point of taking the epoch as a parameter rather than
2024 /// capturing it: `EventTime::ZERO` and the tree's simulated clock name the
2025 /// *same* instant, so one `advance_time` moves gesture deadlines and
2026 /// animations against the same origin.
2027 ///
2028 /// If this ever fails, the two timelines have drifted apart and a test that
2029 /// advances one has silently stopped advancing the other.
2030 #[test]
2031 fn the_input_clock_shares_the_trees_epoch() {
2032 let tree = WidgetTree::new();
2033 assert_eq!(
2034 tree.input_clock().epoch(),
2035 Some(tree.simulated_now()),
2036 "the input clock must be anchored at the instant sim_clock starts from"
2037 );
2038 }
2039
2040 /// …and stays one axis as simulated time moves: the offset between the
2041 /// simulated clock and the epoch is exactly what was advanced.
2042 #[test]
2043 fn advancing_simulated_time_moves_along_the_input_axis() {
2044 let mut tree = WidgetTree::new();
2045 let epoch = tree
2046 .input_clock()
2047 .epoch()
2048 .expect("the default input clock is monotonic");
2049
2050 tree.advance_time(std::time::Duration::from_millis(400));
2051 assert_eq!(
2052 tree.simulated_now().duration_since(epoch),
2053 std::time::Duration::from_millis(400)
2054 );
2055
2056 tree.advance_time(std::time::Duration::from_millis(100));
2057 assert_eq!(
2058 tree.simulated_now().duration_since(epoch),
2059 std::time::Duration::from_millis(500)
2060 );
2061 }
2062
2063 /// The simulated input axis continues from where the wall clock left it,
2064 /// rather than restarting at the simulated clock's own offset.
2065 ///
2066 /// A stamp taken before the switch would otherwise land in the virtual
2067 /// *future*: `sim_clock` only moves when it is advanced, so on a tree that
2068 /// has been alive for 50 ms it still reads the epoch while every sample
2069 /// dispatched so far is stamped 50 ms. Every interval measured from one of
2070 /// those is then clamped to zero — a hold that can never elapse, a coast
2071 /// that never starts.
2072 #[test]
2073 fn the_simulated_input_axis_continues_from_the_wall_clock() {
2074 let mut tree = WidgetTree::new();
2075 // Time the tree spent on the wall clock before anything simulated it —
2076 // in a real suite this is however long the test took to get here.
2077 std::thread::sleep(std::time::Duration::from_millis(50));
2078 let stamped_before_the_switch = tree.input_now();
2079 assert!(
2080 stamped_before_the_switch >= EventTime::from_millis(50),
2081 "the default clock is the wall clock until told otherwise: {stamped_before_the_switch:?}"
2082 );
2083
2084 tree.advance_time(std::time::Duration::from_millis(20));
2085 let after_one = tree.input_now();
2086 assert!(
2087 after_one >= stamped_before_the_switch + std::time::Duration::from_millis(20),
2088 "the axis carries on from the reading it had, not from the epoch: \
2089 {stamped_before_the_switch:?} -> {after_one:?}"
2090 );
2091
2092 // …and from then on it moves by exactly what is advanced, and by
2093 // nothing else — however long this test itself takes.
2094 std::thread::sleep(std::time::Duration::from_millis(20));
2095 tree.advance_time(std::time::Duration::from_millis(30));
2096 assert_eq!(
2097 tree.input_now(),
2098 after_one + std::time::Duration::from_millis(30),
2099 "a simulated tree's input timeline answers to the clock alone"
2100 );
2101 }
2102
2103 /// A test can take the input timeline over entirely.
2104 #[test]
2105 fn a_manual_clock_replaces_the_default() {
2106 let mut tree = WidgetTree::new();
2107 let manual = std::rc::Rc::new(ManualClock::new(EventTime::from_millis(30)));
2108 tree.set_input_clock(manual.clone());
2109
2110 assert_eq!(tree.input_now(), EventTime::from_millis(30));
2111 manual.advance(std::time::Duration::from_millis(70));
2112 assert_eq!(tree.input_now(), EventTime::from_millis(100));
2113 // Reading does not move it — a manual clock is only moved by its owner.
2114 assert_eq!(tree.input_now(), EventTime::from_millis(100));
2115 }
2116
2117 /// The default clock actually reads the wall clock, so a real window's
2118 /// gestures advance without anyone ticking anything.
2119 #[test]
2120 fn the_default_clock_is_monotonic() {
2121 let tree = WidgetTree::new();
2122 let a = tree.input_now();
2123 let b = tree.input_now();
2124 assert!(b >= a);
2125 }
2126
2127 /// Handing the axis back never steps it backwards.
2128 ///
2129 /// The whole reason the hand-back is not just "drop the origin": a frozen
2130 /// axis that has been advanced reads *ahead* of the raw clock, and every
2131 /// stamp already issued sits at that reading. Going back to the raw clock
2132 /// would re-issue times that have already been handed out — a velocity
2133 /// tracker fitting a negative interval, a tap streak whose second tap is
2134 /// older than its first, a hold that un-elapses.
2135 #[test]
2136 fn handing_the_axis_back_never_steps_it_backwards() {
2137 let mut tree = WidgetTree::new();
2138 tree.advance_time(std::time::Duration::from_millis(500));
2139 let frozen = tree.input_now();
2140
2141 tree.resume_real_time();
2142 let resumed = tree.input_now();
2143
2144 assert!(
2145 resumed >= frozen,
2146 "the axis must carry the advance forward, not discard it: \
2147 {frozen:?} -> {resumed:?}"
2148 );
2149 // …and it keeps every bit of what was advanced, rather than trading it
2150 // for however little wall time the test itself took.
2151 assert!(
2152 resumed >= EventTime::from_millis(500),
2153 "500 ms was advanced and must still be on the axis: {resumed:?}"
2154 );
2155 }
2156
2157 /// After the hand-back, real events are stamped from the real clock again:
2158 /// two of them separated by real time are two distinct moments.
2159 ///
2160 /// This is the whole point of the hand-back. While the axis is frozen every
2161 /// dispatch reads one instant, which is exactly right for a test driving
2162 /// the clock itself and exactly wrong for a live window: a bridge that
2163 /// advanced the clock once would leave every subsequent human keystroke,
2164 /// tap and drag stamped the same moment, and no gesture decided by time
2165 /// could ever be recognized again.
2166 #[test]
2167 fn after_the_hand_back_real_events_get_distinct_and_later_times() {
2168 use crate::test_widgets::FillWidget;
2169 use crate::widget_builder::WidgetBuilder;
2170 use std::cell::RefCell;
2171 use std::rc::Rc;
2172
2173 let seen: Rc<RefCell<Vec<EventTime>>> = Rc::new(RefCell::new(Vec::new()));
2174 let log = seen.clone();
2175 let mut tree = WidgetTree::new();
2176 tree.add(FillWidget::new().on_pointer_event(move |_event, ctx| {
2177 log.borrow_mut().push(ctx.pointer().time);
2178 crate::event::EventResponse::Ignored
2179 }));
2180 tree.layout(SizeProposal::exact(100.0, 100.0));
2181
2182 tree.pointer_move(Point::new(10.0, 10.0));
2183 tree.advance_time(std::time::Duration::from_millis(200));
2184 tree.resume_real_time();
2185
2186 tree.pointer_move(Point::new(20.0, 20.0));
2187 std::thread::sleep(std::time::Duration::from_millis(5));
2188 tree.pointer_move(Point::new(30.0, 30.0));
2189
2190 let seen = seen.borrow();
2191 assert_eq!(seen.len(), 3, "three moves reached the widget: {seen:?}");
2192 assert!(
2193 seen[1] >= seen[0] + std::time::Duration::from_millis(200),
2194 "an event after the advance is at least the advance later: {seen:?}"
2195 );
2196 assert!(
2197 seen[2] > seen[1],
2198 "two real events 5 ms apart are two moments, not one: {seen:?}"
2199 );
2200 }
2201
2202 /// …and the next advance freezes it again.
2203 ///
2204 /// The hand-back is not a latch in the other direction: a bridge running a
2205 /// second operation must get the same determinism the first one did, and a
2206 /// test's helpers (which enter simulated mode on every sample) must keep
2207 /// stamping two un-advanced samples the same instant.
2208 #[test]
2209 fn the_freeze_comes_back_after_a_hand_back() {
2210 let mut tree = WidgetTree::new();
2211 tree.advance_time(std::time::Duration::from_millis(100));
2212 tree.resume_real_time();
2213
2214 tree.advance_time(std::time::Duration::from_millis(100));
2215 let a = tree.input_now();
2216 std::thread::sleep(std::time::Duration::from_millis(5));
2217 let b = tree.input_now();
2218 assert_eq!(a, b, "re-frozen: the wall clock stopped moving the axis");
2219 }
2220
2221 /// Every hand-back re-measures the offset against its own readings; none
2222 /// of them adds to what the last one measured.
2223 ///
2224 /// The live bridge hands the axis back after **every** operation, so this
2225 /// is its ordinary path rather than an edge case — and accumulating
2226 /// instead of assigning compounds: each cycle would carry the previous
2227 /// offset into the frozen reading *and* add the previous offset again, so
2228 /// the axis would run `2ⁿ − 1` advances ahead after `n` of them. Four
2229 /// 50 ms cycles is 200 ms of advance and would be reported as 750 ms, and
2230 /// every duration measured from a stamp taken before the run — a hold, a
2231 /// tap streak, a fling's velocity window — would be wrong by the
2232 /// difference.
2233 ///
2234 /// **This is the only guard on the offset's magnitude.** Its companion
2235 /// `a_deadline_armed_after_the_hand_back_is_in_the_future` is insensitive
2236 /// to it by construction — the offset cancels between `event_time_for` and
2237 /// `instant_for`, so that test holds for a wrong offset as readily as for a
2238 /// right one — and nothing else asserts a number. So the
2239 /// ceiling below is expressed **per cycle**: the allowance scales with the
2240 /// work done, so the error it admits per hand-back stays at
2241 /// `SLACK_PER_CYCLE` whatever `CYCLES` is. A single absolute ceiling
2242 /// instead divides by the cycle count — slack at a handful of cycles, and
2243 /// firing on the loop's own wall-clock noise at a hundred.
2244 #[test]
2245 fn repeated_hand_backs_re_measure_the_offset_rather_than_accumulating_it() {
2246 const CYCLES: u32 = 4;
2247 const PER_CYCLE: std::time::Duration = std::time::Duration::from_millis(50);
2248 // What one hand-back may cost beyond what it advanced: the wall clock
2249 // moves while the loop runs, and the loop's own work is not free.
2250 const SLACK_PER_CYCLE: std::time::Duration = std::time::Duration::from_millis(10);
2251 let advanced = PER_CYCLE * CYCLES;
2252
2253 let mut tree = WidgetTree::new();
2254 let before = tree.input_now();
2255 for _ in 0..CYCLES {
2256 tree.advance_time(PER_CYCLE);
2257 tree.resume_real_time();
2258 }
2259 let after = tree.input_now();
2260 let gained = after.saturating_since(before);
2261
2262 assert!(
2263 gained >= advanced,
2264 "every advance must still be on the axis: {gained:?} < {advanced:?}"
2265 );
2266 // The wall clock also moved while the loop ran, so the axis is allowed
2267 // to have gained a little more than was advanced — but only a little,
2268 // and the allowance is per hand-back rather than for the run.
2269 // Accumulating would put it at 750 ms, three and a half times over.
2270 assert!(
2271 gained <= advanced + SLACK_PER_CYCLE * CYCLES,
2272 "the axis gained {gained:?} for {advanced:?} of advancing over \
2273 {CYCLES} hand-backs — the offset is compounding across them"
2274 );
2275 }
2276
2277 /// An animation in flight when the tree is put on the simulated clock
2278 /// keeps the phase it had, and goes on progressing.
2279 ///
2280 /// The scheduler stores absolute instants, and the simulated clock reads
2281 /// the tree's epoch plus whatever has been advanced — on a live window,
2282 /// far behind the wall clock the animation was stamped against. Measuring
2283 /// it there without rebasing clamps its elapsed time to roughly zero and
2284 /// it never moves again, however many frames the operation advances.
2285 #[test]
2286 fn an_animation_in_flight_keeps_its_phase_when_time_is_taken_over() {
2287 use crate::signal::Signal;
2288 use crate::test_widgets::FillWidget;
2289 use std::time::Duration;
2290
2291 let mut tree = WidgetTree::new();
2292 let owner = tree.add(FillWidget::new());
2293 tree.layout(SizeProposal::exact(100.0, 100.0));
2294
2295 // Long enough that a loaded CI runner overshooting the sleep below by
2296 // a few hundred milliseconds — a macOS runner has been seen to take
2297 // 250 ms over a 100 ms sleep — cannot run it to completion before the
2298 // take-over, which would leave nothing for the advance to move.
2299 const DURATION: Duration = Duration::from_millis(4000);
2300
2301 let value = Signal::<f32>::new_animated(0.0);
2302 tree.register_animated_signal(&value, owner);
2303 value.animate_to(1.0, DURATION, teksilo_tokens::Easing::Linear);
2304
2305 // Promote and age it on the wall clock, exactly as a live window does.
2306 tree.layout(SizeProposal::exact(100.0, 100.0));
2307 std::thread::sleep(Duration::from_millis(100));
2308 tree.layout(SizeProposal::exact(100.0, 100.0));
2309 let on_the_wall_clock = value.get();
2310 // 100 ms of 4000 is 0.025; the sleep never undershoots, and the bound
2311 // above allows the runner nearly two seconds of overshoot.
2312 assert!(
2313 (0.02..0.5).contains(&on_the_wall_clock),
2314 "in flight after 100 ms of {DURATION:?}: {on_the_wall_clock}"
2315 );
2316
2317 // Now an automation operation takes time over and advances a further
2318 // 1000 ms. The animation must have moved on by exactly that share of
2319 // its duration — not stuck where the wall clock left it, and not
2320 // restarted from the simulated clock's own reading.
2321 tree.advance_time(Duration::from_millis(1000));
2322 let simulated = value.get();
2323 let moved = simulated - on_the_wall_clock;
2324 // 1000 ms of 4000 is 0.25. Whatever wall-clock time passed between the
2325 // reading above and the take-over is in there too, so the bound is
2326 // loose above — by 400 ms — and tight below.
2327 assert!(
2328 (0.245..0.35).contains(&moved),
2329 "the advance keeps the phase and adds its own 1000 ms of \
2330 {DURATION:?}: {on_the_wall_clock} -> {simulated}"
2331 );
2332 }
2333
2334 /// …and once time is handed back, the wall clock goes on driving it from
2335 /// where the advance left it — neither frozen nor snapped to its end.
2336 ///
2337 /// The two failures this rules out are the two halves of getting the axis
2338 /// wrong on a *live* attached window. Ticking at the simulated clock a
2339 /// live tree no longer advances freezes every animation outright. Ticking
2340 /// at the wall clock against a start stamped on the simulated one hands
2341 /// the animation an elapsed time of the tree's whole age and completes it
2342 /// on the first real frame.
2343 #[test]
2344 fn an_animation_goes_on_progressing_after_the_hand_back() {
2345 use crate::signal::Signal;
2346 use crate::test_widgets::FillWidget;
2347 use std::time::Duration;
2348
2349 let mut tree = WidgetTree::new();
2350 let owner = tree.add(FillWidget::new());
2351 tree.layout(SizeProposal::exact(100.0, 100.0));
2352
2353 // The tree spends real time alive before anything simulates it, and
2354 // more of it than will be advanced. That is the live condition, and it
2355 // is what makes the *second* assertion below discriminating: with the
2356 // wall clock ahead of the simulated one, an un-rebased hand-back hands
2357 // the animation an elapsed time longer than its whole duration.
2358 std::thread::sleep(Duration::from_millis(300));
2359
2360 let value = Signal::<f32>::new_animated(0.0);
2361 tree.register_animated_signal(&value, owner);
2362 // 2 s rather than something short: the 100 ms slept after the
2363 // hand-back is a floor, not a figure, and a loaded runner has
2364 // overshot it by 150 ms — the "not snapped to the end" bound below
2365 // must hold through that.
2366 value.animate_to(
2367 1.0,
2368 Duration::from_millis(2000),
2369 teksilo_tokens::Easing::Linear,
2370 );
2371
2372 // The operation promotes it and advances it a twentieth of the way.
2373 tree.advance_time(Duration::from_millis(100));
2374 let at_hand_back = value.get();
2375 assert!(
2376 (0.04..0.06).contains(&at_hand_back),
2377 "a twentieth through after 100 ms of 2000: {at_hand_back}"
2378 );
2379
2380 // The operation ends and the window goes back to painting frames.
2381 tree.resume_real_time();
2382 std::thread::sleep(Duration::from_millis(100));
2383 tree.layout(SizeProposal::exact(100.0, 100.0));
2384
2385 let after = value.get();
2386 // At least 100 ms of 2000 (0.05) moved it; the sleep only overshoots.
2387 assert!(
2388 after > at_hand_back + 0.045,
2389 "frozen: 100 ms of real time moved it from {at_hand_back} to {after}"
2390 );
2391 assert!(
2392 after < 0.95,
2393 "snapped to the end: 100 ms of 2000 took it from {at_hand_back} to {after}"
2394 );
2395 }
2396
2397 /// A `max_duration` cap measures the animation's own age across the
2398 /// hand-back, not the tree's.
2399 ///
2400 /// `started_at` is the only stored instant the cap reads, and until this
2401 /// test nothing asserted that the rebase shifts it: no production caller
2402 /// sets `max_duration` at all, so the branch is entered only from the
2403 /// public
2404 /// [`Signal::try_animate_with_options`](crate::signal::Signal::try_animate_with_options)
2405 /// and from the scheduler's own unit tests, which never change axis.
2406 /// Left behind on the abandoned axis, `started_at` makes the cap measure
2407 /// the tree's whole wall-clock age instead of the animation's own elapsed
2408 /// time, and the first real frame after the hand-back retires the
2409 /// animation outright — the same snap the rebase exists to prevent,
2410 /// arriving through a different door.
2411 ///
2412 /// The cap is deliberately smaller than the tree's age at the final layout
2413 /// and larger than the animation's own elapsed time there, so the two ways
2414 /// of measuring it disagree about whether it has been reached.
2415 #[test]
2416 fn a_capped_animation_survives_the_hand_back() {
2417 use crate::animation::AnimationRequest;
2418 use crate::signal::Signal;
2419 use crate::test_widgets::FillWidget;
2420 use std::time::Duration;
2421
2422 // The animation lives 200 ms before the final reading — 100 simulated,
2423 // 100 real — and the tree at least 600 ms. The cap sits between the
2424 // two with room on both sides: a loaded runner overshoots a sleep by
2425 // 100 ms or more, and every overshoot ages the tree further but the
2426 // animation only through the real half.
2427 const CAP: Duration = Duration::from_millis(400);
2428 const DURATION: Duration = Duration::from_millis(2000);
2429
2430 let mut tree = WidgetTree::new();
2431 let owner = tree.add(FillWidget::new());
2432 tree.layout(SizeProposal::exact(100.0, 100.0));
2433
2434 // Age the tree past the cap before the animation is armed at all.
2435 std::thread::sleep(Duration::from_millis(500));
2436
2437 let value = Signal::<f32>::new_animated(0.0);
2438 tree.register_animated_signal(&value, owner);
2439 value
2440 .try_animate_with_options(AnimationRequest {
2441 target: 1.0,
2442 duration: DURATION,
2443 easing: teksilo_tokens::Easing::Linear,
2444 max_duration: Some(CAP),
2445 ..AnimationRequest::default()
2446 })
2447 .expect("an animated signal accepts a request");
2448
2449 // 100 ms simulated, then 100 ms real: 200 ms of the animation's own
2450 // life, against a tree already older than the cap.
2451 tree.advance_time(Duration::from_millis(100));
2452 let at_hand_back = value.get();
2453 tree.resume_real_time();
2454 std::thread::sleep(Duration::from_millis(100));
2455 tree.layout(SizeProposal::exact(100.0, 100.0));
2456
2457 let after = value.get();
2458 assert!(
2459 tree.has_active_animations(),
2460 "a {CAP:?} cap retired a {DURATION:?} animation 200 ms in: \
2461 {at_hand_back} -> {after}"
2462 );
2463 assert!(
2464 after > at_hand_back,
2465 "the animation must go on progressing: {at_hand_back} -> {after}"
2466 );
2467 }
2468
2469 /// An animation paused across a hand-back resumes from where it was
2470 /// paused, rather than being driven backwards by the gap between the axes.
2471 ///
2472 /// The pause mark is the scheduler's one instant that is not per-animation,
2473 /// and until this test nothing asserted that the rebase shifts it: on
2474 /// reactivate the scheduler moves each `start_time` forward by
2475 /// `now - paused_at`, so a mark left behind on the abandoned axis measures
2476 /// the whole gap between the axes and puts the start ahead of the reading
2477 /// that follows it — the animation's elapsed time collapses, and it
2478 /// replays from near zero once the wall clock reaches the new start.
2479 ///
2480 /// The wall clock is deliberately left further ahead of the simulated one
2481 /// than the real time that elapses after the hand-back, which is exactly
2482 /// the condition under which the collapse leaves the animation *behind*
2483 /// where it was paused rather than merely slowed.
2484 #[test]
2485 fn an_animation_paused_across_the_hand_back_resumes_forwards() {
2486 use crate::signal::Signal;
2487 use crate::test_widgets::FillWidget;
2488 use std::time::Duration;
2489
2490 let mut tree = WidgetTree::new();
2491 let owner = tree.add(FillWidget::new());
2492 tree.layout(SizeProposal::exact(100.0, 100.0));
2493 std::thread::sleep(Duration::from_millis(300));
2494
2495 let value = Signal::<f32>::new_animated(0.0);
2496 tree.register_animated_signal(&value, owner);
2497 value.animate_to(
2498 1.0,
2499 Duration::from_millis(1000),
2500 teksilo_tokens::Easing::Linear,
2501 );
2502
2503 tree.advance_time(Duration::from_millis(100));
2504 let at_pause = value.get();
2505 assert!(
2506 (0.05..0.2).contains(&at_pause),
2507 "a tenth through after 100 ms of 1000: {at_pause}"
2508 );
2509
2510 // The window loses focus while the operation still owns the clock, and
2511 // regains it after the hand-back — the ordering that makes the pause
2512 // mark and the reading it is subtracted from land on different axes.
2513 tree.set_window_active(false);
2514 tree.resume_real_time();
2515 tree.set_window_active(true);
2516
2517 std::thread::sleep(Duration::from_millis(150));
2518 tree.layout(SizeProposal::exact(100.0, 100.0));
2519
2520 let after = value.get();
2521 assert!(
2522 after > at_pause,
2523 "frozen or driven backwards across a paused hand-back: \
2524 {at_pause} -> {after}"
2525 );
2526 }
2527
2528 /// …and the same, with the gap between the two axes the other way round:
2529 /// the pause mark is stamped on the axis the scheduler is measured
2530 /// against, not on the wall clock.
2531 ///
2532 /// The twin of the test above, and it cannot be merged with it. Which of
2533 /// the two mistakes is observable depends on the *sign* of the gap at the
2534 /// moment of the pause: a mark the rebase left behind only yields a
2535 /// spurious offset while the wall clock leads, and a mark taken from the
2536 /// wall clock instead of the animation clock only survives the
2537 /// subtraction — rather than flooring at zero — while the simulated clock
2538 /// leads. Each test rules out the sign the other needs, so each covers one
2539 /// mistake.
2540 ///
2541 /// Here the simulated clock is advanced past a tree milliseconds old, so
2542 /// it leads — and a wall-clock mark, shifted by the hand-back's rebase
2543 /// like the animation-axis instant it is not, comes out a whole advance
2544 /// early and is subtracted from the reading on reactivate as if the window
2545 /// had been dark for that long.
2546 #[test]
2547 fn a_pause_mark_is_stamped_on_the_animation_axis() {
2548 use crate::signal::Signal;
2549 use crate::test_widgets::FillWidget;
2550 use std::time::Duration;
2551
2552 let mut tree = WidgetTree::new();
2553 let owner = tree.add(FillWidget::new());
2554 tree.layout(SizeProposal::exact(100.0, 100.0));
2555
2556 let value = Signal::<f32>::new_animated(0.0);
2557 tree.register_animated_signal(&value, owner);
2558 value.animate_to(
2559 1.0,
2560 Duration::from_millis(5000),
2561 teksilo_tokens::Easing::Linear,
2562 );
2563
2564 // A second of simulated time on a tree milliseconds old: the advance,
2565 // not a sleep, is what separates the axes, and it separates them the
2566 // other way.
2567 tree.advance_time(Duration::from_millis(1000));
2568 let at_pause = value.get();
2569 assert!(
2570 (0.15..0.25).contains(&at_pause),
2571 "a fifth through after 1000 ms of 5000: {at_pause}"
2572 );
2573
2574 tree.set_window_active(false);
2575 tree.resume_real_time();
2576 tree.set_window_active(true);
2577
2578 std::thread::sleep(Duration::from_millis(150));
2579 tree.layout(SizeProposal::exact(100.0, 100.0));
2580
2581 let after = value.get();
2582 assert!(
2583 after > at_pause,
2584 "the deactivation cost the animation its phase: {at_pause} -> {after}"
2585 );
2586 }
2587
2588 /// A gesture the **timer** recognised is dispatched under its own contact.
2589 ///
2590 /// The whole class of defect this pins: a hold is not a sample, so nothing
2591 /// on the sample path installs a snapshot for it, and `current_input` is
2592 /// saved-and-restored around every dispatch — so a handler reached from a
2593 /// hold used to be told, unconditionally, that it was serving the mouse.
2594 /// It was measured that way (a probe on a real `long_press_at(Touch, ..)`
2595 /// printed `Mouse`), and it cost the first host of the touch-text contract
2596 /// a duplicate guard: `TouchSelection::on_long_press` refused every finger.
2597 ///
2598 /// This asserts the whole of what the context carries **in**: the device,
2599 /// the id, the captor, the frozen `TouchAction` and the press snapshot.
2600 /// What a handler asks the tree *for* from inside a hold — a capture, a
2601 /// cancel — travels the other way and is asserted by
2602 /// `a_hold_captures_and_cancels_the_contact_that_held`.
2603 ///
2604 /// The mouse half is not decoration: it is what proves the fix installs the
2605 /// *holding contact* rather than hard-coding a finger.
2606 #[test]
2607 fn a_hold_is_dispatched_under_the_contact_that_held() {
2608 use crate::TouchAction;
2609 use crate::test_widgets::FillWidget;
2610 use crate::widget_builder::WidgetBuilder;
2611
2612 /// Every answer the context is built from the installed snapshot.
2613 #[derive(Debug, Clone, Copy)]
2614 struct Answers {
2615 kind: teksilo_tokens::PointerKind,
2616 id: crate::pointer::PointerId,
2617 captor: Option<WidgetId>,
2618 touch_action: TouchAction,
2619 press_inside: bool,
2620 }
2621
2622 for kind in [
2623 teksilo_tokens::PointerKind::Touch,
2624 teksilo_tokens::PointerKind::Mouse,
2625 ] {
2626 let seen: std::rc::Rc<std::cell::Cell<Option<Answers>>> = Default::default();
2627 let mut tree = WidgetTree::new();
2628 let held_by = {
2629 let seen = seen.clone();
2630 tree.add(
2631 // A declared, non-`AUTO` action so the frozen value is
2632 // distinguishable from the neutral one a pointer with no
2633 // sequence answers with.
2634 FillWidget::new()
2635 .touch_action(TouchAction::PAN_Y)
2636 .on_long_press(move |_e, ctx| {
2637 seen.set(Some(Answers {
2638 kind: ctx.pointer_kind(),
2639 id: ctx.pointer().id,
2640 // Read off the field rather than through
2641 // `owns_pointer()`, which also needs a
2642 // `dispatch_node` — and a timer dispatch,
2643 // addressed to a node rather than walking to
2644 // one, sets none.
2645 captor: ctx.pointer_captor,
2646 touch_action: ctx.touch_action(),
2647 press_inside: ctx.press_is_inside(),
2648 }));
2649 }),
2650 )
2651 };
2652 tree.layout(SizeProposal::exact(100.0, 100.0));
2653
2654 let held = tree.long_press_at(kind, Point::new(50.0, 50.0));
2655 let seen = seen.get().expect("the hold was dispatched");
2656
2657 assert_eq!(
2658 seen.kind, kind,
2659 "a {kind:?} hold was dispatched as {:?}",
2660 seen.kind
2661 );
2662 assert_eq!(
2663 seen.id, held,
2664 "a hold must carry the identity of the contact that held"
2665 );
2666 assert_eq!(
2667 seen.captor,
2668 Some(held_by),
2669 "the captor is looked up by the dispatched pointer, and the \
2670 holding contact's is the node whose arena took its press"
2671 );
2672 assert_eq!(
2673 seen.touch_action,
2674 TouchAction::PAN_Y,
2675 "the frozen action is read off the dispatched pointer's \
2676 sequence, so a hold under the wrong pointer reads the \
2677 neutral {:?} of a pointer that has none",
2678 TouchAction::AUTO
2679 );
2680 assert!(
2681 seen.press_inside,
2682 "the press snapshot is keyed by the dispatched pointer, and \
2683 the contact that held is holding a press"
2684 );
2685 }
2686 }
2687
2688 /// What a hold handler asks the tree **for** is applied to the contact that
2689 /// held.
2690 ///
2691 /// The other half of
2692 /// `a_hold_is_dispatched_under_the_contact_that_held`: that one asserts
2693 /// what the context is built with, this one what the context is collected
2694 /// into. Two requests carry no pointer of their own
2695 /// and are resolved against `current_pointer_id()` at collection —
2696 /// `capture_pointer()` and `cancel_pointer_sequence()` — so collecting
2697 /// after `current_input` is restored, rather than before, silently
2698 /// addresses both to the mouse.
2699 ///
2700 /// The mouse is made live in both arms and is *not* the contact under test,
2701 /// so a misrouted request lands somewhere the assertions can see rather
2702 /// than on a pointer the table does not hold.
2703 #[test]
2704 fn a_hold_captures_and_cancels_the_contact_that_held() {
2705 use crate::pointer::{CancelReason, PointerId};
2706 use crate::test_widgets::FillWidget;
2707 use crate::widget_builder::WidgetBuilder;
2708
2709 // The capture the handler takes rides on the contact, and the mouse —
2710 // live, hovering, holding nothing — is left alone. The contact's own
2711 // entry is already captured by this node (the arena takes it implicitly
2712 // at the press), so the mouse half is what a misroute shows up in.
2713 {
2714 let mut tree = WidgetTree::new();
2715 let node = tree.add(FillWidget::new().on_long_press(|_e, ctx| {
2716 ctx.capture_pointer();
2717 }));
2718 tree.layout(SizeProposal::exact(100.0, 100.0));
2719 tree.pointer_move(Point::new(10.0, 10.0));
2720
2721 let contact = hold_a_finger(&mut tree, Point::new(50.0, 50.0));
2722
2723 assert_eq!(
2724 tree.captured_by(contact),
2725 Some(node),
2726 "a capture taken from a hold belongs to the contact that held"
2727 );
2728 assert_eq!(
2729 tree.captured_by(PointerId::MOUSE),
2730 None,
2731 "the mouse was not the thing holding, and must not have been \
2732 captured on its behalf"
2733 );
2734 }
2735
2736 // The cancel the handler raises revokes the contact, and only it. The
2737 // finger's entry is gone (a contact that is taken away ceases to exist);
2738 // the mouse's press-less entry is untouched.
2739 {
2740 let mut tree = WidgetTree::new();
2741 tree.add(FillWidget::new().on_long_press(|_e, ctx| {
2742 ctx.cancel_pointer_sequence(CancelReason::WidgetDestroyed);
2743 }));
2744 tree.layout(SizeProposal::exact(100.0, 100.0));
2745 tree.pointer_move(Point::new(10.0, 10.0));
2746
2747 let contact = hold_a_finger(&mut tree, Point::new(50.0, 50.0));
2748
2749 assert!(
2750 !tree.live_pointers().any(|p| p.id == contact),
2751 "a cancel raised from a hold revokes the contact that held"
2752 );
2753 assert!(
2754 tree.live_pointers().any(|p| p.id == PointerId::MOUSE),
2755 "and revokes nothing else"
2756 );
2757 }
2758 }
2759
2760 /// Press one finger at `at` and let its hold ripen, without releasing it.
2761 ///
2762 /// [`long_press_at`](WidgetTree::long_press_at) lifts the contact, and a
2763 /// lift takes the capture back and ends the entry — so what the hold's own
2764 /// handler did to the pointer table is only observable before it.
2765 fn hold_a_finger(tree: &mut WidgetTree, at: Point) -> crate::pointer::PointerId {
2766 let hold = tree
2767 .effective_theme
2768 .input
2769 .profile(teksilo_tokens::PointerKind::Touch)
2770 .long_press;
2771 let contact = tree.new_contact();
2772 tree.touch_down(contact, at);
2773 tree.advance_input_time(hold);
2774 contact
2775 }
2776
2777 /// A deadline armed after the hand-back is reported to the event loop as a
2778 /// *future* instant.
2779 ///
2780 /// `instant_for` is what the winit loop turns into
2781 /// `ControlFlow::WaitUntil`. A deadline reported in the past is not a
2782 /// harmless rounding error: the loop wakes immediately, finds nothing
2783 /// ripe, re-derives the same past instant and spins at full CPU on a
2784 /// deadline that can never arrive.
2785 ///
2786 /// The advance is deliberately a large fraction of the hold, so that
2787 /// shifting by it once too often or once too few — the two ways
2788 /// `instant_for` can be wrong — moves the answer by far more than the
2789 /// tolerance below. Reported *early* is the spinning loop above; reported
2790 /// *late* is a long press the user waits an extra advance for.
2791 ///
2792 /// What this test does **not** cover is the offset's magnitude: it is
2793 /// subtracted here by exactly the amount `event_time_for` added, so the two
2794 /// cancel and the assertions below hold for a wrong offset as readily as
2795 /// for a right one. That number is guarded only by
2796 /// `repeated_hand_backs_re_measure_the_offset_rather_than_accumulating_it`.
2797 #[test]
2798 fn a_deadline_armed_after_the_hand_back_is_in_the_future() {
2799 use crate::test_widgets::FillWidget;
2800 use crate::widget_builder::WidgetBuilder;
2801
2802 // The tree spends real time alive before anything simulates it — which
2803 // on a live app is every second since launch, and is what makes a
2804 // deadline reported against the simulated clock land in the past.
2805 let mut tree = WidgetTree::new();
2806 tree.add(FillWidget::new().on_long_press(|_e, _c| {}));
2807 tree.layout(SizeProposal::exact(100.0, 100.0));
2808 std::thread::sleep(std::time::Duration::from_millis(60));
2809
2810 let advanced = std::time::Duration::from_millis(200);
2811 tree.advance_time(advanced);
2812 tree.resume_real_time();
2813
2814 tree.pointer_down_button(Point::new(50.0, 50.0), PointerButton::Primary);
2815 let hold = tree
2816 .theme()
2817 .input
2818 .profile(teksilo_tokens::PointerKind::Mouse)
2819 .long_press;
2820 let slack = std::time::Duration::from_millis(50);
2821 // The two assertions below only mean something while the advance
2822 // dominates the tolerance. Stated here so a later change to either
2823 // constant fails loudly instead of quietly re-opening the gap a 10 ms
2824 // advance and a 30 ms tolerance left.
2825 assert!(
2826 slack * 4 <= advanced && advanced * 4 >= hold,
2827 "the tolerance must be a fraction of the advance, and the advance a \
2828 large fraction of the hold: slack {slack:?}, advanced {advanced:?}, \
2829 hold {hold:?}"
2830 );
2831 let deadline = tree
2832 .next_timer_deadline()
2833 .expect("a held press has a long-press deadline");
2834 let wait = deadline.saturating_duration_since(std::time::Instant::now());
2835
2836 assert!(
2837 wait > std::time::Duration::ZERO,
2838 "the loop must be given something it can wait for"
2839 );
2840 // And it is the hold away — not the hold minus what was advanced
2841 // (subtracted a second time, the spinning loop), and not the hold plus
2842 // it (never subtracted at all). The tolerance is a quarter of the
2843 // advance, so neither can hide inside it.
2844 assert!(
2845 wait <= hold,
2846 "wake in ~{hold:?} after a {advanced:?} advance, got {wait:?} — reported late"
2847 );
2848 assert!(
2849 wait + slack >= hold,
2850 "wake in ~{hold:?} after a {advanced:?} advance, got {wait:?} — reported early"
2851 );
2852 tree.pointer_up_button(Point::new(50.0, 50.0), PointerButton::Primary);
2853 }
2854}
2855
2856/// The per-pointer table replacing the tree's singular pointer state: two
2857/// contacts hold two captures, hover belongs to the hover owner alone, the
2858/// contact cap is enforced at the door, and a nested dispatch waits its turn.
2859#[cfg(test)]
2860mod pointer_table_tests {
2861 use super::*;
2862 use crate::event::{EventResponse, Modifiers, PointerButton};
2863 use crate::pointer::{
2864 BackendDeviceKey, EventTime, PointerId, PointerIdAllocator, PointerInfo, PointerPhase,
2865 PointerSample,
2866 };
2867 use crate::test_widgets::FillWidget;
2868 use crate::widget_builder::WidgetBuilder;
2869 use std::cell::RefCell;
2870 use std::rc::Rc;
2871
2872 /// A fresh contact identity. Minted through the real allocator so it is
2873 /// monotonic and distinct from [`PointerId::MOUSE`].
2874 fn contact_id(raw: u64) -> PointerId {
2875 let alloc = PointerIdAllocator::global();
2876 let device = BackendDeviceKey::new(0xC0FFEE);
2877 let id = alloc.begin(device, raw);
2878 alloc.end(device, raw);
2879 id
2880 }
2881
2882 fn contact(id: PointerId, phase: PointerPhase, at: Point) -> PointerSample {
2883 PointerSample {
2884 pointer: PointerInfo::touch(id, EventTime::ZERO),
2885 phase,
2886 position: at,
2887 button: None,
2888 modifiers: Modifiers::NONE,
2889 coalesced: Vec::new(),
2890 }
2891 }
2892
2893 /// A widget that captures the pointer on press and holds it. The shape of
2894 /// every real drag handle (a slider knob, a splitter divider).
2895 fn capturing() -> impl crate::widget::Widget + 'static {
2896 FillWidget::new().on_pointer_event(|event, ctx| {
2897 if matches!(event, WidgetEvent::PointerDown { .. }) {
2898 ctx.capture_pointer();
2899 }
2900 EventResponse::Ignored
2901 })
2902 }
2903
2904 /// Two contacts on two widgets hold **independent** captures, and one
2905 /// lifting leaves the other's alone. With a single `pointer_captured_by`
2906 /// the second press overwrote the first, and the first finger's stream
2907 /// silently moved to the second widget.
2908 #[test]
2909 fn two_contacts_hold_independent_captures() {
2910 let mut tree = WidgetTree::new();
2911 let a = tree.add(capturing());
2912 let b = tree.add(capturing());
2913 let _root = tree.add(SideBySide { a, b });
2914 tree.layout(SizeProposal::exact(100.0, 100.0));
2915
2916 let first = contact_id(1);
2917 let second = contact_id(2);
2918 tree.dispatch_pointer(contact(first, PointerPhase::Down, Point::new(25.0, 50.0)));
2919 tree.dispatch_pointer(contact(second, PointerPhase::Down, Point::new(75.0, 50.0)));
2920
2921 assert_eq!(tree.captured_by(first), Some(a));
2922 assert_eq!(tree.captured_by(second), Some(b));
2923
2924 tree.dispatch_pointer(contact(first, PointerPhase::Up, Point::new(25.0, 50.0)));
2925 assert_eq!(tree.captured_by(first), None, "the lifted contact is gone");
2926 assert_eq!(
2927 tree.captured_by(second),
2928 Some(b),
2929 "one contact lifting must not release the other's capture"
2930 );
2931 }
2932
2933 /// A finger arriving while the mouse hovers must not touch hover at all —
2934 /// not the id, not the signal, not the `on_hover` handlers behind it.
2935 #[test]
2936 fn a_second_contact_never_churns_the_hover_signal() {
2937 let mut tree = WidgetTree::new();
2938 let a = tree.add(FillWidget::new());
2939 let b = tree.add(FillWidget::new());
2940 let _root = tree.add(SideBySide { a, b });
2941 tree.layout(SizeProposal::exact(100.0, 100.0));
2942
2943 tree.dispatch_event(WidgetEvent::pointer_move(Point::new(25.0, 50.0)));
2944 assert_eq!(tree.hovered(), Some(a));
2945
2946 let churn = Rc::new(std::cell::Cell::new(0usize));
2947 let observer = {
2948 let churn = churn.clone();
2949 tree.hovered_signal()
2950 .observe(move |_| churn.set(churn.get() + 1))
2951 };
2952
2953 let finger = contact_id(3);
2954 tree.dispatch_pointer(contact(finger, PointerPhase::Down, Point::new(75.0, 50.0)));
2955 tree.dispatch_pointer(contact(finger, PointerPhase::Move, Point::new(80.0, 50.0)));
2956 tree.dispatch_pointer(contact(finger, PointerPhase::Up, Point::new(80.0, 50.0)));
2957
2958 assert_eq!(
2959 tree.hovered(),
2960 Some(a),
2961 "the mouse is still hovering where it was"
2962 );
2963 assert_eq!(churn.get(), 0, "a contact must not write the hover signal");
2964 drop(observer);
2965 }
2966
2967 /// …and the contact is never the hover owner, so it has no hover of its
2968 /// own to report either.
2969 #[test]
2970 fn a_contact_is_never_the_hover_owner() {
2971 let mut tree = WidgetTree::new();
2972 let target = tree.add(FillWidget::new());
2973 tree.layout(SizeProposal::exact(100.0, 100.0));
2974
2975 let finger = contact_id(4);
2976 tree.dispatch_pointer(contact(finger, PointerPhase::Down, Point::new(50.0, 50.0)));
2977 tree.dispatch_pointer(contact(finger, PointerPhase::Move, Point::new(52.0, 50.0)));
2978
2979 assert_eq!(tree.hover_owner(), None, "a finger cannot own hover");
2980 assert_eq!(tree.hovered(), None);
2981 assert_eq!(tree.hovered_for(finger), None);
2982 assert_eq!(
2983 tree.primary_pointer().map(|p| p.id),
2984 Some(finger),
2985 "it is still the primary pointer — primary and hover owner are not the same role"
2986 );
2987 assert_eq!(
2988 tree.pointer_position(finger),
2989 Some(Point::new(52.0, 50.0)),
2990 "and its position is tracked all the same"
2991 );
2992 let _ = target;
2993 }
2994
2995 /// A synthetic pen: a hovering-capable pointer *does* take the role, and
2996 /// the mouse it displaces is told its widget is no longer hovered.
2997 #[test]
2998 fn a_pen_takes_the_hover_owner_role_from_the_mouse() {
2999 let mut tree = WidgetTree::new();
3000 let a = tree.add(FillWidget::new());
3001 let b = tree.add(FillWidget::new());
3002 let _root = tree.add(SideBySide { a, b });
3003 tree.layout(SizeProposal::exact(100.0, 100.0));
3004
3005 tree.dispatch_event(WidgetEvent::pointer_move(Point::new(25.0, 50.0)));
3006 assert_eq!(tree.hovered(), Some(a));
3007
3008 let stylus = contact_id(5);
3009 let mut pen = PointerInfo::touch(stylus, EventTime::ZERO);
3010 pen.kind = teksilo_tokens::PointerKind::Pen(teksilo_tokens::PenKind::Pen);
3011 let mut sample = contact(stylus, PointerPhase::Move, Point::new(75.0, 50.0));
3012 sample.pointer = pen;
3013 tree.dispatch_pointer(sample);
3014
3015 assert_eq!(
3016 tree.hover_owner().map(|p| p.id),
3017 Some(stylus),
3018 "the later hovering sample wins the role"
3019 );
3020 assert_eq!(tree.hovered(), Some(b));
3021 assert_eq!(
3022 tree.hovered_for(PointerId::MOUSE),
3023 None,
3024 "the displaced owner was told to let go"
3025 );
3026 }
3027
3028 /// The tenth simultaneous contact is admitted; the eleventh is refused at
3029 /// the door and produces no event at all.
3030 #[test]
3031 fn the_eleventh_contact_is_dropped_at_the_door() {
3032 use crate::pointer::table::PointerTable;
3033
3034 let presses = Rc::new(std::cell::Cell::new(0usize));
3035 let mut tree = WidgetTree::new();
3036 let counted = {
3037 let presses = presses.clone();
3038 tree.add(FillWidget::new().on_pointer_event(move |event, _ctx| {
3039 if matches!(event, WidgetEvent::PointerDown { .. }) {
3040 presses.set(presses.get() + 1);
3041 }
3042 EventResponse::Ignored
3043 }))
3044 };
3045 tree.layout(SizeProposal::exact(100.0, 100.0));
3046
3047 let ids: Vec<_> = (0..PointerTable::DEFAULT_CAP)
3048 .map(|n| contact_id(100 + n as u64))
3049 .collect();
3050 for &id in &ids {
3051 tree.dispatch_pointer(contact(id, PointerPhase::Down, Point::new(50.0, 50.0)));
3052 }
3053 assert_eq!(presses.get(), PointerTable::DEFAULT_CAP);
3054 assert_eq!(tree.live_pointers().count(), PointerTable::DEFAULT_CAP);
3055
3056 let overflow = contact_id(200);
3057 tree.dispatch_pointer(contact(
3058 overflow,
3059 PointerPhase::Down,
3060 Point::new(50.0, 50.0),
3061 ));
3062 assert_eq!(
3063 presses.get(),
3064 PointerTable::DEFAULT_CAP,
3065 "the eleventh contact must not reach a widget"
3066 );
3067 assert_eq!(tree.captured_by(overflow), None);
3068 assert_eq!(tree.live_pointers().count(), PointerTable::DEFAULT_CAP);
3069 let _ = counted;
3070 }
3071
3072 /// A palm the digitizer flagged never reaches a widget either.
3073 #[test]
3074 fn a_palm_never_reaches_a_widget() {
3075 let presses = Rc::new(std::cell::Cell::new(0usize));
3076 let mut tree = WidgetTree::new();
3077 {
3078 let presses = presses.clone();
3079 tree.add(FillWidget::new().on_pointer_event(move |event, _ctx| {
3080 if matches!(event, WidgetEvent::PointerDown { .. }) {
3081 presses.set(presses.get() + 1);
3082 }
3083 EventResponse::Ignored
3084 }));
3085 }
3086 tree.layout(SizeProposal::exact(100.0, 100.0));
3087
3088 let id = contact_id(300);
3089 let mut sample = contact(id, PointerPhase::Down, Point::new(50.0, 50.0));
3090 sample.pointer.palm = true;
3091 tree.dispatch_pointer(sample);
3092 assert_eq!(presses.get(), 0);
3093 assert_eq!(tree.live_pointers().count(), 0);
3094 }
3095
3096 /// A dispatch reached from inside a dispatch is queued, not run inline:
3097 /// the rest of the outer bubble runs on the state it started with, and the
3098 /// nested dispatch replays afterwards — still before the top-level call
3099 /// returns.
3100 #[test]
3101 fn a_nested_dispatch_is_queued_and_drained_after() {
3102 let log: Rc<RefCell<Vec<&'static str>>> = Rc::new(RefCell::new(Vec::new()));
3103
3104 let mut tree = WidgetTree::new();
3105 let other = {
3106 let log = log.clone();
3107 tree.add(FillWidget::new().on_tap(move |_e, _ctx| {
3108 log.borrow_mut().push("nested");
3109 }))
3110 };
3111 // Two handlers on the child, in the order the bubble runs them:
3112 // `on_pointer_event` (the pre-gesture intercept) queues the nested
3113 // dispatch, `on_tap` is the outer work still to come after it. That
3114 // pair is what makes the ordering below evidence rather than
3115 // coincidence.
3116 let child = {
3117 let log_pointer = log.clone();
3118 let log_tap = log.clone();
3119 tree.add(
3120 FillWidget::new()
3121 .on_pointer_event(move |event, ctx| {
3122 if matches!(event, WidgetEvent::PointerUp { .. }) {
3123 log_pointer.borrow_mut().push("child-press");
3124 // Re-enters the dispatch door from inside a handler.
3125 ctx.synthetic_click(other);
3126 }
3127 EventResponse::Ignored
3128 })
3129 .on_tap(move |_e, _ctx| {
3130 log_tap.borrow_mut().push("child-tap");
3131 }),
3132 )
3133 };
3134 // Keep the two halves disjoint, so the synthetic click lands on
3135 // `other` and not back on `child` (which would re-enter for ever).
3136 let _root = tree.add(SideBySide { a: child, b: other });
3137 tree.layout(SizeProposal::exact(100.0, 100.0));
3138
3139 let at = tree.bounds(child).center();
3140 tree.dispatch_event(WidgetEvent::pointer_down(
3141 at,
3142 PointerButton::Primary,
3143 Modifiers::NONE,
3144 ));
3145 tree.dispatch_event(WidgetEvent::pointer_up(
3146 at,
3147 PointerButton::Primary,
3148 Modifiers::NONE,
3149 ));
3150
3151 assert_eq!(
3152 *log.borrow(),
3153 vec!["child-press", "child-tap", "nested"],
3154 "the outer dispatch must finish on the state it started with, and the \
3155 nested dispatch replay only once it has — run inline it would read \
3156 child-press, nested, child-tap"
3157 );
3158 assert!(
3159 !tree.has_pending_dispatch(),
3160 "the queue must be empty again before the top-level call returns"
3161 );
3162 }
3163
3164 /// Localisation reads the captor's **current** bounds on every event, so a
3165 /// captured control inside a container that moves keeps reporting sensible
3166 /// widget-local coordinates rather than coordinates relative to where it
3167 /// used to be.
3168 #[test]
3169 fn a_captured_widget_localises_against_its_moving_bounds() {
3170 let seen: Rc<RefCell<Vec<Point>>> = Rc::new(RefCell::new(Vec::new()));
3171 let mut tree = WidgetTree::new();
3172 let knob = {
3173 let seen = seen.clone();
3174 tree.add(FillWidget::new().on_pointer_event(move |event, ctx| {
3175 match event {
3176 WidgetEvent::PointerDown { .. } => ctx.capture_pointer(),
3177 WidgetEvent::PointerMove { position, .. } => seen.borrow_mut().push(*position),
3178 _ => {}
3179 }
3180 EventResponse::Ignored
3181 }))
3182 };
3183 let offset = crate::signal::Signal::new(0.0f32);
3184 let _root = tree.add(ShiftedSlot {
3185 child: knob,
3186 offset: offset.clone(),
3187 });
3188 tree.layout(SizeProposal::exact(100.0, 100.0));
3189
3190 tree.dispatch_event(WidgetEvent::pointer_down(
3191 Point::new(30.0, 40.0),
3192 PointerButton::Primary,
3193 Modifiers::NONE,
3194 ));
3195 assert_eq!(tree.pointer_captured_by(), Some(knob));
3196 tree.dispatch_event(WidgetEvent::pointer_move(Point::new(30.0, 40.0)));
3197
3198 // The container slides its child 20 dp to the trailing side.
3199 offset.set(20.0);
3200 tree.arena.mark_all_dirty();
3201 tree.layout(SizeProposal::exact(100.0, 100.0));
3202
3203 tree.dispatch_event(WidgetEvent::pointer_move(Point::new(30.0, 40.0)));
3204
3205 assert_eq!(
3206 *seen.borrow(),
3207 vec![Point::new(30.0, 40.0), Point::new(10.0, 40.0)],
3208 "the same window position must localise against the captor's new origin"
3209 );
3210 }
3211
3212 /// The localisation contract is **deliberately asymmetric**, and this pins
3213 /// the asymmetry so nobody "fixes" it into a defect.
3214 ///
3215 /// `localize_event` rewrites `PointerDown` / `PointerUp` / `PointerMove` /
3216 /// `Gesture` into the receiver's own space, and has no arm for `Scroll` or
3217 /// `PointerCancel`. That is why those two name their position
3218 /// `window_position`: the router routes by the first (hit-testing is
3219 /// necessarily window-space), and `common/scrollable.rs` feeds it to
3220 /// `KineticScroller::pan`, whose tracker follows the *pointer* — and since
3221 /// localisation resolves against the captor's **current** bounds on every
3222 /// event (the test above), a localised value would fold the measured
3223 /// widget's own motion into the velocity.
3224 ///
3225 /// Two independent things keep it that way, and the two assertions below
3226 /// answer for one each — which is why both are here rather than one
3227 /// standing in for the other:
3228 ///
3229 /// * **`Scroll`** reaches its handler through the localising route
3230 /// (`dispatch_to_widget` → `localize_event`), so the missing arm is the
3231 /// whole of its protection. Adding one reads like a tidy-up; the scroll
3232 /// assertion is what goes red.
3233 /// * **`PointerCancel`** is delivered by the cancel funnel through
3234 /// `dispatch_to_widget_direct`, which does not localise at all, so an arm
3235 /// added to `localize_event` would be inert on that path. What guards it
3236 /// is that `pointer_cancel_event` records the pointer table's own
3237 /// (window-space) position verbatim; localising it at the funnel, which
3238 /// knows the recipient and could, is the single change the cancel
3239 /// assertion catches.
3240 #[test]
3241 fn scroll_and_cancel_stay_in_window_space_while_a_press_is_localised() {
3242 #[derive(Default)]
3243 struct Seen {
3244 press: Vec<Point>,
3245 scroll: Vec<Option<Point>>,
3246 cancel: Vec<Option<Point>>,
3247 }
3248 let seen: Rc<RefCell<Seen>> = Rc::new(RefCell::new(Seen::default()));
3249 let mut tree = WidgetTree::new();
3250 let target = {
3251 let a = seen.clone();
3252 let b = seen.clone();
3253 tree.add(
3254 FillWidget::new()
3255 .on_pointer_event(move |event, ctx| {
3256 match event {
3257 WidgetEvent::PointerDown { position, .. } => {
3258 a.borrow_mut().press.push(*position);
3259 // Hold the pointer so the cancel funnel has
3260 // someone to address.
3261 ctx.capture_pointer();
3262 }
3263 WidgetEvent::PointerCancel {
3264 window_position, ..
3265 } => a.borrow_mut().cancel.push(*window_position),
3266 _ => {}
3267 }
3268 EventResponse::Ignored
3269 })
3270 .on_scroll(move |event, _ctx| {
3271 if let WidgetEvent::Scroll {
3272 window_position, ..
3273 } = event
3274 {
3275 b.borrow_mut().scroll.push(*window_position);
3276 }
3277 EventResponse::Ignored
3278 }),
3279 )
3280 };
3281 // The slot puts its child 20 dp along, so window x and local x differ by
3282 // exactly 20 and a localised value is distinguishable from a raw one.
3283 let _root = tree.add(ShiftedSlot {
3284 child: target,
3285 offset: crate::signal::Signal::new(20.0f32),
3286 });
3287 tree.layout(SizeProposal::exact(100.0, 100.0));
3288
3289 let at = Point::new(30.0, 40.0);
3290 tree.dispatch_event(WidgetEvent::pointer_down(
3291 at,
3292 PointerButton::Primary,
3293 Modifiers::NONE,
3294 ));
3295 tree.dispatch_event(WidgetEvent::Scroll {
3296 delta: crate::event::ScrollDelta::Lines { x: 0.0, y: 1.0 },
3297 modifiers: Modifiers::NONE,
3298 window_position: Some(at),
3299 phase: crate::pointer::ScrollPhase::Discrete,
3300 pointer: crate::pointer::PointerInfo::mouse(crate::pointer::EventTime::ZERO),
3301 });
3302 let captor = tree.pointer_captured_by();
3303 assert_eq!(
3304 captor,
3305 Some(target),
3306 "the press must have taken the capture"
3307 );
3308 let pointer = tree.pointers.primary_id().expect("a live pointer");
3309 tree.cancel_pointer(
3310 pointer,
3311 crate::pointer::CancelReason::Platform,
3312 &mut crate::window::NoopWindowOps,
3313 );
3314
3315 let seen = seen.borrow();
3316 assert_eq!(
3317 seen.press,
3318 vec![Point::new(10.0, 40.0)],
3319 "a press is localised: window x 30 minus the slot's 20 dp offset"
3320 );
3321 assert_eq!(
3322 seen.scroll,
3323 vec![Some(at)],
3324 "`Scroll::window_position` must arrive as produced: localising it would feed \
3325 the kinetic tracker a frame that moves with the widget it measures"
3326 );
3327 assert_eq!(
3328 seen.cancel,
3329 vec![Some(at)],
3330 "`PointerCancel::window_position` must arrive as the revoking path recorded \
3331 it, for the same reason"
3332 );
3333 }
3334
3335 // --- fixtures --------------------------------------------------------
3336
3337 /// Splits its bounds down the middle: `a` on the leading half, `b` on the
3338 /// trailing one, so two pointers can land on two different widgets.
3339 #[derive(Debug)]
3340 struct SideBySide {
3341 a: WidgetId,
3342 b: WidgetId,
3343 }
3344
3345 impl crate::widget::Widget for SideBySide {
3346 fn layout_response(
3347 &self,
3348 proposal: SizeProposal,
3349 _ctx: &crate::widget::LayoutContext,
3350 ) -> crate::widget::LayoutResponse {
3351 proposal.resolve(0.0, 0.0).into()
3352 }
3353 fn place_children(
3354 &self,
3355 bounds: Rect,
3356 _proposal: SizeProposal,
3357 children: &mut [crate::widget::WidgetPlacement],
3358 _ctx: &crate::widget::LayoutContext,
3359 ) {
3360 let half = bounds.width / 2.0;
3361 for (index, c) in children.iter_mut().enumerate() {
3362 c.origin = Point::new(bounds.x + half * index as f32, bounds.y);
3363 c.size = teksilo_canvas::Size::new(half, bounds.height);
3364 }
3365 }
3366 fn children(&self) -> Vec<WidgetId> {
3367 vec![self.a, self.b]
3368 }
3369 }
3370
3371 /// Places its single child at a signal-driven horizontal offset, so a test
3372 /// can move a captured widget between two pointer samples.
3373 #[derive(Debug)]
3374 struct ShiftedSlot {
3375 child: WidgetId,
3376 offset: crate::signal::Signal<f32>,
3377 }
3378
3379 impl crate::widget::Widget for ShiftedSlot {
3380 fn layout_response(
3381 &self,
3382 proposal: SizeProposal,
3383 _ctx: &crate::widget::LayoutContext,
3384 ) -> crate::widget::LayoutResponse {
3385 proposal.resolve(0.0, 0.0).into()
3386 }
3387 fn place_children(
3388 &self,
3389 bounds: Rect,
3390 _proposal: SizeProposal,
3391 children: &mut [crate::widget::WidgetPlacement],
3392 _ctx: &crate::widget::LayoutContext,
3393 ) {
3394 for c in children.iter_mut() {
3395 c.origin = Point::new(bounds.x + self.offset.get(), bounds.y);
3396 c.size = bounds.size();
3397 }
3398 }
3399 fn children(&self) -> Vec<WidgetId> {
3400 vec![self.child]
3401 }
3402 }
3403}
3404
3405/// The arbitration binds the **timer** path, not only the sample path.
3406#[cfg(test)]
3407mod tick_arbitration_tests {
3408 use super::*;
3409 use crate::event::EventResponse;
3410 use crate::test_widgets::{FillWidget, StackWidget};
3411 use crate::widget_builder::WidgetBuilder;
3412 use std::cell::Cell;
3413 use std::rc::Rc;
3414 use std::time::Duration;
3415
3416 /// A tree whose innermost child holds the sequence on its press, under an
3417 /// ancestor that competes for the same press (`on_drag` is what enrols it)
3418 /// and also carries a long-press recognizer.
3419 ///
3420 /// `max_hold` is raised past `long_press` so the hold is still standing
3421 /// when the ancestor's timer comes due; with the shipped 250 ms hold and
3422 /// 500 ms long press the hold always expires first and the two never
3423 /// overlap, so there would be nothing to observe.
3424 fn tree_with_a_holder_under_a_long_pressing_peer(
3425 hold_on_press: bool,
3426 ) -> (WidgetTree, Rc<Cell<bool>>) {
3427 let long_pressed = Rc::new(Cell::new(false));
3428 let flag = long_pressed.clone();
3429
3430 let mut tree = WidgetTree::new();
3431 let mut theme = tree.theme().clone();
3432 theme.input.gestures.mouse.max_hold = Duration::from_millis(2000);
3433 tree.set_theme(theme);
3434
3435 let child = tree.add(FillWidget::new().on_pointer_event(move |event, ctx| {
3436 if hold_on_press && matches!(event, WidgetEvent::PointerDown { .. }) {
3437 ctx.hold_gesture();
3438 }
3439 EventResponse::Ignored
3440 }));
3441 tree.add(
3442 StackWidget::new()
3443 .child(child)
3444 .on_drag(|_phase, _c| {})
3445 .on_long_press(move |_e, _c| flag.set(true)),
3446 );
3447 tree.layout(SizeProposal::exact(300.0, 50.0));
3448 (tree, long_pressed)
3449 }
3450
3451 /// The control: with nothing holding, the peer's long press does fire on
3452 /// the tick. Without this the test below would pass on a fixture that
3453 /// could never long-press at all.
3454 #[test]
3455 fn a_peers_long_press_fires_on_the_tick_when_nothing_holds() {
3456 let (mut tree, long_pressed) = tree_with_a_holder_under_a_long_pressing_peer(false);
3457 tree.pointer_down_button(Point::new(20.0, 25.0), PointerButton::Primary);
3458 tree.advance_time(Duration::from_millis(600));
3459 assert!(
3460 long_pressed.get(),
3461 "the ancestor is a member with a long-press recognizer and its \
3462 timer came due"
3463 );
3464 }
3465
3466 /// …and it does not while a peer is holding.
3467 ///
3468 /// `hold_gesture` freezes the arbitration: no other member may win while a
3469 /// member is still deciding. The sample path has always honoured that
3470 /// (`sequence_blocks_arena`); the timer path dispatched whatever a
3471 /// recognizer produced, so a long press whose deadline happened to fall
3472 /// inside a hold fired anyway — which is the same recognizer winning, one
3473 /// door over.
3474 #[test]
3475 fn a_peers_long_press_does_not_fire_on_the_tick_while_a_member_holds() {
3476 let (mut tree, long_pressed) = tree_with_a_holder_under_a_long_pressing_peer(true);
3477 tree.pointer_down_button(Point::new(20.0, 25.0), PointerButton::Primary);
3478 assert!(
3479 tree.sequence_members(crate::pointer::PointerId::MOUSE)
3480 .iter()
3481 .any(|(_, _, state)| *state == crate::gesture::MemberState::Held),
3482 "the fixture must actually be holding"
3483 );
3484
3485 tree.advance_time(Duration::from_millis(600));
3486 assert!(
3487 !long_pressed.get(),
3488 "no peer may win while a member is holding — the timer path is not \
3489 a way around the arbitration"
3490 );
3491 }
3492}