Skip to main content

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