Skip to main content

teksilo_core/widget_tree/
pointer_router.rs

1// SPDX-License-Identifier: MPL-2.0
2// SPDX-FileCopyrightText: 2026 FernTech
3
4//! Pointer, keyboard and accessibility event routing: the dispatch
5//! pipeline, hit-testing, the preview/bubble handler passes and the
6//! context-menu entry points.
7
8use super::*;
9
10use crate::event::ButtonMask;
11use crate::gesture::{GestureEvent, RawPointerEvent, TapEvent};
12
13/// Fire an `EventResponse`-returning handler from BOTH the external
14/// and own slots (in that order). Returns `Handled` if either did,
15/// `Ignored` otherwise. `None` slots are skipped.
16fn fire_event_handler_both(
17    external: &mut Option<Box<dyn FnMut(&WidgetEvent, &mut EventContext) -> EventResponse>>,
18    own: &mut Option<Box<dyn FnMut(&WidgetEvent, &mut EventContext) -> EventResponse>>,
19    event: &WidgetEvent,
20    ctx: &mut EventContext,
21) -> EventResponse {
22    let r1 = external
23        .as_mut()
24        .map(|h| h(event, ctx))
25        .unwrap_or(EventResponse::Ignored);
26    let r2 = own
27        .as_mut()
28        .map(|h| h(event, ctx))
29        .unwrap_or(EventResponse::Ignored);
30    if r1 == EventResponse::Handled || r2 == EventResponse::Handled {
31        EventResponse::Handled
32    } else {
33        EventResponse::Ignored
34    }
35}
36
37/// A dispatch deferred because another was in flight.
38///
39/// Carries everything needed to replay it faithfully: the event, and the input
40/// snapshot that says which pointer produced it. `ops` is not carried — the
41/// drain runs inside the same top-level call, so the caller's sink is still in
42/// hand.
43pub(super) enum QueuedDispatch {
44    /// A nested `dispatch_*` call, replayed verbatim — event *and* input
45    /// snapshot — once the outer sample completes.
46    ///
47    /// The snapshot is boxed: it carries the packet's coalesced positions, so
48    /// it is by some way the largest thing either variant holds, and a queue
49    /// entry that is mostly padding would be paid for on the cancel path too.
50    Event {
51        event: WidgetEvent,
52        snapshot: Box<crate::pointer::InputSnapshot>,
53    },
54    /// A revocation raised through
55    /// [`WidgetTree::cancel_pointer`](crate::WidgetTree::cancel_pointer).
56    ///
57    /// It rides this queue rather than one of its own so that a cancel and the
58    /// dispatch that provoked it cannot be reordered relative to each other:
59    /// one queue is one order. It carries the reason rather than a
60    /// pre-built `PointerCancel`, because the event's position and
61    /// `PointerInfo` must be read from the table at *drain* time — by then the
62    /// pointer may have moved, or ceased to exist, and a snapshot taken at
63    /// queue time would describe a state the widget is no longer in.
64    Cancel {
65        pointer: crate::pointer::PointerId,
66        reason: crate::pointer::CancelReason,
67        /// Who to tell, when the producer knows better than the table does.
68        ///
69        /// The funnel normally addresses the cancel to whoever holds the
70        /// capture. A producer that has *already* taken the capture back as
71        /// part of its own teardown — the OS-drag escalation hands the pointer
72        /// to the platform before it raises the cancel — would leave the
73        /// funnel with nobody to tell, so it names the widget itself.
74        recipient: Option<WidgetId>,
75    },
76}
77
78/// The window-logical position a pointer event happened at, if it carries one.
79///
80/// The pointer table is fed from here: every event with a position refreshes
81/// its pointer's entry, and everything else (keys, IME, focus, AT actions)
82/// leaves the table alone.
83fn pointer_event_position(event: &WidgetEvent) -> Option<Point> {
84    match event {
85        WidgetEvent::PointerDown { position, .. }
86        | WidgetEvent::PointerUp { position, .. }
87        | WidgetEvent::PointerMove { position, .. } => Some(*position),
88        // Deliberately not `PointerCancel`. A revocation must never *create*
89        // a pointer: admitting one here would resurrect a contact the funnel
90        // is in the middle of forgetting, and leave its entry behind for good.
91        _ => None,
92    }
93}
94
95/// What the bubble pass is allowed to run on one node.
96///
97/// Two independent gates, kept together because they answer the same
98/// question — "how much of this node takes part in *this* dispatch".
99#[derive(Copy, Clone)]
100struct BubbleGates {
101    /// Gates the pre-gesture `on_pointer_event` intercept. `true` for the
102    /// bubble target (the widget the event was dispatched at) and `false`
103    /// for every ancestor, because ancestors already fired their
104    /// `on_pointer_event` during the preview pass — firing it again in
105    /// bubble was the source of double-toggle / double-select bugs when a
106    /// wrapper widget (e.g. `ListItemWrapper`) held the handler and a child
107    /// leaf was the hit target.
108    fire_on_pointer_event: bool,
109    /// This node lost the pointer's arbitration, so its **recognizers** stay
110    /// out of the event and it bubbles on as if it carried none. Its own
111    /// handlers still run: losing an arbitration is not the same as being
112    /// removed from the tree. See `WidgetTree::sequence_blocks_arena`.
113    arena_blocked: bool,
114}
115
116impl WidgetTree {
117    /// Hops from `focus` up to `scope_id` (0 when equal), or `None` when
118    /// `scope_id` is not an ancestor-or-self of `focus`. Fewer hops means
119    /// the scope sits closer to focus, i.e. a more specific binding.
120    ///
121    /// Up the widget's own parents only: an overlay's content is not inside
122    /// the scopes of the widget the overlay is attached to, as a key pressed
123    /// in a Qt popup (a window of its own) or in a GTK popover (whose entry
124    /// hears it first) does not reach the shortcuts of the widget below. A
125    /// list's scoped Delete must not fire from the field of a rename popover
126    /// attached to one of its rows. An intent still crosses; see
127    /// [`intent_walk`](Self::intent_walk).
128    fn scope_distance_from_focus(&self, focus: WidgetId, scope_id: WidgetId) -> Option<usize> {
129        let mut hops = 0usize;
130        let mut current = Some(focus);
131        while let Some(id) = current {
132            if id == scope_id {
133                return Some(hops);
134            }
135            current = self.arena.parent(id);
136            hops += 1;
137        }
138        None
139    }
140
141    /// Where a key's shortcut is judged from, and a command sent from focus
142    /// starts: the focused widget, or, with nothing focused while a modal
143    /// overlay is open, the topmost modal's content, as if focus were in it.
144    /// A dialog that holds no focus is still in front of the page, whose
145    /// commands stay out of it as they do with focus inside.
146    pub(crate) fn focus_or_modal(&self) -> Option<WidgetId> {
147        self.focused
148            .filter(|id| self.arena.is_active(*id))
149            .or_else(|| {
150                self.overlay_manager
151                    .topmost_modal()
152                    .map(|overlay| overlay.content_id)
153            })
154    }
155
156    /// From every same-chord shortcut candidate, choose the one whose
157    /// scope applies to the current focus (for a global one, see
158    /// [`global_applies`](Self::global_applies)), preferring the most specific
159    /// scope: a `Scoped` binding whose subtree contains focus beats a
160    /// `Global` one, and among nested applicable scopes the one closest
161    /// to focus (fewest hops) wins. Equal-specificity ties keep the
162    /// deterministic `(category, id)` order `candidates` arrives in (the
163    /// first such candidate wins). Returns `None` when no candidate
164    /// applies — every match is a scoped binding outside the focused
165    /// subtree — so the caller falls through to normal KeyDown dispatch.
166    fn select_shortcut_for_focus(
167        &self,
168        candidates: &[(&'static str, crate::shortcut::ShortcutScope, bool)],
169    ) -> Option<(&'static str, crate::shortcut::ShortcutScope, bool)> {
170        use crate::shortcut::ShortcutScope;
171        let mut best: Option<(usize, (&'static str, ShortcutScope, bool))> = None;
172        // With focus in a modal, a global shortcut applies only when one of
173        // the widgets that registered it is inside that modal, when none did,
174        // or when it is one of the tree's own (the standard edit shortcuts),
175        // whoever re-registered it: a native modal window has its own
176        // widgets' shortcuts and not those of the window it blocks. An app
177        // may re-register a standard edit to rename it, and every text widget
178        // answers those from the focused widget's route, which a modal must
179        // not cut off. With nothing focused, judged from the topmost modal.
180        let focus = self.focus_or_modal();
181        let modal = focus.and_then(|f| self.intent_walk(f, &[]).2);
182        for &(id, scope, propagate) in candidates {
183            // Specificity score, higher = more specific. Global is the
184            // least-specific fallback (0); any applicable scoped binding
185            // outranks it (`usize::MAX - hops`, so fewer hops = deeper
186            // scope = higher score). Tree depth is tiny, so no overflow.
187            let score = match scope {
188                ShortcutScope::Global => (crate::shortcut::is_framework_shortcut_id(id) || {
189                    let owners = self.shortcut_registry.owners(id);
190                    owners.is_empty()
191                        || owners
192                            .iter()
193                            .any(|&owner| self.global_applies(owner, modal))
194                })
195                .then_some(0usize),
196                ShortcutScope::Scoped(scope_id) => focus
197                    .and_then(|f| self.scope_distance_from_focus(f, scope_id))
198                    .map(|hops| usize::MAX - hops),
199            };
200            let Some(score) = score else { continue };
201            // Strictly-greater keeps the first candidate on a tie, so the
202            // existing `(category, id)` precedence holds within a scope.
203            if best.as_ref().is_none_or(|(b, _)| score > *b) {
204                best = Some((score, (id, scope, propagate)));
205            }
206        }
207        best.map(|(_, c)| c)
208    }
209
210    /// Dispatch an event into the widget tree.
211    ///
212    /// Routing rules:
213    /// - Pointer events -> hit testing against layout tree
214    /// - Keyboard/IME events -> focused widget
215    /// - AccessKit actions -> target widget directly
216    /// - Scroll events -> hit testing (scroll target under pointer)
217    ///
218    /// Dispatch an event with the caller-supplied app-level
219    /// [`WindowOps`](crate::window::WindowOps) sink. `teksilo-app` calls
220    /// this variant; handlers can reach the multi-window API
221    /// synchronously (`open_window` creates the winit window inside
222    /// the same call before returning).
223    pub fn dispatch_event_with_ops(
224        &mut self,
225        event: WidgetEvent,
226        ops: &mut dyn crate::window::WindowOps,
227    ) {
228        // A legacy event names no pointer, so it is the mouse at the epoch —
229        // which is exactly what it has always meant.
230        let mut snapshot = crate::pointer::InputSnapshot::from_event(&event);
231        // A legacy `WidgetEvent` carries no timestamp of its own, so stamp it
232        // from the tree clock. Without this the gesture layer would see every
233        // hand-built event at the epoch and no interval — a double tap, a long
234        // press and a swipe would all be undecidable.
235        if snapshot.pointer.time == crate::pointer::EventTime::ZERO {
236            snapshot.pointer.time = self.input_now();
237        }
238        self.dispatch_with_input_snapshot(event, snapshot, ops)
239    }
240
241    /// Dispatch an event on a standalone tree (tests, headless
242    /// scenarios). Handler code that calls `ctx.open_window(...)`
243    /// from within this dispatch will panic — by design. See
244    /// [`dispatch_event_with_ops`](Self::dispatch_event_with_ops)
245    /// for the app-facing variant.
246    pub fn dispatch_event(&mut self, event: WidgetEvent) {
247        let mut noop = crate::window::NoopWindowOps;
248        self.dispatch_event_with_ops(event, &mut noop);
249    }
250
251    // The three ingress doors
252
253    /// Deliver one pointer sample.
254    ///
255    /// This and [`dispatch_scroll`](Self::dispatch_scroll) are the real input
256    /// doors: a backend produces [`PointerSample`](crate::pointer::PointerSample)s
257    /// and [`ScrollSample`](crate::pointer::ScrollSample)s, and everything
258    /// Teksilo knows about *who* is pointing — identity, kind, pressure,
259    /// timestamp, coalesced history — reaches the tree through them.
260    ///
261    /// For now a sample is **lowered** onto the legacy `WidgetEvent` it
262    /// describes and takes the existing route, so a mouse behaves bit for bit
263    /// as it did before the doors existed. What changes here is only that the
264    /// door exists and that the sample's
265    /// [`PointerInfo`](crate::pointer::PointerInfo) is visible to handlers
266    /// through [`EventContext::pointer`](crate::widget::EventContext::pointer).
267    ///
268    /// A `Down` and an `Up` sample at the same point form a tap, whatever
269    /// timestamps a test gives them. For a whole gesture in one call a test
270    /// has [`click`](Self::click) (the centre of a widget) and
271    /// [`tap_with`](Self::tap_with) (a point, for any pointer kind).
272    pub fn dispatch_pointer(&mut self, sample: crate::pointer::PointerSample) {
273        let mut noop = crate::window::NoopWindowOps;
274        self.dispatch_pointer_with_ops(sample, &mut noop);
275    }
276
277    /// [`dispatch_pointer`](Self::dispatch_pointer) with the caller's
278    /// app-level [`WindowOps`](crate::window::WindowOps) sink, so handlers can
279    /// reach the multi-window API synchronously.
280    pub fn dispatch_pointer_with_ops(
281        &mut self,
282        sample: crate::pointer::PointerSample,
283        ops: &mut dyn crate::window::WindowOps,
284    ) {
285        use crate::pointer::PointerPhase;
286
287        crate::trace_input!(
288            Samples,
289            "{:?} {:?} at {:?} buttons={:?} t={:?}",
290            sample.phase,
291            sample.pointer.id,
292            sample.position,
293            sample.pointer.buttons,
294            sample.pointer.time
295        );
296
297        // The button a Down/Up is *about*. A direct-pointer contact reports no
298        // button at all, and the widget layer has always been told
299        // `Primary` for a press — that is what a tap is.
300        let button = sample
301            .button
302            .unwrap_or(crate::event::PointerButton::Primary);
303        let event = match sample.phase {
304            PointerPhase::Down => WidgetEvent::PointerDown {
305                position: sample.position,
306                button,
307                modifiers: sample.modifiers,
308                pointer: sample.pointer,
309            },
310            PointerPhase::Move => WidgetEvent::PointerMove {
311                position: sample.position,
312                modifiers: sample.modifiers,
313                pointer: sample.pointer,
314            },
315            PointerPhase::Up => WidgetEvent::PointerUp {
316                position: sample.position,
317                button,
318                modifiers: sample.modifiers,
319                pointer: sample.pointer,
320            },
321            // The platform revoked the contact (a `wl_touch.cancel`, a
322            // `WM_POINTERCAPTURECHANGED`, a compositor grab). It takes the
323            // cancel funnel directly rather than being lowered onto an event:
324            // the funnel owns the teardown order, and lowering would first
325            // *admit* the pointer the sample is revoking.
326            PointerPhase::Cancel => {
327                // The dismissal this contact had armed goes with it. The funnel
328                // below returns early for a pointer with nothing revocable, and
329                // a suppressed arming `Down` leaves exactly that shape — no
330                // sequence, no capture — so the abort cannot ride on it.
331                self.overlay_manager.abort_dismiss(sample.pointer.id);
332                self.cancel_pointer(
333                    sample.pointer.id,
334                    crate::pointer::CancelReason::Platform,
335                    ops,
336                );
337                // A revoked contact ceases to exist, exactly as a lifted one
338                // does — the `ends_pointer` rule below, which this arm returns
339                // before reaching. The funnel ends the entry itself *when it
340                // runs*; for a pointer that had no press to revoke it returns
341                // first, and the entry would outlive the finger. Idempotent, so
342                // the ordinary path is unaffected.
343                if !sample.pointer.kind.hovers() {
344                    self.pointers.end(sample.pointer.id);
345                }
346                return;
347            }
348        };
349
350        // Admit the pointer before anything is dispatched. A palm, or an
351        // eleventh simultaneous contact, is refused here and produces no event
352        // at all — the alternative (evicting a live contact to make room) turns
353        // a pinch into a fling, and letting a resting palm through turns a hand
354        // on a tablet into a stream of taps.
355        if !self.pointers.would_admit(&sample.pointer) {
356            return;
357        }
358        // A contact ceases to exist when it lifts; a hovering-capable pointer
359        // does not — a mouse that releases a button is still there, still
360        // hovering, and its entry is what every legacy singular accessor reads.
361        let ends_pointer = matches!(sample.phase, PointerPhase::Up | PointerPhase::Cancel)
362            && !sample.pointer.kind.hovers();
363        let pointer_id = sample.pointer.id;
364
365        let snapshot = crate::pointer::InputSnapshot::from_pointer_sample(&sample);
366        self.dispatch_with_input_snapshot(event, snapshot, ops);
367
368        if ends_pointer {
369            self.pointers.end(pointer_id);
370        }
371    }
372
373    /// Deliver one scroll sample.
374    ///
375    /// Routing follows [`ScrollSample::position`](crate::pointer::ScrollSample::position):
376    /// `Some` hit-tests it, `None` falls back to the hovered (else focused)
377    /// widget, which is what every scroll did before. A mouse wheel carries no
378    /// position, so this is a no-op for a mouse; a pan synthesised from a
379    /// direct pointer must carry one, because a contact never writes hover.
380    pub fn dispatch_scroll(&mut self, sample: crate::pointer::ScrollSample) {
381        let mut noop = crate::window::NoopWindowOps;
382        self.dispatch_scroll_with_ops(sample, &mut noop);
383    }
384
385    /// [`dispatch_scroll`](Self::dispatch_scroll) with the caller's app-level
386    /// [`WindowOps`](crate::window::WindowOps) sink.
387    pub fn dispatch_scroll_with_ops(
388        &mut self,
389        sample: crate::pointer::ScrollSample,
390        ops: &mut dyn crate::window::WindowOps,
391    ) {
392        crate::trace_input!(
393            Samples,
394            "scroll {:?} {:?}/{:?} at {:?}",
395            sample.delta,
396            sample.phase,
397            sample.source,
398            sample.position
399        );
400
401        let event = WidgetEvent::Scroll {
402            delta: sample.delta,
403            modifiers: sample.modifiers,
404            window_position: sample.position,
405            phase: sample.phase,
406            pointer: sample.pointer,
407        };
408        let snapshot = crate::pointer::InputSnapshot::from_scroll_sample(&sample);
409        self.dispatch_with_input_snapshot(event, snapshot, ops);
410    }
411
412    /// The pointer left the window.
413    ///
414    /// The third ingress door, and the only one that carries no sample: the OS
415    /// says the cursor crossed the window boundary and nothing else. It exists
416    /// because hover is otherwise cleared *only* by a move that lands
417    /// elsewhere — so a mouse that leaves through an edge would leave the last
418    /// widget hovered for as long as it stays away, with its hover chrome
419    /// painted, its `hover_within` signal true and its tooltip still counting
420    /// down.
421    ///
422    /// Clears hover the way a move to an empty spot does: a `PointerLeave` to
423    /// the hovered widget, the tooltip dwell cancelled, the `hover_within`
424    /// chain updated. It touches nothing else — no pointer is cancelled, no
425    /// capture released, no table entry ended. A mouse that leaves the window
426    /// is still a mouse, and a *captured* pointer is deliberately exempt: a
427    /// drag whose pointer wanders off the window keeps its target, which is
428    /// what makes a drag past the edge (and the OS-drag escalation built on
429    /// it) work at all.
430    ///
431    /// There is no matching `pointer_entered_window`, and that is not an
432    /// omission: the enter carries no position either, and a position only
433    /// ever arrives with a `CursorMoved` — which re-arms hover through the
434    /// ordinary path. A door that could only say "somewhere" would have
435    /// nothing to hit-test.
436    pub fn pointer_left_window(&mut self, ops: &mut dyn crate::window::WindowOps) {
437        // The pointer that owns hover is the one that just left; if it holds a
438        // capture, the interaction it is in the middle of outranks the
439        // boundary crossing.
440        if self
441            .pointers
442            .hover_owner_id()
443            .and_then(|id| self.captured_by(id))
444            .is_some()
445        {
446            return;
447        }
448        self.hover_owner_outside_window = true;
449        self.tooltip_dwell_held = false;
450        let Some(hovered) = self.hovered_id() else {
451            return;
452        };
453        // The hover owner is the pointer that just left — read from the table
454        // because this door carries no sample of its own.
455        let leave = WidgetEvent::PointerLeave {
456            pointer: self.hover_transition_pointer(),
457        };
458        self.dispatch_to_widget(hovered, &leave, &mut *ops);
459        self.tooltip_pointer_leave(hovered, &mut *ops);
460        self.set_hovered(None);
461        self.update_hover_within_signals(Some(hovered), None);
462    }
463
464    /// The pointer a hover transition is credited to.
465    ///
466    /// [`PointerEnter`](WidgetEvent::PointerEnter) /
467    /// [`PointerLeave`](WidgetEvent::PointerLeave) are hover-owner events by
468    /// construction — a contact never writes hover — so the answer is the hover
469    /// owner's own [`PointerInfo`](crate::pointer::PointerInfo), read from the
470    /// table rather than from the in-flight sample: a transition can be raised
471    /// by something that is not a pointer sample at all (a relayout that moves
472    /// a widget out from under the cursor, the window-leave door), and a
473    /// hover-incapable pointer must never be credited with hover.
474    ///
475    /// Falls back to a mouse at the current tree time when the table has no
476    /// hover owner, which is the state a synthesized `dispatch_event` leaves it
477    /// in. Either way this is the tree's own view rather than a producer's — see
478    /// the rule stated on
479    /// [`handle_pointer_move`](Self::handle_pointer_move).
480    pub(super) fn hover_transition_pointer(&self) -> crate::pointer::PointerInfo {
481        self.pointers
482            .hover_owner()
483            .map(|entry| entry.info)
484            .unwrap_or_else(|| crate::pointer::PointerInfo::mouse(self.input_now()))
485    }
486
487    /// Run one dispatch with `snapshot` installed as the tree's view of the
488    /// in-flight sample, restoring the previous value afterwards.
489    ///
490    /// Save-and-restore rather than reset-to-default so a nested dispatch (a
491    /// synthetic click queued by a handler, a scroll-into-view walk) leaves the
492    /// outer sample's snapshot intact for the rest of the outer dispatch.
493    fn dispatch_with_input_snapshot(
494        &mut self,
495        event: WidgetEvent,
496        snapshot: crate::pointer::InputSnapshot,
497        ops: &mut dyn crate::window::WindowOps,
498    ) {
499        // A dispatch reached from inside a dispatch — a handler's synthetic
500        // click, an assistive-technology action re-entering the door — is
501        // **queued**, not run inline. Running it inline would let it unwind the
502        // pointer state the outer sample is still standing on: the outer
503        // handler would return to a tree whose hover, capture and table entries
504        // had all moved under it. Queued, the outer dispatch finishes on the
505        // state it started with and the nested one replays immediately
506        // afterwards, so from a caller's side nothing changed — the queue is
507        // empty again before the top-level call returns.
508        self.pending_dispatch.push_back(QueuedDispatch::Event {
509            event,
510            snapshot: Box::new(snapshot),
511        });
512        if self.dispatch_depth > 0 {
513            return;
514        }
515        self.drain_pending_dispatch(&mut *ops);
516    }
517
518    /// Run everything the queue holds, in order, each at depth zero.
519    ///
520    /// `pop_front` in a loop rather than `drain`: a replayed dispatch — or a
521    /// cancel's own `PointerCancel` handler — may queue another entry, and
522    /// each must in turn run at depth zero.
523    pub(super) fn drain_pending_dispatch(&mut self, ops: &mut dyn crate::window::WindowOps) {
524        while let Some(queued) = self.pending_dispatch.pop_front() {
525            match queued {
526                QueuedDispatch::Event { event, snapshot } => {
527                    self.run_one_dispatch(event, *snapshot, &mut *ops);
528                }
529                QueuedDispatch::Cancel {
530                    pointer,
531                    reason,
532                    recipient,
533                } => {
534                    self.run_one_cancel(pointer, reason, recipient, &mut *ops);
535                }
536            }
537        }
538    }
539
540    /// One dispatch at depth zero, with `snapshot` installed as the tree's view
541    /// of the in-flight sample and the previous value restored afterwards.
542    ///
543    /// Save-and-restore rather than reset-to-default: the restore is what stops
544    /// one queued dispatch's snapshot standing as the tree's view of the world
545    /// once it has returned, while the drain replays the next entry.
546    fn run_one_dispatch(
547        &mut self,
548        event: WidgetEvent,
549        snapshot: crate::pointer::InputSnapshot,
550        ops: &mut dyn crate::window::WindowOps,
551    ) {
552        let previous = std::mem::replace(&mut self.current_input, snapshot);
553        self.dispatch_depth += 1;
554        self.dispatch_event_impl(event, ops);
555        self.dispatch_depth -= 1;
556        self.current_input = previous;
557    }
558
559    /// Dismiss the top overlay Escape may close, as the Escape key does, and
560    /// give the focus back to where that overlay took it from. `false` when
561    /// nothing was dismissed.
562    fn dismiss_top_on_escape(&mut self, ops: &mut dyn crate::window::WindowOps) -> bool {
563        let mark = self.dismissal_mark();
564        let Some((_id, content_ids, focus_restore)) =
565            self.overlay_manager.try_dismiss_top_on_escape()
566        else {
567            return false;
568        };
569        self.dormant_dismissed_content(&content_ids, ops);
570        self.return_focus_after_dismissal(focus_restore, mark, ops);
571        true
572    }
573
574    /// Offer Escape to what holds the focus inside the overlay Escape would
575    /// close, before that overlay goes: the `on_key_preview` handlers from the
576    /// overlay's content root down to the focused node's parent, root first,
577    /// as the preview pass runs them. `true` when one took the key.
578    ///
579    /// A widget in a dialog that says "Escape comes back here" (a list row
580    /// being edited, a card being edited, a question waiting for an answer)
581    /// takes the key before the dialog does, as a focused element's `keydown`
582    /// in a browser comes before its `<dialog>`'s cancel. Only the overlay
583    /// Escape would close is asked: a popup over the focused control (a combo
584    /// box's list) is that overlay, the focus is not inside it, and it closes
585    /// first. Nothing fires when no such overlay holds the focus, so a handler
586    /// never sees the key twice: either one takes it here, or the overlay
587    /// closes and the key goes no further.
588    fn escape_taken_inside_top_overlay(
589        &mut self,
590        event: &WidgetEvent,
591        ops: &mut dyn crate::window::WindowOps,
592    ) -> bool {
593        let Some((_, content)) = self.overlay_manager.top_escape_target() else {
594            return false;
595        };
596        let Some(focus) = self.focused else {
597            return false;
598        };
599        let mut path = Vec::new();
600        let mut current = self.arena.parent(focus);
601        let mut inside = false;
602        while let Some(id) = current {
603            path.push(id);
604            if id == content {
605                inside = true;
606                break;
607            }
608            current = self.arena.parent(id);
609        }
610        if !inside || !self.arena.is_enabled(focus) {
611            return false;
612        }
613        for &id in path.iter().rev() {
614            let frame = self.arena.local_frame(id);
615            let mut ctx = self
616                .make_event_context(&mut *ops)
617                .with_dispatch_node(id)
618                .with_content_language(self.content_language(id))
619                .with_dispatch_target(focus)
620                .with_local_frame(frame);
621            let response = if let Some(node) = self.arena.get_mut(id) {
622                Self::try_handler_preview(node, event, &mut ctx).unwrap_or(EventResponse::Ignored)
623            } else {
624                EventResponse::Ignored
625            };
626            self.collect_from_ctx(ctx, id);
627            if response == EventResponse::Handled {
628                self.arena.mark_needs_paint(id);
629                // Its release goes where the press went, as for any key the
630                // focused widget's dispatch took.
631                self.note_key_press(focus);
632                return true;
633            }
634        }
635        false
636    }
637
638    /// Answer a request to close the window that the user made (Alt+F4, the
639    /// title bar's close button, the taskbar's Close) while a modal overlay is
640    /// open in it. It does what Escape would and nothing more, as Alt+F4 does
641    /// to a dialog window: the top overlay Escape may close goes through its
642    /// own dismissal (a modal's Cancel path), and a modal Escape cannot close
643    /// stays. Returns `true` when a modal was open, so the window's close is
644    /// not asked for: the next request reaches it once no modal is left.
645    /// `false` when none was open, and the window's close goes ahead.
646    ///
647    /// The window manager's seam, called for the user's own close gestures
648    /// only, and the one a title bar's close button reaches through
649    /// `EventContext::give_close_request_to_modal`: `EventContext::close_window`
650    /// and a quit ask the window directly.
651    #[doc(hidden)]
652    pub fn answer_close_request_with_modal(
653        &mut self,
654        ops: &mut dyn crate::window::WindowOps,
655    ) -> bool {
656        if !self.overlay_manager.has_open_modal() {
657            return false;
658        }
659        // As the Escape key does: a tooltip, and any overlay nothing can be
660        // done in, go first without being what the request is spent on.
661        self.tooltip_escape_pressed();
662        self.inert_overlays_escape_pressed(ops);
663        self.dismiss_top_on_escape(ops);
664        true
665    }
666
667    /// Record that the press being dispatched went to `target`. A fresh press
668    /// replaces a record for the same key (its release was lost); an
669    /// auto-repeat keeps the first.
670    fn note_key_press(&mut self, target: WidgetId) {
671        let Some((identity, repeat)) = self.current_key else {
672            return;
673        };
674        match self.key_presses.iter_mut().find(|(id, _)| *id == identity) {
675            Some(_) if repeat => {}
676            Some(record) => record.1 = target,
677            None => self.key_presses.push((identity, target)),
678        }
679    }
680
681    /// Whether `id` asked for every key release it had the press of, even
682    /// behind a modal opened since (a web view, whose engine otherwise keeps
683    /// the key held). See `BuildContext::receive_every_key_release`.
684    fn receives_every_key_release(&self, id: WidgetId) -> bool {
685        self.arena
686            .get(id)
687            .is_some_and(|node| node.receives_every_key_release)
688    }
689
690    /// Deliver a key release to the widget that received its press, not to
691    /// whatever focus moved to while the key was down: the Enter that ran
692    /// "Close tab" must not reach the next tab's button as a release. The
693    /// release bubbles from there (no preview pass), when that widget is
694    /// still active and not behind a modal opened since (a widget that
695    /// captures the keyboard, or one that asked for every release, a web
696    /// view, still gets it); otherwise it is dropped. A release with no press recorded goes to focus as before,
697    /// except Enter and Space, whose release activates a control: a lone one
698    /// (its press closed a dialog in another window, or was taken by a
699    /// shortcut) is dropped.
700    fn dispatch_key_release(
701        &mut self,
702        key: Key,
703        event: &WidgetEvent,
704        ops: &mut dyn crate::window::WindowOps,
705    ) {
706        let identity = self.current_key.map(|(id, _)| id);
707        let pressed = identity.and_then(|identity| {
708            let at = self
709                .key_presses
710                .iter()
711                .position(|(id, _)| *id == identity)?;
712            Some(self.key_presses.remove(at).1)
713        });
714        match pressed {
715            Some(target) if Some(target) == self.focused => {
716                self.dispatch_to_widget(target, event, &mut *ops);
717            }
718            Some(target) => {
719                if self.arena.is_active(target)
720                    && (!self.is_behind_modal(target)
721                        || self.is_keyboard_capture(target)
722                        || self.receives_every_key_release(target))
723                {
724                    // Bubbled from the press target up, as the press was, so
725                    // an ancestor tracking held keys hears it too; no preview
726                    // pass, which belongs to the focused widget's route.
727                    // A target behind a modal (one that asked for every release)
728                    // gets it alone: its ancestors are behind the modal too.
729                    let behind_modal = self.is_behind_modal(target);
730                    let mut current = Some(target);
731                    while let Some(id) = current {
732                        if self.dispatch_to_widget_direct_returning_handled(id, event, &mut *ops)
733                            || behind_modal
734                        {
735                            break;
736                        }
737                        current = self.arena.parent(id);
738                    }
739                }
740            }
741            None if matches!(key, Key::Enter | Key::Space) => {}
742            None => {
743                if let Some(focused) = self.focused {
744                    self.dispatch_to_widget(focused, event, &mut *ops);
745                }
746            }
747        }
748    }
749
750    fn dispatch_event_impl(&mut self, event: WidgetEvent, ops: &mut dyn crate::window::WindowOps) {
751        // Admit the pointer this event belongs to into the table before
752        // anything routes. A legacy `WidgetEvent` names no pointer, so
753        // `current_input` reports the mouse and this creates (or refreshes) the
754        // one mouse entry — which is what every singular accessor then reads,
755        // so a mouse-only tree behaves exactly as it did before the table.
756        if let Some(position) = pointer_event_position(&event) {
757            let is_down = matches!(event, WidgetEvent::PointerDown { .. });
758            let is_move = matches!(event, WidgetEvent::PointerMove { .. });
759            if !self.admit_current_pointer(position, is_down, is_move) {
760                return;
761            }
762            // A hovering-capable pointer takes the hover-owner role by pointing:
763            // the later sample wins, and whoever held it is sent a leave. A
764            // contact is refused the role outright — it has no hover to give.
765            if self.current_input.pointer.kind.hovers() {
766                self.claim_hover_owner_for_current(&mut *ops);
767            }
768        }
769
770        // Which physical key this is, for pairing a release with its press:
771        // what the window manager noted, else the key itself.
772        if let WidgetEvent::KeyDown { key, .. } | WidgetEvent::KeyUp { key, .. } = &event {
773            let noted = self
774                .window_state
775                .as_ref()
776                .and_then(|w| w.take_key_identity());
777            self.current_key = Some(noted.unwrap_or_else(|| (logical_key_identity(*key), false)));
778        } else if self.dispatch_depth <= 1 {
779            // Another event: no key identity is current.
780            self.current_key = None;
781        }
782
783        // Track input modality for `:focus-visible`: keyboard input reveals
784        // focus rings, pointer input hides them. Updated at the dispatch root so
785        // every handler (and the next paint) observes the current modality.
786        match &event {
787            WidgetEvent::KeyDown { .. } if !self.focus_visible.get() => {
788                self.focus_visible.set(true);
789            }
790            WidgetEvent::PointerDown { .. } if self.focus_visible.get() => {
791                self.focus_visible.set(false);
792            }
793            _ => {}
794        }
795
796        // The "back toward the parent overlay" key closes the top nested
797        // overlay (e.g. an open submenu over its parent menu). It is the
798        // inline-start arrow: ArrowLeft under LTR, ArrowRight under RTL.
799        // Without the RTL flip, ArrowLeft would navigate *into* a submenu
800        // in RTL menus yet still dismiss it here.
801        let overlay_back_key = match self.layout_direction {
802            crate::environment::LayoutDirection::RightToLeft => Key::ArrowRight,
803            crate::environment::LayoutDirection::LeftToRight => Key::ArrowLeft,
804        };
805        if let WidgetEvent::KeyDown { key, .. } = &event
806            && *key == overlay_back_key
807        {
808            // Count menu-level (non-host) overlays. A revealed collapsible
809            // `MenuBar` is itself a *host* overlay (Role::MenuBar), so a
810            // single open top-level menu sitting over it must NOT be treated
811            // as a nested submenu — otherwise the back key would close the
812            // menu instead of letting the menubar navigate to the previous
813            // one. Only when ≥2 non-host overlays are stacked (a submenu over
814            // its parent menu) does the back key dismiss the top overlay.
815            //
816            // **Menus only**, which is what the band says. Every mounted text
817            // editor keeps one full-viewport affordance host alive in the
818            // [`TextAffordance`](crate::overlay::OverlayBand::TextAffordance)
819            // band for its selection handles, so counting bands alike made two
820            // editors on one page read as a menu cascade: the back key then
821            // tore down an affordance host and returned, and ArrowLeft stopped
822            // reaching *any* editor in that window for as long as a second one
823            // was mounted. A text affordance is not a cascade level, the same
824            // reason `OverlayBand::dismissed_by_outside_press` already excludes
825            // it from press dismissal.
826            //
827            // An inert overlay (a slider's value readout, say) is no level
828            // either: it takes no input, so it is neither counted nor what the
829            // key closes. Counted, a readout under one open menu made that menu
830            // read as a submenu and closed it; on top of the stack, it was the
831            // overlay the key closed, and the key was spent on it.
832            //
833            // The topmost *non-inert* overlay is the menu this key means: the
834            // stack is band-ordered (`OverlayManager::show_with_auto_dismiss`
835            // inserts, it does not push), so a `Standard` overlay always sits
836            // above every `TextAffordance` one.
837            let nested_menu_overlays = {
838                let ids: Vec<_> = self
839                    .overlay_manager
840                    .stack
841                    .iter()
842                    .filter(|o| o.band == crate::overlay::OverlayBand::Standard && !o.inert)
843                    .map(|o| o.id)
844                    .collect();
845                ids.into_iter()
846                    .filter(|&id| !self.overlay_is_host_surface(id))
847                    .count()
848            };
849            // The back key only navigates *menu* cascades; it must never close a
850            // dialog / alert / modal that happens to sit on top. Each modal is a
851            // scrim+panel overlay pair and the (non-host) scrims inflate the count
852            // above, so also require the topmost non-inert overlay to be
853            // back-navigable — i.e. a non-host (menu) surface — before dismissing
854            // it.
855            let top_id = self
856                .overlay_manager
857                .stack
858                .iter()
859                .rev()
860                .find(|o| !o.inert)
861                .map(|o| o.id);
862            let top_is_back_navigable = top_id.is_some_and(|id| !self.overlay_is_host_surface(id));
863            if nested_menu_overlays > 1
864                && top_is_back_navigable
865                && let Some(top_id) = top_id
866            {
867                let mark = self.dismissal_mark();
868                let (content_ids, focus_restore) =
869                    self.overlay_manager.dismiss_with_focus_restore_because(
870                        top_id,
871                        crate::overlay::DismissReason::Escape,
872                    );
873                self.dormant_dismissed_content(&content_ids, &mut *ops);
874                self.return_focus_after_dismissal(focus_restore, mark, &mut *ops);
875                return;
876            }
877        }
878
879        // Escape retires any shown tooltip first, and does **not** stop there —
880        // see `tooltip_escape_pressed`. Ordered before the stack walk below so
881        // that walk can no longer pick a tooltip as the thing to dismiss, which
882        // is what used to spend the key on a tip nobody was reading while the
883        // editor / menu / dialog the user meant stayed open.
884        if let WidgetEvent::KeyDown {
885            key: Key::Escape, ..
886        } = &event
887        {
888            self.tooltip_escape_pressed();
889            // The same rule for every overlay nothing can be done in: it goes,
890            // and the key goes on. See `inert_overlays_escape_pressed`.
891            self.inert_overlays_escape_pressed(&mut *ops);
892        }
893
894        if let WidgetEvent::KeyDown {
895            key: Key::Escape, ..
896        } = &event
897            && !self.overlay_manager.is_empty()
898            && (self.escape_taken_inside_top_overlay(&event, &mut *ops)
899                || self.dismiss_top_on_escape(&mut *ops))
900        {
901            return;
902        }
903
904        // Outside-press overlay dismissal. Two shapes, chosen by the pointer:
905        // an indirect one dismisses on the press and falls through, exactly as
906        // it always has; a direct one *arms* on the press and commits on the
907        // release. See `arm_outside_press_dismissal`.
908        match &event {
909            WidgetEvent::PointerDown {
910                position, button, ..
911            } => {
912                if self.arm_outside_press_dismissal(*position, *button, &mut *ops) {
913                    return;
914                }
915            }
916            WidgetEvent::PointerUp { position, .. } => {
917                if self.commit_outside_press_dismissal(*position, &mut *ops) {
918                    return;
919                }
920            }
921            WidgetEvent::PointerCancel { pointer, .. } => {
922                // A revoked press dismisses nothing. The arming Down was never
923                // delivered beneath either, so the whole gesture leaves no
924                // trace — which is the point of deferring to the release.
925                self.overlay_manager.abort_dismiss(pointer.id);
926            }
927            _ => {}
928        }
929
930        // Key-capture mode: if a callback is armed (via
931        // `WidgetTree::begin_key_capture`), the next KeyDown bypasses
932        // shortcut resolution entirely and runs the callback with
933        // mutable access to the registry AND an `EventContext` so
934        // rebind handlers can also emit commands, send intents,
935        // dismiss overlays, etc. The capture is one-shot; its slot
936        // is emptied before the callback runs so a re-entrant
937        // `begin_key_capture` call from inside the callback arms a
938        // fresh session (rather than competing with the in-flight
939        // one).
940        if let WidgetEvent::KeyDown { key, modifiers, .. } = &event
941            && let Some(callback) = self.take_key_capture()
942        {
943            let keystroke = crate::shortcut::KeyStroke::new(*key, *modifiers);
944            let mut cap_ctx = self.make_event_context(&mut *ops);
945            callback(keystroke, self.shortcut_registry_mut(), &mut cap_ctx);
946            // Route side effects of the callback through the
947            // focused widget (or the intent anchor if no focus).
948            let anchor = self.focused.or_else(|| self.intent_anchor());
949            if let Some(anchor_id) = anchor {
950                self.collect_from_ctx(cap_ctx, anchor_id);
951                self.drain_pending_intents(&mut *ops);
952            }
953            return;
954        }
955
956        // Keyboard-capture surfaces (a terminal, a game viewport) opt out
957        // of shortcut resolution entirely while focused: they want every
958        // keystroke delivered raw so a host-app `Ctrl+C` shortcut can't
959        // steal the SIGINT the child process needs. The Escape / overlay
960        // back-navigation handled above still runs first, so an open
961        // overlay is still dismissable. Only a KeyDown is affected; KeyUp
962        // and IME already bypass the shortcut path.
963        let focus_captures_keys = matches!(&event, WidgetEvent::KeyDown { .. })
964            && self.focused.is_some_and(|f| self.is_keyboard_capture(f));
965
966        // Shortcut → intent → action dispatch. A KeyDown whose chord
967        // matches a registered enabled `Shortcut` whose scope contains
968        // the focused widget is consumed here: the shortcut's
969        // `on_activate` runs (producing an `Intent`), its ctx side
970        // effects are collected, and the intent walks source-widget →
971        // root firing any matching `Action`. An intent nothing here takes
972        // is kept for the application tree when that tree takes it.
973        // Otherwise the focused widget sees the raw KeyDown below.
974        //
975        // Two-phase: the registry is inspected first (immutable read)
976        // to resolve `id / scope / propagate_when_disabled`. Only if
977        // scope matches the current focus do we take a mutable borrow
978        // to invoke `on_activate` — this way a scope mismatch cannot
979        // drop side effects the closure put into its ctx, because
980        // the closure never runs.
981        if !focus_captures_keys && let WidgetEvent::KeyDown { key, modifiers, .. } = &event {
982            let keystroke = crate::shortcut::KeyStroke::new(*key, *modifiers);
983            // Gather every same-chord candidate (owned fields) before any
984            // mutable borrow of the registry, then pick the one whose scope
985            // actually applies to the current focus. `find_by_keystroke`
986            // alone yields only the first by `(category, id)` order, which
987            // can be a `Scoped` binding outside focus shadowing an
988            // applicable `Global` one — or a `Global` binding that should
989            // yield to an in-focus `Scoped` one. Selection needs focus +
990            // the tree, so it happens here, not in the registry.
991            let candidates: Vec<(&'static str, crate::shortcut::ShortcutScope, bool)> = self
992                .shortcut_registry
993                .matches_by_keystroke(keystroke)
994                .map(|eff| {
995                    (
996                        eff.shortcut.id,
997                        eff.shortcut.scope,
998                        eff.shortcut.propagate_when_disabled,
999                    )
1000                })
1001                .collect();
1002            // The focus region commands (F6, Shift+F6) yield: an application
1003            // shortcut on the same chord that applies wins whatever its
1004            // category, and with no region to go to and no action (in the
1005            // window or the application tree) taking the intent they are not
1006            // candidates, so the key reaches the focused widget as before.
1007            let (region_commands, others): (Vec<_>, Vec<_>) = candidates
1008                .into_iter()
1009                .partition(|(id, _, _)| crate::shortcut::region_direction(id).is_some());
1010            let lookup = self.select_shortcut_for_focus(&others).or_else(|| {
1011                let source = self.focus_or_modal().or_else(|| self.intent_anchor());
1012                let live: Vec<_> = region_commands
1013                    .into_iter()
1014                    .filter(|(id, _, _)| {
1015                        crate::shortcut::region_direction(id).is_some_and(|forward| {
1016                            self.region_cycle_target_from(source, forward).is_some()
1017                                || source.is_some_and(|source| self.can_handle_from(source, id))
1018                        })
1019                    })
1020                    .collect();
1021                self.select_shortcut_for_focus(&live)
1022            });
1023            if let Some((id, scope, propagate_when_disabled)) = lookup {
1024                let anchor = match scope {
1025                    // Global shortcuts fire regardless of focus. If no
1026                    // widget is currently focused, anchor the intent
1027                    // walk in the topmost modal, or at the intent anchor so
1028                    // actions registered at the top of the app's tree still
1029                    // see the intent.
1030                    crate::shortcut::ShortcutScope::Global => {
1031                        self.focus_or_modal().or_else(|| self.intent_anchor())
1032                    }
1033                    crate::shortcut::ShortcutScope::Scoped(scope_id) => self
1034                        .focus_or_modal()
1035                        .filter(|f| self.scope_distance_from_focus(*f, scope_id).is_some()),
1036                };
1037                if let Some(anchor_id) = anchor {
1038                    let mut act_ctx = self.make_event_context(&mut *ops);
1039                    if let Some(intent) =
1040                        self.shortcut_registry
1041                            .invoke_on_activate(id, keystroke, &mut act_ctx)
1042                    {
1043                        self.collect_from_ctx(act_ctx, anchor_id);
1044                        // Intents `on_activate` sent through its ctx go
1045                        // first, as they did when everything shared one
1046                        // queue.
1047                        self.drain_pending_intents(&mut *ops);
1048                        // Tag shortcut origin so analytics can
1049                        // distinguish keyboard-driven activations from
1050                        // button / menu / programmatic ones.
1051                        let intent = self.sent_here(
1052                            intent.with_source(crate::telemetry::IntentSource::Shortcut),
1053                        );
1054                        let keep = self.keeps_unclaimed(&intent).then(|| intent.clone());
1055                        let consumed = self.dispatch_intent(
1056                            anchor_id,
1057                            intent,
1058                            propagate_when_disabled,
1059                            &mut *ops,
1060                        );
1061                        self.drain_pending_intents(&mut *ops);
1062                        if consumed {
1063                            return;
1064                        }
1065                        // Nothing in this tree took it, but the application
1066                        // tree does: kept for it, and the key is used.
1067                        if let Some(intent) = keep {
1068                            self.keep_unclaimed(intent, &mut *ops);
1069                            return;
1070                        }
1071                        // No action took the intent: the key is the focused
1072                        // widget's after all, delivered below as if no
1073                        // shortcut had matched. The standard edit shortcuts
1074                        // depend on this: Ctrl+C is bound in every tree, and
1075                        // a widget that copies from its own `on_key` must
1076                        // still see it.
1077                    }
1078                }
1079                // Chosen candidate had no anchor after all (e.g. a Global
1080                // match while nothing is focused and the tree has no
1081                // roots) — fall through to normal KeyDown dispatch.
1082                // `on_activate` was never called, so nothing to clean up.
1083            }
1084            // `lookup` is `None` when every same-chord candidate was a
1085            // scoped binding outside the focused subtree — fall through.
1086        }
1087
1088        // Escape during an OS drag we escalated. There is no `active_drag`
1089        // any more — `try_escalate_to_os_drag` took it when the platform
1090        // accepted the hand-off — so this cannot live in the block below, but
1091        // it is the same user gesture and belongs on the same path rather than
1092        // being special-cased in the event loop of whichever backend needs it.
1093        if self.outbound_drag_source.is_some()
1094            && let WidgetEvent::KeyDown {
1095                key: Key::Escape, ..
1096            } = &event
1097        {
1098            ops.cancel_os_drag();
1099            // Deliberately no `return`: the backend answers asynchronously with
1100            // a terminal `DragEnded`, which is what actually tears the session
1101            // down via `handle_os_drag_ended`. Swallowing the key here would
1102            // also stop Escape from closing whatever else is open.
1103        }
1104
1105        // --- Active drag session handling ---
1106        //
1107        // Our own OS drag re-entered into this window is driven by the OS drag
1108        // events (`update_external_drag`, `end_external_drag`), never by this
1109        // window's pointer samples. On X11 winit keeps its implicit grab
1110        // through the XDND drag, so the press that handed the drag over still
1111        // sends this window its moves and its release; taking that release as
1112        // the drop would land it here, lose its in-app outcome (the session has
1113        // no source) and leave the XDND drop with nothing to complete. A move
1114        // is dropped, and the release goes on to the router below, which
1115        // swallows it as the `Up` of a press cancelled by the handover. Only
1116        // the dragging pointer's: another pointer (a pen hovering, a second
1117        // finger) goes on to the router as it would with no drag at all.
1118        if self.os_drag_reentered
1119            && matches!(
1120                event,
1121                WidgetEvent::PointerMove { .. } | WidgetEvent::PointerUp { .. }
1122            )
1123        {
1124            let dragging = self.current_pointer_id();
1125            let own = self
1126                .active_drag
1127                .as_ref()
1128                .is_some_and(|d| d.pointer.id == dragging);
1129            if own && matches!(event, WidgetEvent::PointerMove { .. }) {
1130                return;
1131            }
1132        } else if self.active_drag.is_some() {
1133            match &event {
1134                WidgetEvent::PointerMove { position, .. } => {
1135                    self.handle_drag_sample(*position, &mut *ops);
1136                    return;
1137                }
1138                WidgetEvent::PointerUp { position, .. } => {
1139                    self.handle_drag_drop(*position, &mut *ops);
1140                    return;
1141                }
1142                WidgetEvent::KeyDown {
1143                    key: Key::Escape, ..
1144                } => {
1145                    self.cancel_active_drag(&mut *ops);
1146                    return;
1147                }
1148                WidgetEvent::Scroll { .. } => {
1149                    // Route the wheel to the current drop target so users
1150                    // can scroll the list/tree beneath the drag. Then
1151                    // synthesise a hover at the stationary pointer so
1152                    // feedback, drop-index math and the preview overlay
1153                    // all reflect the new scroll offset.
1154                    let target_and_pos = self
1155                        .active_drag
1156                        .as_ref()
1157                        .and_then(|d| d.current_target.map(|t| (t, d.current_position)));
1158                    if let Some((target, _pos)) = target_and_pos {
1159                        self.dispatch_to_widget(target, &event, &mut *ops);
1160                    }
1161                    if let Some((_, pos)) = target_and_pos
1162                        && self.active_drag.is_some()
1163                    {
1164                        self.handle_drag_move(pos, &mut *ops);
1165                    }
1166                    return;
1167                }
1168                _ => {}
1169            }
1170        }
1171
1172        // A keyboard route to the context menu, reserved at the dispatcher so
1173        // every widget with a `.context_menu(..)` gets one without opting in.
1174        //
1175        // It has to be here rather than in a widget, and it cannot be a
1176        // `Shortcut`: shortcut resolution runs above this point, so a global
1177        // binding would fire while the user was typing in a modal. Sitting
1178        // below it means an application that deliberately binds Shift+F10 to
1179        // something else still wins.
1180        if let WidgetEvent::KeyDown { key, modifiers, .. } = &event
1181            && is_context_menu_chord(*key, *modifiers)
1182            && self.open_context_menu_from_keyboard(&mut *ops)
1183        {
1184            return;
1185        }
1186
1187        match &event {
1188            WidgetEvent::PointerMove { position, .. } => {
1189                // Every sample: re-check the sequence's members against the
1190                // arena, and record where the pointer now is so each threshold
1191                // reads one number.
1192                self.note_sequence_position(*position);
1193                self.revalidate_sequence(&mut *ops);
1194                // Timers before positional thresholds, and before the move
1195                // reaches any recognizer — see `tick_sequence_timers`.
1196                self.tick_sequence_timers();
1197                // The multi-contact and palm layers see every sample, decided
1198                // or not: a pinch is arbitrated by contact count rather than by
1199                // the press arbitration, and the palm watch has to know whether
1200                // this contact ever moved.
1201                self.note_palm_sample(*position);
1202                self.feed_pinch(super::pan_arbiter::PinchFeed::Move, *position, &mut *ops);
1203                if let Some(captured) = self.current_pointer_capture() {
1204                    self.dispatch_to_widget(captured, &event, &mut *ops);
1205                    // Advance the arbitration so an ancestor drag can still
1206                    // begin while a descendant tap holds the capture. Once a
1207                    // drag latches, `active_drag` takes over and the capture
1208                    // branch above is bypassed.
1209                    if self.active_drag.is_none() {
1210                        self.advance_sequence(&event, &mut *ops);
1211                    }
1212                } else {
1213                    self.handle_pointer_move(&event, *position, &mut *ops);
1214                    // No capture: for a mouse there is nothing enrolled (a
1215                    // gesture member is only enrolled *through* a capture), so
1216                    // this is a no-op. A contact panning from empty space has
1217                    // its pan claimants here.
1218                    if self.active_drag.is_none() {
1219                        self.advance_sequence(&event, &mut *ops);
1220                    }
1221                }
1222                // After the arbitration, so a claim taken on *this* sample
1223                // already delivers its own movement rather than waiting a frame.
1224                self.advance_pan(*position, &mut *ops);
1225                // …and after that, so the press visual answers to a claim taken
1226                // on this very sample rather than surviving it by one move.
1227                self.update_press(*position);
1228                // A tree-owned hold survives only while the contact holds
1229                // still; past the tap boundary this is a pan or a drag.
1230                self.touch_route_moved(self.current_pointer_id());
1231                // Hover-owner-only, exactly as `handle_pointer_move` is. The
1232                // `DismissBehavior::PointerLeave` grace is a *hover* dismissal:
1233                // it asks "has the pointer left this overlay and its trigger",
1234                // a question only a pointer that hovers is entitled to answer.
1235                // Ungated, any contact's move anywhere started the 150 ms grace
1236                // on every such overlay — so a submenu a finger had just tapped
1237                // open was closed by the frame pass with no further input, and
1238                // no mouse test could see it because a mouse *is* the hover
1239                // owner.
1240                if self.pointers.hover_owner_id() == Some(self.current_pointer_id()) {
1241                    self.update_pointer_leave_overlays(*position, &mut *ops);
1242                }
1243            }
1244            WidgetEvent::PointerDown {
1245                position, button, ..
1246            } => {
1247                // A new press is a new interaction: whatever took the previous
1248                // one away has nothing to say about this one.
1249                let pressed = self.current_pointer_id();
1250                self.cancelled_pointers.retain(|p| *p != pressed);
1251                // The user has acted — a tooltip that has not yet appeared is
1252                // now answering a question nobody is asking any more, and one
1253                // already up is covering the thing being clicked. Cancel the
1254                // pending dwell and retire any shown non-sticky tip, the way
1255                // Windows and GTK both do. Runs before hit-testing so it fires
1256                // even for a press that lands on nothing.
1257                self.tooltip_pointer_press(Some(*position));
1258                // Routed for the pointer that is actually pressing: a finger
1259                // gets its grip outsets and its miss-only slop, a mouse gets the
1260                // exact test it has always had.
1261                let pressing = self.current_input.pointer;
1262                if let Some(target) = self.hit_test_for(*position, &pressing) {
1263                    if *button == PointerButton::Secondary
1264                        && self.show_context_menu_for(
1265                            target,
1266                            *position,
1267                            crate::widget_builder::ContextMenuTrigger::Pointer,
1268                            &mut *ops,
1269                        )
1270                    {
1271                        return;
1272                    }
1273                    // Open the arbitration BEFORE any handler runs: the frozen
1274                    // `TouchAction` has to be readable from `ctx.touch_action()`
1275                    // inside the press handler, and an explicit
1276                    // `capture_pointer()` made there needs a sequence to enrol
1277                    // into.
1278                    self.begin_sequence(target, *position);
1279                    // Straight after the sequence, so the frozen `TouchAction`
1280                    // and the enrolled pan members are already in hand — and so
1281                    // a press on a coasting list catches it before anything
1282                    // else runs.
1283                    let modifiers = match &event {
1284                        WidgetEvent::PointerDown { modifiers, .. } => *modifiers,
1285                        _ => crate::event::Modifiers::NONE,
1286                    };
1287                    self.begin_pan(target, *position, modifiers);
1288                    self.begin_palm_watch(*position);
1289                    self.feed_pinch(super::pan_arbiter::PinchFeed::Down, *position, &mut *ops);
1290                    // Open the press record before the dispatch, so a handler
1291                    // asking `ctx.press_pending()` on its own `PointerDown`
1292                    // gets the answer the router already knows.
1293                    let focusable = self.find_focusable_at_or_above(target);
1294                    self.begin_press(focusable);
1295                    // An indirect pointer focuses on press, as it always has.
1296                    // A direct one waits for the release: a finger that lands
1297                    // on a control and slides away has not chosen it, and
1298                    // moving focus at touch-down would leave the ring — and
1299                    // the caret — on a control the user never activated. See
1300                    // `focus_on_release`. A widget built with
1301                    // `focus_on_click(false)` takes no focus from either, and
1302                    // has the focused field commit on the release that
1303                    // completes the click, for either.
1304                    if !pressing.kind.is_direct()
1305                        && let Some(focusable) = focusable
1306                        && self.click_may_focus(focusable)
1307                    {
1308                        self.focus_with_origin_ops(
1309                            focusable,
1310                            crate::focus::FocusOrigin::Pointer(pressing.kind),
1311                            &mut *ops,
1312                        );
1313                    }
1314                    self.dispatch_to_widget(target, &event, &mut *ops);
1315                    // Enrol the competitors that only become knowable once the
1316                    // press has been dispatched: the drag-capable ancestors of
1317                    // whoever took the capture (tap-vs-drag across the hit
1318                    // path).
1319                    if self.active_drag.is_none() {
1320                        self.enrol_sequence_members(&event, &mut *ops);
1321                    }
1322                    // The arena has now claimed the press, so the node whose
1323                    // visual this record drives is known — and whether the
1324                    // button that opened it is one that node can act on.
1325                    self.adopt_press_owner(*button);
1326                    // Last: the tree-owned hold. It has to see the enrolment
1327                    // (a deferred grab spends the hold) and it has to see the
1328                    // handlers a press-time build may have installed, so it is
1329                    // resolved after both. See `super::touch_route`.
1330                    self.arm_touch_route(target, *position);
1331                }
1332            }
1333            WidgetEvent::PointerUp {
1334                position, button, ..
1335            } => {
1336                // A `PointerCancel` is terminal. If this pointer's press was
1337                // revoked, the `Up` that follows completes nothing — the widget
1338                // has already been told to let go, and delivering the release
1339                // would hand it back an interaction the system took away. Drop
1340                // it, and forget the cancel: the pointer is free again.
1341                let released = self.current_pointer_id();
1342                // The hold is over whatever else this release does, and it is
1343                // cleared before any of it so a handler that runs below cannot
1344                // see a route that will never fire.
1345                self.cancel_touch_route(released);
1346                if let Some(index) = self.cancelled_pointers.iter().position(|p| *p == released) {
1347                    self.cancelled_pointers.swap_remove(index);
1348                    crate::trace_input!(
1349                        Samples,
1350                        "swallowing the Up for {released:?}: its press was cancelled"
1351                    );
1352                    return;
1353                }
1354                // The palm verdict, before anything else acts on the release:
1355                // a contact the heuristic rejects must fire no tap at all, and
1356                // the only way to guarantee that is to take the cancel funnel
1357                // instead of the release path. Judged on the `Up` and never
1358                // earlier — a contact is not revoked while the user might still
1359                // be doing something with it.
1360                self.feed_pinch(super::pan_arbiter::PinchFeed::Up, *position, &mut *ops);
1361                if self.take_palm_verdict(released) {
1362                    crate::trace_input!(
1363                        Samples,
1364                        "{released:?} released as a palm: large, and it never moved"
1365                    );
1366                    self.cancel_pointer(
1367                        released,
1368                        crate::pointer::CancelReason::PalmRejected,
1369                        &mut *ops,
1370                    );
1371                    return;
1372                }
1373                // A pan hands its release velocity to the fling driver here,
1374                // and closes its session either way.
1375                self.end_pan(*position, &mut *ops);
1376                // The pointer sequence ends here — the release sweep feeds the
1377                // `Up` to every member still following the press so its
1378                // recognizer clears the press origin it recorded. Without this,
1379                // a press that an interactive descendant captured (a card's
1380                // editor, a row's button) leaves the ancestor's DragRecognizer
1381                // armed, and the next hover move starts a phantom drag.
1382                self.note_sequence_position(*position);
1383                // Whether this release completes a tap on a control that
1384                // takes no focus is read from the sequence, so before it ends.
1385                let taps_unfocusable = self.release_taps_unfocusable(*position, *button);
1386                self.end_sequence(&event, &mut *ops);
1387                // A direct pointer's focus lands here, before the release is
1388                // dispatched, so a handler activating on the `Up` runs with the
1389                // focus its own press earned; so does the commit a click on a
1390                // control that takes no focus makes, for every pointer.
1391                self.focus_on_release(*position, taps_unfocusable, &mut *ops);
1392                if let Some(captured) = self.current_pointer_capture() {
1393                    self.dispatch_to_widget(captured, &event, &mut *ops);
1394                    // Per pointer: this Up releases *this* pointer's capture and
1395                    // leaves every other contact's alone.
1396                    self.set_current_pointer_capture(None);
1397                } else {
1398                    let releasing = self.current_input.pointer;
1399                    if let Some(target) = self.hit_test_for(*position, &releasing) {
1400                        self.dispatch_to_widget(target, &event, &mut *ops);
1401                    }
1402                }
1403                // The press is over. Any arena still following this contact saw
1404                // its `Down` but not its `Up` — see `release_arenas_following`.
1405                let released = self.current_pointer_id();
1406                self.release_arenas_following(released);
1407                // The visual goes with it. After the dispatch, so a release
1408                // handler reading `ctx.is_pressed()` still sees the press it is
1409                // completing.
1410                self.end_press(released);
1411            }
1412            WidgetEvent::PointerCancel {
1413                reason, pointer, ..
1414            } => {
1415                // A hand-built `PointerCancel` — a caller reaching the legacy
1416                // door with one, a test — means the same thing a producer does,
1417                // so it takes the same funnel rather than a second teardown of
1418                // its own. Queued behind this dispatch, like every cancel.
1419                let (reason, pointer) = (*reason, pointer.id);
1420                self.cancel_pointer(pointer, reason, &mut *ops);
1421            }
1422            WidgetEvent::Scroll {
1423                window_position: position,
1424                ..
1425            } => {
1426                use super::pan_arbiter::ScrollDelivery;
1427                match ScrollDelivery::for_source(self.current_input.scroll_source) {
1428                    // A synthesised pan (and the coast that follows it) walks
1429                    // the pan claimants and nothing else — see
1430                    // `widget_tree::pan_arbiter` for why the generic bubble
1431                    // would be wrong here.
1432                    ScrollDelivery::ClaimantChain => {
1433                        let position = *position;
1434                        self.route_scroll_along_chain(&event, position, &mut *ops);
1435                    }
1436                    // A positioned scroll routes by hit test; a positionless one
1437                    // keeps the historical hover-then-focus fallback. A mouse wheel
1438                    // is positionless, so this is a no-op for it — the change
1439                    // exists for a pan synthesised from a direct pointer, which
1440                    // never writes hover and would otherwise route nowhere.
1441                    ScrollDelivery::Bubble => {
1442                        let scrolling = self.current_input.pointer;
1443                        let target = match position {
1444                            Some(p) => self.hit_test_for(*p, &scrolling),
1445                            None => self.hovered_id().or(self.focused),
1446                        };
1447                        if let Some(target) = target {
1448                            self.dispatch_to_widget(target, &event, &mut *ops);
1449                        }
1450                    }
1451                }
1452            }
1453            WidgetEvent::KeyDown { key, modifiers, .. } => {
1454                if *key == Key::Tab {
1455                    // Ctrl+Tab / Ctrl+Shift+Tab always leave a keyboard-capture
1456                    // surface (WCAG 2.1.2). A capture node exists precisely to
1457                    // swallow every keystroke — a terminal encodes Tab as `\t`
1458                    // and Shift+Tab as CSI Z — so the ordinary "dispatch first,
1459                    // cycle only when unhandled" rule below can never move focus
1460                    // out of one. Reserving this one chord at the dispatcher, not
1461                    // in each capture widget, is what makes the escape a property
1462                    // of `keyboard_capture` itself rather than a promise every
1463                    // future capture-surface author has to remember to keep.
1464                    //
1465                    // Literal `ctrl()`, not `command()`: Ctrl+Tab is Ctrl+Tab on
1466                    // macOS too — ⌘⇥ is the application switcher and never
1467                    // reaches an app at all. Same reading as `TableView`'s
1468                    // cell-grid escape and `RichTextEditor`'s `tab_escape`.
1469                    let captured_focus = self
1470                        .focused
1471                        .is_some_and(|focused| self.is_keyboard_capture(focused));
1472                    if captured_focus && modifiers.ctrl() {
1473                        self.cycle_focus(modifiers.shift(), &mut *ops);
1474                        return;
1475                    }
1476                    // Dispatch Tab to the focused widget first so
1477                    // ancestors (e.g. an open overlay that wants to
1478                    // close instead of moving focus out through its
1479                    // content) get a chance to intercept. Fall back to
1480                    // built-in focus cycling only when no handler
1481                    // returns `EventResponse::Handled`.
1482                    if let Some(focused) = self.focused {
1483                        self.note_key_press(focused);
1484                    }
1485                    let handled = self
1486                        .focused
1487                        .map(|focused| {
1488                            self.dispatch_to_widget_returning_handled(focused, &event, &mut *ops)
1489                        })
1490                        .unwrap_or(false);
1491                    if !handled {
1492                        self.cycle_focus(modifiers.shift(), &mut *ops);
1493                    }
1494                } else if let Some(focused) = self.focused {
1495                    self.note_key_press(focused);
1496                    self.dispatch_to_widget(focused, &event, &mut *ops);
1497                }
1498            }
1499            WidgetEvent::KeyUp { key, .. } => {
1500                self.dispatch_key_release(*key, &event, &mut *ops);
1501            }
1502            WidgetEvent::ImeComposition { .. } | WidgetEvent::ImeCommit { .. } => {
1503                if let Some(focused) = self.focused {
1504                    self.dispatch_to_widget(focused, &event, &mut *ops);
1505                }
1506            }
1507            WidgetEvent::AccessAction {
1508                target,
1509                action,
1510                target_node,
1511                ..
1512            } => {
1513                // An AT action (e.g. VoiceOver's VO+Space → `Action::Click`)
1514                // always names the node it targets — the element under the
1515                // assistive-technology cursor. It must be delivered to THAT
1516                // node, never to whatever happens to hold keyboard focus.
1517                // Falling back to `self.focused` would make VO+Space fire the
1518                // focused control instead of the cursored one, and would mask
1519                // a stale/inactive target by silently activating something
1520                // else. If the target is missing or no longer active, drop the
1521                // action rather than redirecting it.
1522                //
1523                // Drop it too when a modal is up and the target is behind it
1524                // (`is_behind_modal`). The scrim keeps the pointer off the page
1525                // and the Tab cycle stays in the modal, but the page stays in
1526                // the tree a screen reader walks, and its request names a node
1527                // there directly. Delivered, a click behind "Save changes?"
1528                // opened a second box over it, and a focus request put the
1529                // keyboard on a control the box covers.
1530                if let Some(id) =
1531                    target.filter(|id| self.arena.is_active(*id) && !self.is_behind_modal(*id))
1532                {
1533                    if *action == accesskit::Action::Focus {
1534                        // Land where the keys go. A composite publishes one AT
1535                        // node on a root that is not itself focusable (a
1536                        // `ComboBox` or a `DateEdit` keeps focus on an inner
1537                        // leaf), and `ctx.request_focus` has always walked
1538                        // into the subtree for exactly that reason. The AT path
1539                        // must too: focusing the root parks `self.focused` on a
1540                        // node that takes no keystrokes, and because
1541                        // `on_key_preview` fires only on *strict* ancestors of
1542                        // the focused node, it also disarms the composite's own
1543                        // stepping keys. `first_focusable_descendant` returns the
1544                        // node itself when it is focusable, so every leaf control
1545                        // is unchanged.
1546                        //
1547                        // The walk is gated on the node actually offering
1548                        // `Action::Focus`, which is what makes the sentence
1549                        // above true of composites and only of them. Walking
1550                        // from *any* non-focusable node meant an AT `Focus` on a
1551                        // `Panel`, a `GroupBox`, a landmark or a label moved the
1552                        // keyboard onto the first control inside it, a node the
1553                        // assistive technology could have named itself and did
1554                        // not, and reported success. A node that offers no
1555                        // `Focus` reports the action unhandled instead, which is
1556                        // the honest answer, and so does one whose walk finds
1557                        // nothing focusable: the keyboard is never parked on a
1558                        // node that takes no keys.
1559                        //
1560                        // A node that stands for a focusable composite (an
1561                        // editor's text body, see `Widget::accessibility_proxy`)
1562                        // is the composite to the assistive technology, so the
1563                        // keyboard goes to the composite.
1564                        //
1565                        // A node that is not itself the focus but an item the
1566                        // focus points at (a table cell, a list row, a link in
1567                        // a viewer, a chart's mark: a widget's
1568                        // `active_descendant`) is first offered to the widget
1569                        // that publishes it, which moves its own cursor there
1570                        // and gives itself keyboard focus, as an arrow key
1571                        // would. See `offer_item_focus` for who is asked.
1572                        let synthetic =
1573                            *target_node != crate::accessibility::widget_id_to_node_id(id);
1574                        let takes_focus_itself = !synthetic
1575                            && (self
1576                                .arena
1577                                .get(id)
1578                                .is_some_and(|node| self.is_node_focusable(node))
1579                                || self.focusable_composite_behind(id).is_some());
1580                        // A composite with a Tab stop inside (a `DateEdit`
1581                        // in a card) is no item: the walk below lands on its
1582                        // stop, and no ancestor is asked. A synthetic node is
1583                        // offered only when it advertises `Focus` itself, in
1584                        // the tree the assistive technology was handed.
1585                        let offered = !takes_focus_itself
1586                            && if synthetic {
1587                                self.published_node_advertises_focus(*target_node)
1588                            } else {
1589                                self.advertises_focus_action(id)
1590                                    && self.first_focusable_descendant(id).is_none()
1591                            };
1592                        let focused_before = self.focused;
1593                        let answered = if offered {
1594                            self.offer_item_focus(id, synthetic, &event, &mut *ops)
1595                        } else {
1596                            None
1597                        };
1598                        if let Some(answerer) = answered {
1599                            // Success only when the keyboard is where the
1600                            // item's owner keeps it: focus moved, or it was
1601                            // already on the widget that answered (or inside
1602                            // it), or the item answered for itself, as an
1603                            // option of an open list does while the field it
1604                            // belongs to keeps focus. A handler that answered
1605                            // and moved nothing is no success, and lights no
1606                            // ring on a field the mouse focused.
1607                            let landed = self.focused.is_some_and(|focused| {
1608                                Some(focused) != focused_before
1609                                    || focused == answerer
1610                                    || self.is_descendant_of(focused, answerer)
1611                                    || answerer == id
1612                            });
1613                            if landed {
1614                                // The handler's own `request_focus` declares
1615                                // no modality; the user is navigating, as for
1616                                // the branch below.
1617                                self.focus_origin = Some(crate::focus::FocusOrigin::Accessibility);
1618                                if let Some(visible) =
1619                                    crate::focus::FocusOrigin::Accessibility.focus_visible()
1620                                    && self.focus_visible.get() != visible
1621                                {
1622                                    self.focus_visible.set(visible);
1623                                }
1624                            }
1625                            self.access_action_handled = landed;
1626                        } else if self.advertises_focus_action(id) {
1627                            let target = self
1628                                .focusable_composite_behind(id)
1629                                .or_else(|| self.first_focusable_descendant(id))
1630                                .unwrap_or(id);
1631                            if self.arena.is_enabled(target)
1632                                && self
1633                                    .arena
1634                                    .get(target)
1635                                    .is_some_and(|node| self.is_node_focusable(node))
1636                            {
1637                                // An assistive move, not a scripted one: the
1638                                // user is navigating, so the focus ring appears
1639                                // exactly as it would for a Tab. `Programmatic`,
1640                                // what this used to pass, declares no modality
1641                                // and left a screen-reader user with an
1642                                // invisible focus after any click.
1643                                self.focus_with_origin_ops(
1644                                    target,
1645                                    crate::focus::FocusOrigin::Accessibility,
1646                                    &mut *ops,
1647                                );
1648                                // Focus is serviced here rather than by the
1649                                // widget, so "handled" means the focus actually
1650                                // landed.
1651                                self.access_action_handled = self.focused == Some(target);
1652                            } else {
1653                                // An item whose owner refused it (a day the
1654                                // arrows cannot reach, a row in a disabled
1655                                // view), or a disabled widget: nothing takes
1656                                // keys there.
1657                                self.access_action_handled = false;
1658                            }
1659                        } else {
1660                            self.access_action_handled = false;
1661                        }
1662                    } else if *action == accesskit::Action::ShowContextMenu {
1663                        // A "show context menu" AT action — a screen reader's
1664                        // menu key, or an automation `right_click` /
1665                        // `invoke_action(node, "show_context_menu")` — first
1666                        // offers itself to the node's own `on_access_action`
1667                        // handlers. If none consume it, fall through to the very
1668                        // same machinery a Secondary `PointerDown` drives, so a
1669                        // widget's `.context_menu(..)` factory opens without the
1670                        // caller having to synthesise a right-click. The AT
1671                        // action carries no point, so anchor the menu at the
1672                        // node's centre. Without this, the AT action was a silent
1673                        // no-op for every widget that wires its menu through the
1674                        // factory (i.e. all of them) — see `show_context_menu_for`.
1675                        // Handled = the widget consumed it, or the factory
1676                        // fallback actually opened a menu. A node with neither
1677                        // reports unhandled rather than a silent success.
1678                        self.access_action_handled =
1679                            if self.dispatch_to_widget_returning_handled(id, &event, &mut *ops) {
1680                                true
1681                            } else {
1682                                // Where the keyboard's menu key would start:
1683                                // a data view's row, or the cell or delegate
1684                                // inside it that carries the app's menu.
1685                                let target = self.resolve_context_menu_target(id);
1686                                let position = self.arena.bounds(target).center();
1687                                self.show_context_menu_for(
1688                                    target,
1689                                    position,
1690                                    crate::widget_builder::ContextMenuTrigger::Accessibility,
1691                                    &mut *ops,
1692                                )
1693                            };
1694                    } else {
1695                        // A Click on a control a click does not focus
1696                        // (`focus_on_click(false)`, or nothing focusable up to
1697                        // the root) blurs nothing, as the pointer's does not:
1698                        // the focused field commits what was typed first, so
1699                        // the command sees it. Unless the control is part of
1700                        // that field, or scroll chrome, as for the pointer.
1701                        if *action == accesskit::Action::Click
1702                            && !self.in_scroll_chrome(id)
1703                            && match self.find_focusable_at_or_above(id) {
1704                                Some(focusable) => !self.click_may_focus(focusable),
1705                                None => !self.belongs_to_focused(id),
1706                            }
1707                        {
1708                            self.commit_pending_edit(&mut *ops);
1709                        }
1710                        self.access_action_handled =
1711                            self.dispatch_to_widget_returning_handled(id, &event, &mut *ops);
1712                    }
1713                }
1714            }
1715            WidgetEvent::Gesture { .. } => {
1716                if let Some(target) = self.hovered_id().or(self.focused) {
1717                    self.dispatch_to_widget(target, &event, &mut *ops);
1718                }
1719            }
1720            WidgetEvent::ScrollIntoView { .. }
1721            | WidgetEvent::PointerEnter { .. }
1722            | WidgetEvent::PointerLeave { .. }
1723            | WidgetEvent::FocusGained { .. }
1724            | WidgetEvent::FocusLost => {}
1725        }
1726        // Any intents queued by handlers via `ctx.send_intent(...)`
1727        // are dispatched after the raw event has been handled but
1728        // before commands are flushed, so commands emitted from
1729        // action handlers land on the same tick.
1730        self.drain_pending_intents(&mut *ops);
1731    }
1732
1733    /// Offer an assistive `Focus` on `id`, an item a widget may name as its
1734    /// active descendant, to the widget that owns it; report whether one took
1735    /// it.
1736    ///
1737    /// Addressed, not bubbled: the item's own node, then each ancestor up to
1738    /// and including the first focusable one, which is where a view, a menu or
1739    /// a calendar that keeps keyboard focus sits. An ancestor above that owns
1740    /// nothing in the item, and a catch-all `Focus` handler there (a card
1741    /// selecting itself) must not take it.
1742    ///
1743    /// A greyed item (a menu row the arrows still highlight) takes no input of
1744    /// its own, so the offer starts at its parent. An item inside a disabled
1745    /// container is offered to no one: its owner is disabled with it.
1746    ///
1747    /// Only a widget item is greyed that way. For a synthetic node `id` is its
1748    /// owner (a chart, a web view), and a disabled owner refuses; a disabled
1749    /// composite (a `DateEdit` with its segments) is no item either.
1750    ///
1751    /// Returns the node that answered.
1752    fn offer_item_focus(
1753        &mut self,
1754        id: WidgetId,
1755        synthetic: bool,
1756        event: &WidgetEvent,
1757        ops: &mut dyn crate::window::WindowOps,
1758    ) -> Option<WidgetId> {
1759        let start = if self.arena.is_enabled(id) {
1760            Some(id)
1761        } else {
1762            let greyed_item = !synthetic
1763                && self
1764                    .arena
1765                    .get(id)
1766                    .and_then(|node| node.enabled_state.as_ref())
1767                    .is_some_and(|state| !state.get())
1768                && !self.has_focusable_descendant(id);
1769            self.arena
1770                .parent(id)
1771                .filter(|&parent| greyed_item && self.arena.is_enabled(parent))
1772        };
1773        let mut at = start;
1774        while let Some(node) = at {
1775            if self.dispatch_to_widget_direct_returning_handled(node, event, &mut *ops) {
1776                return Some(node);
1777            }
1778            if self
1779                .arena
1780                .get(node)
1781                .is_some_and(|n| self.is_node_focusable(n))
1782            {
1783                return None;
1784            }
1785            at = self.arena.parent(node);
1786        }
1787        None
1788    }
1789
1790    /// Whether any node below `id` is focusable, Tab stop or not, enabled or
1791    /// not.
1792    fn has_focusable_descendant(&self, id: WidgetId) -> bool {
1793        let mut stack: Vec<WidgetId> = self.arena.children(id).to_vec();
1794        while let Some(node) = stack.pop() {
1795            if self
1796                .arena
1797                .get(node)
1798                .is_some_and(|n| self.is_node_focusable(n))
1799            {
1800                return true;
1801            }
1802            stack.extend_from_slice(self.arena.children(node));
1803        }
1804        false
1805    }
1806
1807    /// Whether the node `node_id` advertises `Focus` in the accessibility
1808    /// tree last built, the one an assistive technology acts on. For a
1809    /// synthetic node, which no widget can be asked about directly.
1810    fn published_node_advertises_focus(&self, node_id: accesskit::NodeId) -> bool {
1811        self.cached_a11y.as_ref().is_some_and(|update| {
1812            update
1813                .nodes
1814                .iter()
1815                .any(|(id, node)| *id == node_id && node.supports_action(accesskit::Action::Focus))
1816        })
1817    }
1818
1819    /// Open the context menu the keyboard just asked for, and report whether
1820    /// one appeared.
1821    ///
1822    /// Targets the focused widget, or whatever its
1823    /// [`context_menu_key_target`](crate::widget::Widget::context_menu_key_target)
1824    /// nominates instead — for a data view, the selected row. Anchors the menu
1825    /// at the target's own bounds rather than at the last pointer position,
1826    /// which may be anywhere on screen or nowhere at all.
1827    ///
1828    /// Returns `false` when nothing on the ancestor chain owns a factory, so
1829    /// the key falls through to normal dispatch and a widget that wants to
1830    /// handle it itself still can.
1831    fn open_context_menu_from_keyboard(&mut self, ops: &mut dyn crate::window::WindowOps) -> bool {
1832        let Some(focused) = self.focused else {
1833            return false;
1834        };
1835        let target = self.resolve_context_menu_target(focused);
1836
1837        // The menu belongs where the thing it is about is. A keyboard user has
1838        // no pointer position, and the stale one is worse than useless: it
1839        // would put the menu over an unrelated part of the window.
1840        let bounds = self.bounds(target);
1841        let anchor = Point {
1842            x: bounds.x + bounds.width / 2.0,
1843            y: bounds.y + bounds.height / 2.0,
1844        };
1845        self.show_context_menu_for(
1846            target,
1847            anchor,
1848            crate::widget_builder::ContextMenuTrigger::Keyboard,
1849            ops,
1850        )
1851    }
1852
1853    /// Follow [`context_menu_key_target`](crate::widget::Widget::context_menu_key_target)
1854    /// from `start` while it names an active node: a view names its current
1855    /// row, the row the delegate (or the cell) inside it, so each widget
1856    /// states only its own next hop. Stops after a few hops, or at a node
1857    /// already passed, on the last good one (a cycle is a widget bug, which
1858    /// a debug build reports).
1859    ///
1860    /// Asked for every node on every accessibility walk (to advertise the
1861    /// action), so it allocates nothing.
1862    pub(super) fn resolve_context_menu_target(&self, start: WidgetId) -> WidgetId {
1863        const MAX_HOPS: usize = 8;
1864        let next_of = |id: WidgetId| {
1865            self.arena
1866                .get(id)
1867                .and_then(|node| node.widget.context_menu_key_target())
1868                .filter(|next| self.arena.is_active(*next))
1869        };
1870        let mut passed = [start; MAX_HOPS + 1];
1871        let mut target = start;
1872        for hop in 0..MAX_HOPS {
1873            let Some(next) = next_of(target) else {
1874                break;
1875            };
1876            if passed[..=hop].contains(&next) {
1877                debug_assert!(
1878                    false,
1879                    "context_menu_key_target cycle through {next:?}: a widget names an ancestor's target"
1880                );
1881                break;
1882            }
1883            passed[hop + 1] = next;
1884            target = next;
1885        }
1886        target
1887    }
1888
1889    /// Ask the factories from `target` up for a menu, and mount the first one
1890    /// offered at `position`.
1891    ///
1892    /// The closest claimer wins: at each node the factory is asked first,
1893    /// and a node whose factory declines (or that has none) but carries a
1894    /// [contribution](crate::widget_builder::ContextMenuContribution) claims
1895    /// the menu with that section alone. Then the contributions on the owner
1896    /// and above it, up to (and excluding) the first focusable node above it,
1897    /// are appended to the menu, innermost first, unless the owner is itself
1898    /// a focusable control. So a contribution on a data view itself (which is
1899    /// focusable) is never merged into its rows' menus.
1900    ///
1901    /// `trigger` reaches each factory through
1902    /// [`EventContext::context_menu_trigger`](crate::widget::EventContext::context_menu_trigger):
1903    /// only a pointer's `position` is a place the user chose, and a factory
1904    /// that moves a caret to it on a keyboard request writes the menu's Paste
1905    /// into the middle of the text.
1906    pub(super) fn show_context_menu_for(
1907        &mut self,
1908        target: WidgetId,
1909        position: Point,
1910        trigger: crate::widget_builder::ContextMenuTrigger,
1911        ops: &mut dyn crate::window::WindowOps,
1912    ) -> bool {
1913        // Walks up the parent chain calling each factory in turn. A
1914        // factory returning `Some(menu)` claims the click and mounts;
1915        // a factory returning `None` declines and the walk continues.
1916        // No factory anywhere on the chain → fall through to whatever
1917        // the caller does with the unconsumed PointerDown.
1918        let mut ctx = self.make_event_context(&mut *ops);
1919        ctx.context_menu_trigger = Some(trigger);
1920        let mut walker = Some(target);
1921        // The owner, its menu, and whether a factory made it (rather than a
1922        // contribution standing in for one).
1923        let mut menu_decision: Option<(WidgetId, Box<dyn Widget>, bool)> = None;
1924        while let Some(id) = walker {
1925            let Some(node) = self.arena.get(id) else {
1926                break;
1927            };
1928            // Invoke the factory with the click position and a real
1929            // EventContext. The factory is `Fn`, so it is called through an
1930            // immutable borrow on the node; `ctx` is a local whose
1931            // `&mut WindowOps` is disjoint from `self.arena`.
1932            if let Some(factory) = node.context_menu_factory.as_ref()
1933                && let Some(menu) = factory(position, &mut ctx)
1934            {
1935                menu_decision = Some((id, menu, true));
1936                break;
1937            }
1938            // No factory claimed here: a contribution on this node is the
1939            // closest offer, mounted as the menu.
1940            if let Some(contribution) = node.context_menu_contribution.as_ref()
1941                && let Some(section) = contribution(&mut ctx)
1942            {
1943                menu_decision = Some((id, section, false));
1944                break;
1945            }
1946            walker = node.parent;
1947        }
1948
1949        // The sections the owner and the nodes above it add, innermost first,
1950        // up to the first focusable node above the owner (a data view: a view
1951        // nested in another view's row adds only its own). A menu a focusable
1952        // control owns (a text field, a cell editor) is about that control
1953        // and gains none.
1954        if let Some((owner_id, menu, by_factory)) = menu_decision.as_mut() {
1955            let sealed = *by_factory && self.is_focusable_control(*owner_id);
1956            if !sealed {
1957                // A contribution that claimed the menu already gave its
1958                // section; its node's is not asked again.
1959                let mut probe = if *by_factory {
1960                    Some(*owner_id)
1961                } else {
1962                    self.arena.get(*owner_id).and_then(|node| node.parent)
1963                };
1964                while let Some(id) = probe {
1965                    let Some(node) = self.arena.get(id) else {
1966                        break;
1967                    };
1968                    if id != *owner_id && self.is_focusable_control(id) {
1969                        break;
1970                    }
1971                    if let Some(contribution) = node.context_menu_contribution.as_ref()
1972                        && let Some(section) = contribution(&mut ctx)
1973                        && menu.append_context_menu_section(section).is_err()
1974                    {
1975                        note_refused_section(*owner_id);
1976                    }
1977                    probe = node.parent;
1978                }
1979            }
1980        }
1981        let menu_decision = menu_decision.map(|(owner, menu, _)| (owner, menu));
1982
1983        // Drain ctx side effects regardless of whether a menu showed —
1984        // a factory that returns `None` may still have queued intents,
1985        // updated signals, or requested a frame. With no menu, they start
1986        // where the menu was asked for, so every factory the walk called
1987        // (each one an ancestor of `target`) is on their way to the root.
1988        let drain_anchor = menu_decision.as_ref().map(|(id, _)| *id).unwrap_or(target);
1989        self.collect_from_ctx(ctx, drain_anchor);
1990
1991        let Some((owner_id, menu_widget)) = menu_decision else {
1992            return false;
1993        };
1994
1995        // Clear stale transient overlays (other menus / popovers) before mounting
1996        // the new menu, but KEEP any overlay that *contains* the right-clicked
1997        // widget — otherwise a right-click inside a modal editor would tear down
1998        // the modal it lives in (dismiss_all did exactly that). The context menu
1999        // then mounts on top of its host overlay.
2000        let keep: std::collections::HashSet<WidgetId> = self
2001            .overlay_manager
2002            .stack
2003            .iter()
2004            .map(|o| o.content_id)
2005            .filter(|&content_id| self.is_descendant_of(owner_id, content_id))
2006            .collect();
2007        let dismissed = self.overlay_manager.dismiss_except(&keep);
2008        self.dormant_dismissed_content(&dismissed, &mut *ops);
2009
2010        let content_id = self.add_boxed(menu_widget);
2011        let prev_focus = self.focused;
2012        // One branch, every menu: a coarse pointer gets a placement that keeps
2013        // clear of its own contact patch, everything else the historical
2014        // `AtPointer`. A point-anchored panel that puts its own corner under
2015        // the finger is the defect this exists to fix, and it is invisible from
2016        // a mouse — which is why the decision lives in
2017        // `OverlayPlacement::at_pointer_for` rather than at each call site.
2018        let placement =
2019            crate::overlay::OverlayPlacement::at_pointer_for(position, &self.current_input.pointer);
2020        // The factory built this menu for this opening alone: it is destroyed
2021        // once the menu closes, rather than parked forever.
2022        let mut request = crate::overlay::OverlayRequest::new(
2023            content_id,
2024            owner_id,
2025            placement,
2026            crate::overlay::DismissBehavior::EscapeOrClickOutside,
2027        );
2028        request.destroy_content_on_dismiss = true;
2029        self.overlay_manager.show(request);
2030        if let Some(focus_id) = prev_focus {
2031            self.record_top_focus_restore(focus_id);
2032        }
2033        // Opened without pointing (a key, a screen reader's action): the
2034        // keyboard drives the menu, so the modality is the keyboard's, and
2035        // a menu highlights its first row on arrival as it does from a key.
2036        if trigger != crate::widget_builder::ContextMenuTrigger::Pointer
2037            && !self.focus_visible.get()
2038        {
2039            self.focus_visible.set(true);
2040        }
2041        self.focus_ops(content_id, &mut *ops);
2042        // Flush intents the factory queued so they take effect on the
2043        // same dispatch tick as the menu mount. The caller's
2044        // PointerDown handler returns after we return `true`, skipping
2045        // its own drain — fire ours here.
2046        self.drain_pending_intents(&mut *ops);
2047        true
2048    }
2049
2050    /// Whether `id` is a control that takes focus itself: a focusable node,
2051    /// a composite whose root stands for a focusable inner leaf through its
2052    /// accessibility proxy (a `SpinBox`, a `DateEdit`, a `TimeEdit`, whose
2053    /// root is not focusable), or a body a focusable composite stands for.
2054    fn is_focusable_control(&self, id: WidgetId) -> bool {
2055        let focusable = |id: WidgetId| {
2056            self.arena
2057                .get(id)
2058                .is_some_and(|node| self.is_node_focusable(node))
2059        };
2060        if focusable(id) || self.focusable_composite_behind(id).is_some() {
2061            return true;
2062        }
2063        let mut current = id;
2064        for _ in 0..8 {
2065            let Some(proxy) = self.live_accessibility_proxy(current) else {
2066                return false;
2067            };
2068            if focusable(proxy) {
2069                return true;
2070            }
2071            current = proxy;
2072        }
2073        false
2074    }
2075
2076    // -----------------------------------------------------------------
2077    // Outside-press overlay dismissal
2078    // -----------------------------------------------------------------
2079
2080    /// Handle a press that lands outside one or more dismissable overlays.
2081    ///
2082    /// Returns `true` when the press is consumed and must not reach the tree.
2083    ///
2084    /// **An indirect pointer is unchanged.** It dismisses on the press and
2085    /// falls through, so one click still closes a menu and actuates the control
2086    /// beneath — deliberate behaviour for a cursor, which names one pixel that
2087    /// the user could see the whole time they were aiming at it.
2088    ///
2089    /// **A direct pointer arms instead.** A finger covers what it is about to
2090    /// actuate: the menu is the only thing the user was looking at, and the
2091    /// control underneath is one they never saw. So the `Down` is withheld from
2092    /// the tree, the dismissal waits for the release, and a press that is
2093    /// cancelled — or slid onto the very overlay it would have closed — leaves
2094    /// nothing behind at all. Both the arming `Down` and the committing `Up`
2095    /// are consumed, so nothing beneath ever sees half a press.
2096    fn arm_outside_press_dismissal(
2097        &mut self,
2098        position: Point,
2099        button: PointerButton,
2100        ops: &mut dyn crate::window::WindowOps,
2101    ) -> bool {
2102        self.prune_stale_dismiss_arms();
2103        let pressing = self.current_input.pointer;
2104        let busy = self.busy_press_points(pressing.id);
2105
2106        if pressing.kind.is_direct() {
2107            return self
2108                .overlay_manager
2109                .arm_dismiss(pressing.id, position, &busy)
2110                .suppress_beneath;
2111        }
2112
2113        let mark = self.dismissal_mark();
2114        let (dismissed, focus_restore, toggle_anchors) = self
2115            .overlay_manager
2116            .dismiss_outside_press_toggles(position, &busy);
2117        if dismissed.is_empty() {
2118            return false;
2119        }
2120        self.dormant_dismissed_content(&dismissed, &mut *ops);
2121        self.return_focus_after_dismissal(focus_restore, mark, &mut *ops);
2122        // The press dismissed one or more overlays. By default it
2123        // now ALSO falls through to the widget under the cursor,
2124        // so a single click both closes the menu/popover and
2125        // activates the control beneath. The one case swallowed: a
2126        // press on the anchor of a click-opened overlay, with a
2127        // button the anchor's tap answers to, because that tap
2128        // would otherwise reopen the overlay this very press just
2129        // dismissed (click-the-trigger-to-close). A primary press
2130        // is always taken for the toggle, as it always was; any
2131        // other button only where the trigger opens on it, so a
2132        // right click on a left-click trigger still dismisses and
2133        // falls through to the trigger's context menu.
2134        toggle_anchors
2135            .iter()
2136            .any(|&toggle| self.press_reopens(toggle, position, button, &pressing))
2137    }
2138
2139    /// Whether a press at `position` that has just dismissed the overlay
2140    /// anchored on `toggle` would open it again, and so is taken for the
2141    /// toggle rather than falling through.
2142    ///
2143    /// A popover's anchor is its trigger: a press anywhere on it is taken, a
2144    /// primary one always and any other where the trigger opens on it. A
2145    /// modal's anchor is whatever presented it, which may be the whole page
2146    /// (an app that presents a card from its root), so a press inside it is
2147    /// taken only when the anchor is the first widget on its way up that
2148    /// answers the button: the dialog's own opener is, a list row on the
2149    /// page that presented a card is not, and gets the click.
2150    fn press_reopens(
2151        &self,
2152        toggle: crate::overlay::ToggleAnchor,
2153        position: Point,
2154        button: PointerButton,
2155        pointer: &crate::pointer::PointerInfo,
2156    ) -> bool {
2157        let anchor = toggle.anchor;
2158        if !self.arena.is_active(anchor) || !self.arena.bounds(anchor).contains(position) {
2159            return false;
2160        }
2161        if toggle.modal {
2162            return self.first_tapper(position, button, pointer) == Some(anchor);
2163        }
2164        button == PointerButton::Primary
2165            || self
2166                .anchor_tap_buttons(anchor, position, pointer)
2167                .contains(button)
2168    }
2169
2170    /// The first widget at or above the one hit at `position` whose tap
2171    /// answers `button`: the one a click there would activate.
2172    fn first_tapper(
2173        &self,
2174        position: Point,
2175        button: PointerButton,
2176        pointer: &crate::pointer::PointerInfo,
2177    ) -> Option<WidgetId> {
2178        let mut node = self.hit_test_for(position, pointer);
2179        while let Some(id) = node {
2180            if self.tap_buttons(id).contains(button) {
2181                return Some(id);
2182            }
2183            node = self.arena.parent(id);
2184        }
2185        None
2186    }
2187
2188    /// The buttons a tap at `position` would be recognized for on its way up
2189    /// to `anchor`: the union of the tap masks of every node from the one hit
2190    /// at `position` up to and including `anchor`.
2191    ///
2192    /// An anchor is often not the node carrying the tap. A popover anchors on
2193    /// its own wrapper, and the opener sits on the trigger inside it, or on a
2194    /// control inside that; any of them answering to the button means the
2195    /// press would reach an opener. [`ButtonMask::NONE`] when the node hit is
2196    /// not inside `anchor` at all.
2197    fn anchor_tap_buttons(
2198        &self,
2199        anchor: WidgetId,
2200        position: Point,
2201        pointer: &crate::pointer::PointerInfo,
2202    ) -> ButtonMask {
2203        let mut mask = ButtonMask::NONE;
2204        let mut node = self.hit_test_for(position, pointer);
2205        while let Some(id) = node {
2206            mask = mask.union(self.tap_buttons(id));
2207            if id == anchor {
2208                return mask;
2209            }
2210            node = self.arena.parent(id);
2211        }
2212        ButtonMask::NONE
2213    }
2214
2215    /// Complete a direct pointer's armed dismissal on its release.
2216    ///
2217    /// Returns `true` when this pointer held an arm — in which case the `Up` is
2218    /// consumed whether or not anything actually closed. Nothing beneath saw
2219    /// the `Down`, so delivering the `Up` alone would hand a widget the second
2220    /// half of a press it never started.
2221    fn commit_outside_press_dismissal(
2222        &mut self,
2223        position: Point,
2224        ops: &mut dyn crate::window::WindowOps,
2225    ) -> bool {
2226        let pointer = self.current_pointer_id();
2227        if !self.overlay_manager.has_armed_dismiss(pointer) {
2228            return false;
2229        }
2230        let mark = self.dismissal_mark();
2231        let (dismissed, focus_restore, _anchors) =
2232            self.overlay_manager.commit_dismiss(pointer, position);
2233        if !dismissed.is_empty() {
2234            self.dormant_dismissed_content(&dismissed, &mut *ops);
2235            self.return_focus_after_dismissal(focus_restore, mark, &mut *ops);
2236        }
2237        true
2238    }
2239
2240    /// Where every *other* live pointer is holding a press.
2241    ///
2242    /// A press is only "outside" relative to the overlays nobody else is
2243    /// working in — see
2244    /// [`OverlayManager::dismiss_outside_press`](crate::overlay::OverlayManager::dismiss_outside_press).
2245    /// Liveness is judged with
2246    /// [`press_is_revocable`](Self::press_is_revocable), the predicate the
2247    /// cancel funnel already uses, and for the same reason: a pointer with
2248    /// neither a sequence nor a capture has no interaction that could be taken
2249    /// away, so it has none to protect either. That also exempts a pointer
2250    /// inside its terminal `Up` — its sequence is still installed but already
2251    /// terminating — which is what lets a menu item's own handler close its
2252    /// menu while a second contact rests elsewhere.
2253    ///
2254    /// The *press* position, not the current one: a contact that grabbed a
2255    /// menu and dragged past its edge is still manipulating that menu.
2256    fn busy_press_points(&self, exclude: crate::pointer::PointerId) -> Vec<Point> {
2257        self.pointers
2258            .iter()
2259            .filter(|entry| entry.info.id != exclude)
2260            .filter(|entry| self.press_is_revocable(entry.info.id))
2261            .map(|entry| entry.down_position)
2262            .collect()
2263    }
2264
2265    /// Drop arms whose contact is gone.
2266    ///
2267    /// An arm is normally retired by its own `Up` or `Cancel`. A contact that
2268    /// disappears without either — a table sweep, a window losing its input —
2269    /// would otherwise leave one behind, and a later contact minted with the
2270    /// same id would inherit a dismissal it never asked for.
2271    fn prune_stale_dismiss_arms(&mut self) {
2272        let stale: Vec<crate::pointer::PointerId> = self
2273            .overlay_manager
2274            .armed_pointers()
2275            .into_iter()
2276            .filter(|id| self.pointers.get(*id).is_none())
2277            .collect();
2278        for id in stale {
2279            self.overlay_manager.abort_dismiss(id);
2280        }
2281    }
2282
2283    // -----------------------------------------------------------------
2284    // Press state
2285    // -----------------------------------------------------------------
2286
2287    /// Open the press record for the contact being dispatched.
2288    ///
2289    /// Called from the `PointerDown` arm before the press is dispatched, with
2290    /// the focusable the press landed on (which a direct pointer will hold
2291    /// until its release). The node whose visual the record drives is not
2292    /// known yet — the arena claims the press during the dispatch — so
2293    /// [`adopt_press_owner`](Self::adopt_press_owner) finishes the record
2294    /// afterwards.
2295    ///
2296    /// The press-feedback delay applies **only inside a pan claimant**: a
2297    /// finger resting on a list row must not flash the row before the pan has
2298    /// been ruled out, while a button that nothing can scroll has no ambiguity
2299    /// to wait out and highlights at once. `begin_pan` has already decided
2300    /// whether this press is inside one — a session exists only when a claimant
2301    /// along the hit path accepts this pointer kind — so this reads its answer
2302    /// rather than re-deriving it.
2303    fn begin_press(&mut self, focusable: Option<WidgetId>) {
2304        let pointer = self.current_pointer_id();
2305        let now = self.sequence_now();
2306        let delay = self
2307            .pan_session_open(pointer)
2308            .then(|| self.current_profile().press_feedback_delay)
2309            .filter(|d| !d.is_zero());
2310        self.presses.press(pointer, focusable, now, delay);
2311    }
2312
2313    /// Record the node whose gesture arena took this press, and publish its
2314    /// signal.
2315    ///
2316    /// The owner is the sequence's `pressed_owner` — the node holding the
2317    /// pointer capture once the `Down` has been dispatched, which is exactly
2318    /// the node whose `on_tap` would fire. A press no arena took owns no
2319    /// visual, and its record stays for the focus deferral alone.
2320    ///
2321    /// So does a press on a **button the owner cannot act on**. A press visual
2322    /// says "release here and this control acts", so it has to answer to the
2323    /// same buttons the activation does: the router opens a record for every
2324    /// button, but only [`press_buttons`](Self::press_buttons) — the union of
2325    /// the owner's own click-style [`ButtonMask`]s,
2326    /// `PRIMARY` unless the widget widened it — decides which of them may light
2327    /// the control up. Without the gate a middle-click, or a right-click on a
2328    /// node with no context menu, would raise a press that can never complete;
2329    /// with it, the visual and the activation agree by construction, exactly as
2330    /// they do at the tap boundary where one predicate fails the tap, fires
2331    /// `cancel_taps` and clears the visual.
2332    ///
2333    /// The record itself is untouched either way, so the focus a direct
2334    /// pointer deferred to its release is still there to be assigned.
2335    fn adopt_press_owner(&mut self, button: PointerButton) {
2336        let pointer = self.current_pointer_id();
2337        let Some(owner) = self.current_sequence().and_then(|s| s.pressed_owner()) else {
2338            return;
2339        };
2340        if !self.press_buttons(owner).contains(button) {
2341            crate::trace_input!(
2342                Samples,
2343                "no press visual for {owner:?}: {button:?} is not one of its accepted buttons"
2344            );
2345            return;
2346        }
2347        self.presses.set_owner(pointer, owner);
2348        self.publish_pressed(owner);
2349    }
2350
2351    /// Re-evaluate the press being dispatched against `position`.
2352    ///
2353    /// Three ways a press visual changes without a release:
2354    ///
2355    /// * the pointer left the press's [`TapBoundary`](crate::gesture::TapBoundary)
2356    ///   — the same predicate that fails the tap and fires `cancel_taps`, so
2357    ///   the visual and the activation are abandoned together;
2358    /// * it came back inside, which restores the visual: WCAG 2.2 SC 2.5.2's
2359    ///   abort gesture is reversible right up to the release;
2360    /// * the arbitration decided for somebody else — a pan claimant, an
2361    ///   ancestor drag — and the pressed control has lost the press without
2362    ///   ever seeing a release.
2363    fn update_press(&mut self, position: Point) {
2364        let pointer = self.current_pointer_id();
2365        if self.presses.get(pointer).is_none() {
2366            return;
2367        }
2368        // A peer claim ends the press outright: the node was never told, and
2369        // leaving its visual up would advertise an interaction it has lost.
2370        let claimed_elsewhere = self.current_sequence().is_some_and(|sequence| {
2371            sequence
2372                .winner()
2373                .is_some_and(|winner| Some(winner) != sequence.pressed_owner())
2374        });
2375        if claimed_elsewhere {
2376            self.end_press(pointer);
2377            return;
2378        }
2379        let profile = self.current_profile();
2380        let origin = self.current_sequence().map(|s| s.press_origin());
2381        let owner = self.presses.get(pointer).and_then(|p| p.owner);
2382        let inside = match (origin, owner) {
2383            (Some(origin), Some(owner)) => {
2384                let bounds = self
2385                    .arena
2386                    .is_active(owner)
2387                    .then(|| self.arena.bounds(owner));
2388                !crate::gesture::TapBoundary::for_pointer(&self.current_input.pointer, &profile)
2389                    .left(origin, position, bounds, &profile)
2390            }
2391            // No sequence to measure from, or no owner to measure against:
2392            // there is no visual either way, so the flag is moot.
2393            _ => true,
2394        };
2395        let Some(press) = self.presses.get_mut(pointer) else {
2396            return;
2397        };
2398        if press.inside == inside {
2399            return;
2400        }
2401        press.inside = inside;
2402        if let Some(owner) = owner {
2403            self.publish_pressed(owner);
2404        }
2405    }
2406
2407    /// Close the press held by `pointer` and republish the node it drove.
2408    ///
2409    /// The one exit: a release, a cancel, and a peer claim all come through
2410    /// here, so a node can never be left painted as pressed by a path that
2411    /// forgot to clear it.
2412    pub(crate) fn end_press(&mut self, pointer: crate::pointer::PointerId) {
2413        if let Some(owner) = self.presses.release(pointer) {
2414            self.publish_pressed(owner);
2415        }
2416    }
2417
2418    /// Resolve every elapsed press-feedback delay and publish the visuals that
2419    /// just appeared. Driven by the same tick that advances the long press.
2420    pub(crate) fn resolve_press_delays(&mut self, now: crate::pointer::EventTime) {
2421        if self.presses.is_empty() {
2422            return;
2423        }
2424        for id in self.presses.resolve_delays(now) {
2425            self.publish_pressed(id);
2426            self.arena.mark_needs_paint(id);
2427        }
2428    }
2429
2430    /// The earliest instant a pending press wants the event loop back, so a
2431    /// finger that lands and does not move still gets its highlight.
2432    pub(crate) fn next_press_deadline(&self) -> Option<std::time::Instant> {
2433        self.presses.next_deadline().map(|t| self.instant_for(t))
2434    }
2435
2436    /// The click about to be dispatched (by a pointer, or an
2437    /// assistive-technology Click) lands on a control that takes no
2438    /// focus from it (built with `focus_on_click(false)`, or not focusable at
2439    /// all), so it blurs nothing: have the focused widget, and each
2440    /// of its ancestors, commit the edit it holds
2441    /// ([`on_commit_edit`](crate::widget_builder::HandlerSet::on_commit_edit)),
2442    /// innermost first, as a blur would have made it, so that the command
2443    /// the click runs sees the value typed (AppKit's `commitEditing`).
2444    ///
2445    /// The ancestors are those of an intent's walk from the focused widget
2446    /// ([`intent_walk`](Self::intent_walk)): from a popup on to the widget it
2447    /// is attached to, and no further than an open modal. The widgets that
2448    /// commit are the ones whose actions the command can reach; a form whose
2449    /// field is edited in a popover attached to it commits, and the page
2450    /// behind a dialog does not.
2451    pub(crate) fn commit_pending_edit(&mut self, ops: &mut dyn crate::window::WindowOps) {
2452        let Some(focus) = self.focused.filter(|id| self.arena.is_active(*id)) else {
2453            return;
2454        };
2455        let (chain, _, _) = self.intent_walk(focus, &[]);
2456        for id in chain {
2457            for external in [true, false] {
2458                let handler = self.arena.get_mut(id).and_then(|node| {
2459                    let handlers = if external {
2460                        &mut node.external_handlers
2461                    } else {
2462                        &mut node.handlers
2463                    };
2464                    handlers.on_commit_edit.take()
2465                });
2466                let Some(mut handler) = handler else { continue };
2467                let mut ctx = self
2468                    .make_event_context(&mut *ops)
2469                    .with_dispatch_node(id)
2470                    .with_content_language(self.content_language(id));
2471                handler(&mut ctx);
2472                if let Some(node) = self.arena.get_mut(id) {
2473                    let handlers = if external {
2474                        &mut node.external_handlers
2475                    } else {
2476                        &mut node.handlers
2477                    };
2478                    // A rebuild the commit caused installed a new one: keep it.
2479                    if handlers.on_commit_edit.is_none() {
2480                        handlers.on_commit_edit = Some(handler);
2481                    }
2482                }
2483                self.collect_from_ctx(ctx, id);
2484            }
2485        }
2486    }
2487
2488    /// Whether the release at `position` with `button` completes a tap on a
2489    /// control that takes no focus at all, from the press to the root (a
2490    /// `focusable(false)` icon, a plain `on_tap` node): the click runs that
2491    /// control's command, and the focused field commits first, as for a
2492    /// control built with `focus_on_click(false)`.
2493    ///
2494    /// The press must have been taken by a node whose `on_tap` answers the
2495    /// button, and must end inside the tap boundary the tap recognizer
2496    /// measures: a hover, a scroll, a press on empty background (no node took
2497    /// it, nothing runs, focus does not move, so nothing has to be committed,
2498    /// as a native line edit commits only when focus leaves it or a command
2499    /// runs), a drag or a swipe that took the press, and a press dragged off
2500    /// commit nothing. Nor does a tap on the focused widget's own parts
2501    /// ([`belongs_to_focused`](Self::belongs_to_focused)): its scroll bar, or
2502    /// a popup attached to it, act within the edit. Nor one on scroll chrome
2503    /// ([`in_scroll_chrome`](Self::in_scroll_chrome)): another view's scroll
2504    /// bar moves that view and runs no command.
2505    ///
2506    /// Read before the sequence ends, since the tap boundary is measured from
2507    /// the press origin it holds.
2508    fn release_taps_unfocusable(&self, position: Point, button: PointerButton) -> bool {
2509        let Some(press) = self.presses.get(self.current_pointer_id()) else {
2510            return false;
2511        };
2512        let Some(owner) = press.owner.filter(|_| press.focusable.is_none()) else {
2513            return false;
2514        };
2515        if !self.arena.is_active(owner) || !self.tap_buttons(owner).contains(button) {
2516            return false;
2517        }
2518        let Some(sequence) = self.current_sequence() else {
2519            return false;
2520        };
2521        // Any winner ends the tap: a peer that claimed the press (an
2522        // ancestor's drag, a pan), or the owner's own drag or swipe. An
2523        // explicit capture the owner made (a raw member) decides without
2524        // recognizing anything, and its tap may still follow.
2525        if let Some(winner) = sequence.winner()
2526            && (winner != owner
2527                || sequence.members().iter().any(|member| {
2528                    member.id == winner
2529                        && matches!(member.role, crate::gesture::MemberRole::Gesture)
2530                }))
2531        {
2532            return false;
2533        }
2534        let profile = self.current_profile();
2535        let left = crate::gesture::TapBoundary::for_pointer(&self.current_input.pointer, &profile)
2536            .left(
2537                sequence.press_origin(),
2538                position,
2539                Some(self.arena.bounds(owner)),
2540                &profile,
2541            );
2542        !left && !self.in_scroll_chrome(owner) && !self.belongs_to_focused(owner)
2543    }
2544
2545    /// Whether `id` is in a subtree marked
2546    /// [`scroll_chrome`](crate::widget_builder::HandlerSet::scroll_chrome): a
2547    /// scroll bar, a tab strip's scroll arrows. A click there scrolls and runs
2548    /// no command, so the focused field commits nothing for it.
2549    fn in_scroll_chrome(&self, id: WidgetId) -> bool {
2550        let mut current = Some(id);
2551        while let Some(node) = current {
2552            if self.arena.get(node).is_some_and(|n| n.scroll_chrome) {
2553                return true;
2554            }
2555            current = self.arena.parent(node);
2556        }
2557        false
2558    }
2559
2560    /// Whether `id` is part of the focused widget: in its subtree, or in a
2561    /// popup attached to it or to a widget of its subtree (its completion or
2562    /// candidate list, its context menu), which an intent's walk from `id`
2563    /// crosses back to it ([`intent_walk`](Self::intent_walk)).
2564    fn belongs_to_focused(&self, id: WidgetId) -> bool {
2565        self.focused
2566            .is_some_and(|focus| self.intent_walk(id, &[]).0.contains(&focus))
2567    }
2568
2569    /// Whether a click or a tap may move focus to `focusable`, the focusable
2570    /// widget it landed on or in: false when that widget was built with
2571    /// [`focus_on_click(false)`](crate::widget_builder::HandlerSet::focus_on_click),
2572    /// which a pointer activates without focusing. Asked of that one node, as
2573    /// GTK's `focus-on-click` is, so a text field inside a toolbar built with
2574    /// the flag still takes focus; a composite whose focusable node is a child
2575    /// of its own forwards the flag to it.
2576    fn click_may_focus(&self, focusable: WidgetId) -> bool {
2577        self.arena
2578            .get(focusable)
2579            .is_none_or(|node| node.focus_on_click)
2580    }
2581
2582    /// Assign the focus a direct pointer's press deferred, if the release
2583    /// earned it.
2584    ///
2585    /// The guard is "the release landed on the same focusable as the press".
2586    /// A finger that presses a button, slides onto its neighbour and lifts has
2587    /// activated nothing and must move focus nowhere — the same rule the tap
2588    /// recognizer applies to activation, applied to focus so the two cannot
2589    /// disagree. A press that found no focusable defers nothing.
2590    ///
2591    /// For a widget built with `focus_on_click(false)` it moves no focus and
2592    /// has the focused widget commit its pending edit instead
2593    /// ([`commit_pending_edit`](Self::commit_pending_edit)), under the same
2594    /// guard and for every pointer, a mouse included: a press dragged off or
2595    /// cancelled has run no command, so nothing is committed for it, and
2596    /// neither is a click on scroll chrome
2597    /// ([`in_scroll_chrome`](Self::in_scroll_chrome)), which only scrolls.
2598    /// Otherwise a no-op for an indirect pointer, which focused at press.
2599    ///
2600    /// A press that found no focusable at all commits the same way when
2601    /// `taps_unfocusable` says its release completes a tap
2602    /// ([`release_taps_unfocusable`](Self::release_taps_unfocusable)): a
2603    /// toolbar icon built without focus runs its command as one built with
2604    /// `focus_on_click(false)` does.
2605    fn focus_on_release(
2606        &mut self,
2607        position: Point,
2608        taps_unfocusable: bool,
2609        ops: &mut dyn crate::window::WindowOps,
2610    ) {
2611        if taps_unfocusable {
2612            self.commit_pending_edit(&mut *ops);
2613            return;
2614        }
2615        let releasing = self.current_input.pointer;
2616        let pointer = self.current_pointer_id();
2617        let Some(pressed) = self.presses.get(pointer).and_then(|p| p.focusable) else {
2618            return;
2619        };
2620        if !releasing.kind.is_direct() && self.click_may_focus(pressed) {
2621            return;
2622        }
2623        let Some(target) = self.hit_test_for(position, &releasing) else {
2624            return;
2625        };
2626        if self.find_focusable_at_or_above(target) != Some(pressed) {
2627            return;
2628        }
2629        if !self.click_may_focus(pressed) {
2630            // Scroll chrome built this way (a tab strip's scroll arrows)
2631            // scrolls and runs no command: nothing to commit for.
2632            if !self.in_scroll_chrome(target) {
2633                self.commit_pending_edit(&mut *ops);
2634            }
2635        } else {
2636            self.focus_with_origin_ops(
2637                pressed,
2638                crate::focus::FocusOrigin::Pointer(releasing.kind),
2639                &mut *ops,
2640            );
2641        }
2642    }
2643
2644    /// The hover walk for one move: hit-test, run the enter/leave transitions,
2645    /// then deliver `event` to whatever the pointer is now over.
2646    ///
2647    /// `event` is the `PointerMove` being dispatched and is forwarded
2648    /// **verbatim** — its `modifiers` (a Shift or Ctrl pressed mid-drag) and its
2649    /// `pointer` are the producer's own, not a copy assembled here. `position`
2650    /// is that event's position, passed separately only because every step below
2651    /// needs it.
2652    ///
2653    /// Which is the rule for the whole router: a producer's event reaches the
2654    /// widget carrying what the producer said, while an event the *tree*
2655    /// synthesizes — the enter/leave pair below — carries the tree's own view of
2656    /// who is pointing, read from the pointer table. The two differ only for a
2657    /// hand-built legacy event, which names no time and is stamped from the tree
2658    /// clock into the snapshot [`EventContext::pointer`] reports (see
2659    /// [`dispatch_event_with_ops`](Self::dispatch_event_with_ops)) without that
2660    /// stamp being written back onto the event.
2661    ///
2662    /// [`EventContext::pointer`]: crate::widget::EventContext::pointer
2663    fn handle_pointer_move(
2664        &mut self,
2665        event: &WidgetEvent,
2666        position: Point,
2667        ops: &mut dyn crate::window::WindowOps,
2668    ) {
2669        // A contact routes its move by hit test but writes **no hover**: a
2670        // finger has no hover state, so a second finger arriving beside a
2671        // hovering mouse must leave enter/leave, the cursor, tooltip dwell and
2672        // every `on_hover` handler exactly where they were.
2673        let moving = self.current_input.pointer;
2674        if self.pointers.hover_owner_id() != Some(self.current_pointer_id()) {
2675            if let Some(target) = self.hit_test_for(position, &moving) {
2676                self.dispatch_to_widget(target, event, &mut *ops);
2677            }
2678            return;
2679        }
2680        let target = self.hit_test_for(position, &moving);
2681
2682        if target != self.hovered_id() {
2683            // Past the gate above, so the mover *is* the hover owner.
2684            let hover = self.hover_transition_pointer();
2685            let previously_hovered = self.hovered_id();
2686            if let Some(old) = previously_hovered {
2687                self.dispatch_to_widget(
2688                    old,
2689                    &WidgetEvent::PointerLeave { pointer: hover },
2690                    &mut *ops,
2691                );
2692                self.tooltip_pointer_leave(old, &mut *ops);
2693            }
2694            if let Some(new) = target {
2695                self.dispatch_to_widget(
2696                    new,
2697                    &WidgetEvent::PointerEnter { pointer: hover },
2698                    &mut *ops,
2699                );
2700                self.tooltip_pointer_enter(new);
2701            }
2702            // A pointer that goes to another widget, or to nothing, has left
2703            // the one the press answered for: its next hover is a new one.
2704            self.tooltip_dwell_held = false;
2705            self.set_hovered(target);
2706            self.update_hover_within_signals(previously_hovered, target);
2707        } else if let Some(target) = target {
2708            // Same hover target — restart pending tooltip timers if the
2709            // pointer is still moving beyond the stationary slop.
2710            self.tooltip_pointer_moved(target, position);
2711        }
2712
2713        if let Some(target) = target {
2714            self.dispatch_to_widget(target, event, &mut *ops);
2715        }
2716    }
2717
2718    pub(super) fn dispatch_to_widget(
2719        &mut self,
2720        target: WidgetId,
2721        event: &WidgetEvent,
2722        ops: &mut dyn crate::window::WindowOps,
2723    ) {
2724        self.dispatch_to_widget_returning_handled(target, event, ops);
2725    }
2726
2727    /// Rebuild `event` with any pointer position converted into `id`'s
2728    /// **widget-local** space. Returns `None` for events that carry no
2729    /// position, so the caller keeps the original event.
2730    ///
2731    /// This is the single point where the framework localizes pointer
2732    /// coordinates. It runs once per node in both the preview and bubble
2733    /// passes, and because both `on_pointer_event` and the gesture arena
2734    /// read the position out of `event`, localizing it here makes
2735    /// `on_tap` / `on_double_tap` / `on_long_press` / `on_drag` and
2736    /// `on_pointer_event` all receive widget-local coordinates uniformly.
2737    /// See [`WidgetArena::local_pointer_position`]. `frame` is the node's,
2738    /// from [`WidgetArena::local_frame`], computed once per node so every
2739    /// position in the event is converted by the same walk — and the same
2740    /// frame is handed to the node's handlers as
2741    /// [`EventContext::to_local`](crate::widget::EventContext::to_local).
2742    pub(super) fn localize_event(
2743        frame: &crate::arena::LocalFrame,
2744        event: &WidgetEvent,
2745    ) -> Option<WidgetEvent> {
2746        match event {
2747            WidgetEvent::PointerDown {
2748                position,
2749                button,
2750                modifiers,
2751                pointer,
2752            } => Some(WidgetEvent::PointerDown {
2753                position: frame.to_local(*position),
2754                button: *button,
2755                modifiers: *modifiers,
2756                pointer: *pointer,
2757            }),
2758            WidgetEvent::PointerUp {
2759                position,
2760                button,
2761                modifiers,
2762                pointer,
2763            } => Some(WidgetEvent::PointerUp {
2764                position: frame.to_local(*position),
2765                button: *button,
2766                modifiers: *modifiers,
2767                pointer: *pointer,
2768            }),
2769            WidgetEvent::PointerMove {
2770                position,
2771                modifiers,
2772                pointer,
2773            } => Some(WidgetEvent::PointerMove {
2774                position: frame.to_local(*position),
2775                modifiers: *modifiers,
2776                pointer: *pointer,
2777            }),
2778            WidgetEvent::Gesture { gesture } => Some(WidgetEvent::Gesture {
2779                gesture: Self::localize_gesture(frame, gesture),
2780            }),
2781            // Deliberately no `Scroll` or `PointerCancel` arm. Both name their
2782            // position `window_position` precisely because it stays in window
2783            // space — see the fields' own docs for why routing and velocity
2784            // need it there — and adding an arm here would silently change the
2785            // frame every reader of those two fields works in.
2786            _ => None,
2787        }
2788    }
2789
2790    /// Convert every position / center field of a pre-recognized
2791    /// [`GestureEvent`] into `id`'s widget-local space (`DragMoved.delta`
2792    /// is relative and left untouched). Used for the platform gesture
2793    /// path; arena-recognized gestures are already local because the
2794    /// `RawPointerEvent` feeding the arena was localized by
2795    /// [`Self::localize_event`].
2796    fn localize_gesture(frame: &crate::arena::LocalFrame, gesture: &GestureEvent) -> GestureEvent {
2797        let loc = |p: teksilo_canvas::Point| frame.to_local(p);
2798        let tap = |t: &TapEvent| {
2799            TapEvent::new(loc(t.position), t.button, t.modifiers).with_pointer(t.pointer)
2800        };
2801        match gesture {
2802            GestureEvent::Tap(t) => GestureEvent::Tap(tap(t)),
2803            GestureEvent::DoubleTap(t) => GestureEvent::DoubleTap(tap(t)),
2804            GestureEvent::TripleTap(t) => GestureEvent::TripleTap(tap(t)),
2805            GestureEvent::LongPress(t) => GestureEvent::LongPress(tap(t)),
2806            GestureEvent::DragStarted {
2807                position,
2808                button,
2809                pointer,
2810            } => GestureEvent::DragStarted {
2811                position: loc(*position),
2812                button: *button,
2813                pointer: *pointer,
2814            },
2815            GestureEvent::DragMoved {
2816                position,
2817                delta,
2818                pointer,
2819            } => GestureEvent::DragMoved {
2820                position: loc(*position),
2821                delta: *delta,
2822                pointer: *pointer,
2823            },
2824            GestureEvent::DragEnded { position, pointer } => GestureEvent::DragEnded {
2825                position: loc(*position),
2826                pointer: *pointer,
2827            },
2828            GestureEvent::DragCancelled {
2829                position,
2830                pointer,
2831                reason,
2832            } => GestureEvent::DragCancelled {
2833                position: loc(*position),
2834                pointer: *pointer,
2835                reason: *reason,
2836            },
2837            GestureEvent::PinchStarted { center } => GestureEvent::PinchStarted {
2838                center: loc(*center),
2839            },
2840            GestureEvent::PinchChanged {
2841                center,
2842                scale,
2843                rotation,
2844            } => GestureEvent::PinchChanged {
2845                center: loc(*center),
2846                scale: *scale,
2847                rotation: *rotation,
2848            },
2849            GestureEvent::PinchEnded => GestureEvent::PinchEnded,
2850            GestureEvent::PinchCancelled { reason } => {
2851                GestureEvent::PinchCancelled { reason: *reason }
2852            }
2853            GestureEvent::Swipe {
2854                direction,
2855                velocity,
2856            } => GestureEvent::Swipe {
2857                direction: *direction,
2858                velocity: *velocity,
2859            },
2860        }
2861    }
2862
2863    /// Same as `dispatch_to_widget` but returns `true` when any
2864    /// preview or bubble handler consumed the event. Used for keyboard
2865    /// events the framework wants to consume by default (Tab focus
2866    /// navigation): callers can dispatch first, then fall back to
2867    /// built-in behavior only when no widget claimed it.
2868    pub(super) fn dispatch_to_widget_returning_handled(
2869        &mut self,
2870        target: WidgetId,
2871        event: &WidgetEvent,
2872        ops: &mut dyn crate::window::WindowOps,
2873    ) -> bool {
2874        // A disabled widget takes no input, but `FocusLost` is not input: it
2875        // tells a widget that held focus that it no longer does, and one that
2876        // loses focus because it was disabled must still hear it (Qt sends
2877        // FocusOut to the widget it disables), or a button keeps its focused
2878        // look and a text field never commits its edit.
2879        if !self.arena.is_enabled(target) && !matches!(event, WidgetEvent::FocusLost) {
2880            return false;
2881        }
2882
2883        let mut ancestors = Vec::new();
2884        let mut current = self.arena.parent(target);
2885        while let Some(id) = current {
2886            ancestors.push(id);
2887            current = self.arena.parent(id);
2888        }
2889        ancestors.reverse();
2890
2891        // For a pointer press, find the innermost tap-owning node at-or-above
2892        // the hit target (a chevron / checkbox / inline button). A row or
2893        // container that selects on press consults
2894        // `ctx.press_claimed_by_interactive_child()` to skip selecting when this
2895        // owner is a strict descendant of it — the press belongs to the inner
2896        // control, not the row. Tap-like handlers only; drag/swipe are excluded
2897        // so a draggable row still selects itself on press.
2898        //
2899        // **`on_tap` / `on_long_press` only — never `on_double_tap` alone.**
2900        // The question this answers is "does a descendant own *this press*",
2901        // and a widget that wired only a multi-tap handler does not: the first
2902        // click of a double-click is not its business. Counting it meant a
2903        // table cell could not carry double-click-to-edit without also
2904        // silently stopping its row from selecting on a plain click — while
2905        // every file manager selects a row on the first click of the
2906        // double-click that opens it. A node that wants the press still has
2907        // `on_tap` (a real `Button`, a checkbox), and those are unaffected.
2908        let tap_owner: Option<WidgetId> = if matches!(
2909            event,
2910            WidgetEvent::PointerDown { .. } | WidgetEvent::PointerUp { .. }
2911        ) {
2912            let mut owner = None;
2913            let mut cur = Some(target);
2914            while let Some(id) = cur {
2915                if self.arena.get(id).is_some_and(|n| {
2916                    n.any_handler(|h| h.on_tap.is_some() || h.on_long_press.is_some())
2917                }) {
2918                    owner = Some(id);
2919                    break;
2920                }
2921                cur = self.arena.parent(id);
2922            }
2923            owner
2924        } else {
2925            None
2926        };
2927
2928        for &id in &ancestors {
2929            let frame = self.arena.local_frame(id);
2930            let mut ctx = self
2931                .make_event_context(&mut *ops)
2932                .with_dispatch_node(id)
2933                .with_content_language(self.content_language(id))
2934                .with_dispatch_target(target)
2935                .with_local_frame(frame);
2936            ctx.press_claimed_by_interactive_child =
2937                tap_owner.is_some_and(|owner| owner != id && self.is_descendant_of(owner, id));
2938            // Convert any pointer position into this node's widget-local
2939            // space before its handlers see it (see `localize_event`).
2940            let localized = Self::localize_event(&frame, event);
2941            let event = localized.as_ref().unwrap_or(event);
2942            let response = if let Some(node) = self.arena.get_mut(id) {
2943                Self::try_handler_preview(node, event, &mut ctx).unwrap_or(EventResponse::Ignored)
2944            } else {
2945                EventResponse::Ignored
2946            };
2947            self.collect_from_ctx(ctx, id);
2948            if response == EventResponse::Handled {
2949                self.arena.mark_needs_paint(id);
2950                // Step 1 of the decision procedure: the raw-preview pass runs
2951                // FIRST and keeps its root-first order, and the first `Handled`
2952                // claims the press. Deliberately not folded into the
2953                // innermost-first member order — `rich_text/mouse.rs` documents
2954                // relying on an outer wrapper seeing a press before an inner
2955                // one, and reordering it would silently invert a precedence
2956                // real widgets depend on.
2957                if matches!(event, WidgetEvent::PointerDown { .. }) {
2958                    self.note_preview_claim(id);
2959                }
2960                return true;
2961            }
2962        }
2963
2964        let needs_layout_on_handle = matches!(
2965            event,
2966            WidgetEvent::Scroll { .. } | WidgetEvent::ScrollIntoView { .. }
2967        );
2968        let mut current = Some(target);
2969        let mut is_target = true;
2970        while let Some(id) = current {
2971            let frame = self.arena.local_frame(id);
2972            let mut ctx = self
2973                .make_event_context(&mut *ops)
2974                .with_dispatch_node(id)
2975                .with_content_language(self.content_language(id))
2976                .with_dispatch_target(target)
2977                .with_local_frame(frame);
2978            ctx.press_claimed_by_interactive_child =
2979                tap_owner.is_some_and(|owner| owner != id && self.is_descendant_of(owner, id));
2980            // Convert any pointer position into this node's widget-local
2981            // space before its handlers (and its gesture arena) see it.
2982            let localized = Self::localize_event(&frame, event);
2983            let gesture_cx = self.recognizer_context(id);
2984            // A member that lost the arbitration keeps its handlers and loses
2985            // only its recognizers — see `sequence_blocks_arena`.
2986            let arena_blocked = self.sequence_blocks_arena(id);
2987            let WidgetTree {
2988                arena,
2989                gesture_owners,
2990                ..
2991            } = self;
2992            let event = localized.as_ref().unwrap_or(event);
2993            let response = if let Some(node) = arena.get_mut(id) {
2994                Self::try_handler_bubble(
2995                    node,
2996                    event,
2997                    &mut ctx,
2998                    BubbleGates {
2999                        fire_on_pointer_event: is_target,
3000                        arena_blocked,
3001                    },
3002                    id,
3003                    gesture_owners,
3004                    gesture_cx,
3005                )
3006                .unwrap_or(EventResponse::Ignored)
3007            } else {
3008                EventResponse::Ignored
3009            };
3010            self.collect_from_ctx(ctx, id);
3011            if response == EventResponse::Handled {
3012                if needs_layout_on_handle {
3013                    self.arena.mark_needs_layout(id);
3014                } else {
3015                    self.arena.mark_needs_paint(id);
3016                }
3017                self.note_pointer_acceptance(id, event);
3018                // **Hover transitions are notifications, and every ancestor is
3019                // entitled to one.** Stopping the bubble here left a container
3020                // stuck hovered whenever the pointer left it *through* an
3021                // interactive child: the child's own `on_hover` handled the
3022                // `PointerLeave`, the bubble stopped, and the row went on believing
3023                // the pointer was still over it. A search result whose controls
3024                // appear on hover then kept them after the pointer had gone.
3025                //
3026                // The preview pass already refuses to let an ancestor swallow a
3027                // descendant's Enter/Leave; this is that rule in the other
3028                // direction, and it is what makes a container's hover mean "the
3029                // pointer is somewhere inside me" rather than "the pointer is on my
3030                // own background". Every other event still stops at its handler,
3031                // which is what makes handling one mean anything.
3032                if !matches!(
3033                    event,
3034                    WidgetEvent::PointerEnter { .. } | WidgetEvent::PointerLeave { .. }
3035                ) {
3036                    return true;
3037                }
3038            }
3039            is_target = false;
3040            current = self.arena.parent(id);
3041        }
3042        false
3043    }
3044
3045    pub(super) fn dispatch_to_widget_direct(
3046        &mut self,
3047        target: WidgetId,
3048        event: &WidgetEvent,
3049        ops: &mut dyn crate::window::WindowOps,
3050    ) {
3051        self.dispatch_to_widget_direct_returning_handled(target, event, ops);
3052    }
3053
3054    /// [`dispatch_to_widget_direct`](Self::dispatch_to_widget_direct), reporting
3055    /// whether the node consumed the event.
3056    ///
3057    /// The claimant chain needs the answer: `Handled` means the container
3058    /// absorbed some of the delta and the walk stops, `Ignored` means it is at
3059    /// a boundary and the same whole event goes to the next container outward.
3060    /// Addressed rather than bubbled, which is exactly what a claimant chain is
3061    /// — a list of named recipients, like the one the cancel funnel delivers
3062    /// to.
3063    pub(super) fn dispatch_to_widget_direct_returning_handled(
3064        &mut self,
3065        target: WidgetId,
3066        event: &WidgetEvent,
3067        ops: &mut dyn crate::window::WindowOps,
3068    ) -> bool {
3069        // `FocusLost` reaches a disabled widget too: see
3070        // `dispatch_to_widget_returning_handled`.
3071        if !self.arena.is_enabled(target) && !matches!(event, WidgetEvent::FocusLost) {
3072            return false;
3073        }
3074
3075        let frame = self.arena.local_frame(target);
3076        let mut ctx = self
3077            .make_event_context(&mut *ops)
3078            .with_dispatch_node(target)
3079            .with_content_language(self.content_language(target))
3080            .with_dispatch_target(target)
3081            .with_local_frame(frame);
3082        let gesture_cx = self.recognizer_context(target);
3083        let arena_blocked = self.sequence_blocks_arena(target);
3084        let WidgetTree {
3085            arena,
3086            gesture_owners,
3087            ..
3088        } = self;
3089        let response = if let Some(node) = arena.get_mut(target) {
3090            Self::try_handler_bubble(
3091                node,
3092                event,
3093                &mut ctx,
3094                BubbleGates {
3095                    fire_on_pointer_event: true,
3096                    arena_blocked,
3097                },
3098                target,
3099                gesture_owners,
3100                gesture_cx,
3101            )
3102            .unwrap_or(EventResponse::Ignored)
3103        } else {
3104            EventResponse::Ignored
3105        };
3106        self.collect_from_ctx(ctx, target);
3107
3108        if response == EventResponse::Handled {
3109            // A scroll changes geometry, so it earns a layout pass rather than
3110            // a repaint — the same distinction the bubble path makes.
3111            if matches!(
3112                event,
3113                WidgetEvent::Scroll { .. } | WidgetEvent::ScrollIntoView { .. }
3114            ) {
3115                self.arena.mark_needs_layout(target);
3116            } else {
3117                self.arena.mark_needs_paint(target);
3118            }
3119            self.note_pointer_acceptance(target, event);
3120        }
3121        response == EventResponse::Handled
3122    }
3123
3124    /// Remember that `target` answered `Handled` to one of the current
3125    /// pointer's positional events.
3126    ///
3127    /// Read only by the cancel funnel, as the recipient of last resort when a
3128    /// revoked pointer holds no capture. Restricted to the three positional
3129    /// phases: a key, an accessibility action or a focus change is not "an
3130    /// event from this pointer", and letting one of those set the anchor would
3131    /// address the cancel to a widget the pointer never touched.
3132    pub(super) fn note_pointer_acceptance(&mut self, target: WidgetId, event: &WidgetEvent) {
3133        if !matches!(
3134            event,
3135            WidgetEvent::PointerDown { .. }
3136                | WidgetEvent::PointerMove { .. }
3137                | WidgetEvent::PointerUp { .. }
3138        ) {
3139            return;
3140        }
3141        let pointer = self.current_pointer_id();
3142        if let Some(entry) = self.pointers.get_mut(pointer) {
3143            entry.last_accepted = Some(target);
3144        }
3145    }
3146
3147    fn try_handler_preview(
3148        node: &mut crate::arena::WidgetNode,
3149        event: &WidgetEvent,
3150        ctx: &mut EventContext,
3151    ) -> Option<EventResponse> {
3152        match event {
3153            // Key + IME events fire `on_key_preview` on each strict
3154            // ancestor of the focused widget (root → parent-of-target).
3155            // Mirrors how `on_pointer_event` previews on the pointer
3156            // side; the focused widget itself does NOT see its own
3157            // `on_key_preview` (the dispatch loop builds an ancestors
3158            // list that excludes the target, so this is enforced by
3159            // the caller, not here).
3160            WidgetEvent::KeyDown { .. }
3161            | WidgetEvent::KeyUp { .. }
3162            | WidgetEvent::ImeComposition { .. }
3163            | WidgetEvent::ImeCommit { .. } => {
3164                let has = node.external_handlers.on_key_preview.is_some()
3165                    || node.handlers.on_key_preview.is_some();
3166                if !has {
3167                    return None;
3168                }
3169                Some(fire_event_handler_both(
3170                    &mut node.external_handlers.on_key_preview,
3171                    &mut node.handlers.on_key_preview,
3172                    event,
3173                    ctx,
3174                ))
3175            }
3176            // `PointerEnter` / `PointerLeave` are per-node hover transitions
3177            // synthesized by `handle_pointer_move`, not part of the raw pointer
3178            // stream. Running them through the ancestor preview pass would let
3179            // a drag-detecting ancestor whose `on_pointer_event` returns
3180            // `Handled` silently swallow a descendant's hover (its cursor and
3181            // `on_hover` would never fire). They are delivered to their target
3182            // directly via the bubble pass (where Enter/Leave fire `on_hover`),
3183            // so they have no business in preview. `PointerMove`/`Down`/`Up`
3184            // and `Scroll` still preview through the catch-all below — the
3185            // tab-bar wheel-remap (`tab_widget/bar.rs`) and the split-view /
3186            // rich-text drag guards depend on that.
3187            WidgetEvent::PointerEnter { .. } | WidgetEvent::PointerLeave { .. } => None,
3188            _ => {
3189                let has = node.external_handlers.on_pointer_event.is_some()
3190                    || node.handlers.on_pointer_event.is_some();
3191                if !has {
3192                    return None;
3193                }
3194                Some(fire_event_handler_both(
3195                    &mut node.external_handlers.on_pointer_event,
3196                    &mut node.handlers.on_pointer_event,
3197                    event,
3198                    ctx,
3199                ))
3200            }
3201        }
3202    }
3203
3204    fn try_handler_bubble(
3205        node: &mut crate::arena::WidgetNode,
3206        event: &WidgetEvent,
3207        ctx: &mut EventContext,
3208        gates: BubbleGates,
3209        node_id: WidgetId,
3210        gesture_owners: &mut std::collections::HashSet<WidgetId>,
3211        gesture_cx: crate::gesture::RecognizerContext<'_>,
3212    ) -> Option<EventResponse> {
3213        let BubbleGates {
3214            fire_on_pointer_event,
3215            arena_blocked,
3216        } = gates;
3217        match event {
3218            WidgetEvent::PointerEnter { .. } => {
3219                if let Some(cursor) = node.node_cursor {
3220                    // The declared channel, not `set_cursor`: a handler
3221                    // overriding the cursor in the same dispatch must not
3222                    // erase the tree's record of what the node asked for —
3223                    // that record is what `release_cursor` hands back to.
3224                    ctx.declared_cursor_request = Some(cursor);
3225                }
3226                let mut fired = false;
3227                if let Some(h) = node.external_handlers.on_hover.as_mut() {
3228                    h(true, ctx);
3229                    fired = true;
3230                }
3231                if let Some(h) = node.handlers.on_hover.as_mut() {
3232                    h(true, ctx);
3233                    fired = true;
3234                }
3235                if fired {
3236                    Some(EventResponse::Handled)
3237                } else {
3238                    node.node_cursor.map(|_| EventResponse::Handled)
3239                }
3240            }
3241            WidgetEvent::PointerLeave { .. } => {
3242                if node.node_cursor.is_some() {
3243                    ctx.declared_cursor_request = Some(crate::widget::CursorIcon::Default);
3244                }
3245                let mut fired = false;
3246                if let Some(h) = node.external_handlers.on_hover.as_mut() {
3247                    h(false, ctx);
3248                    fired = true;
3249                }
3250                if let Some(h) = node.handlers.on_hover.as_mut() {
3251                    h(false, ctx);
3252                    fired = true;
3253                }
3254                if fired {
3255                    Some(EventResponse::Handled)
3256                } else {
3257                    node.node_cursor.map(|_| EventResponse::Handled)
3258                }
3259            }
3260            WidgetEvent::FocusGained { origin } => {
3261                // The handler signature is a bare `bool`; the origin rides on
3262                // the context so a widget can tell a rebuild's restore from a
3263                // real arrival (`EventContext::focus_origin`).
3264                let previous_origin = ctx.focus_origin.replace(*origin);
3265                let mut fired = false;
3266                if let Some(h) = node.external_handlers.on_focus.as_mut() {
3267                    h(true, ctx);
3268                    fired = true;
3269                }
3270                if let Some(h) = node.handlers.on_focus.as_mut() {
3271                    h(true, ctx);
3272                    fired = true;
3273                }
3274                ctx.focus_origin = previous_origin;
3275                fired.then_some(EventResponse::Handled)
3276            }
3277            WidgetEvent::FocusLost => {
3278                let mut fired = false;
3279                if let Some(h) = node.external_handlers.on_focus.as_mut() {
3280                    h(false, ctx);
3281                    fired = true;
3282                }
3283                if let Some(h) = node.handlers.on_focus.as_mut() {
3284                    h(false, ctx);
3285                    fired = true;
3286                }
3287                fired.then_some(EventResponse::Handled)
3288            }
3289            WidgetEvent::KeyDown { .. }
3290            | WidgetEvent::KeyUp { .. }
3291            | WidgetEvent::ImeComposition { .. }
3292            | WidgetEvent::ImeCommit { .. } => {
3293                if node.external_handlers.on_key.is_some() || node.handlers.on_key.is_some() {
3294                    Some(fire_event_handler_both(
3295                        &mut node.external_handlers.on_key,
3296                        &mut node.handlers.on_key,
3297                        event,
3298                        ctx,
3299                    ))
3300                } else {
3301                    None
3302                }
3303            }
3304            WidgetEvent::Scroll { .. } | WidgetEvent::ScrollIntoView { .. } => {
3305                if node.external_handlers.on_scroll.is_some() || node.handlers.on_scroll.is_some() {
3306                    Some(fire_event_handler_both(
3307                        &mut node.external_handlers.on_scroll,
3308                        &mut node.handlers.on_scroll,
3309                        event,
3310                        ctx,
3311                    ))
3312                } else {
3313                    None
3314                }
3315            }
3316            WidgetEvent::AccessAction {
3317                action,
3318                target_node,
3319                data,
3320                ..
3321            } => {
3322                // Every installed slot fires — both payload shapes, and
3323                // within each shape both the external (app-installed
3324                // `.on_access_action*`) and the widget's own. Button (own)
3325                // and Dialog (external) layered together rely on that for a
3326                // single accesskit click.
3327                //
3328                // The two shapes are layered, not alternatives, because they
3329                // have different owners: `on_access_action_request` is what a
3330                // widget reaches for when it needs `target_node` or `data`
3331                // (`Slider`, `SpinBox`, `TextInputField`, `CodeEditor`,
3332                // `TabBar`), while `.on_access_action(..)` is the app's
3333                // builder-level hook. Preferring the payload shape when it was
3334                // set therefore did not choose between two handlers for the
3335                // same job — it silently disabled the app's handler on exactly
3336                // the widgets that had migrated, with nothing at the call site
3337                // to say so.
3338                //
3339                // Assistive-tech action paths run under the `Accessibility`
3340                // source label. Restored after the block.
3341                let saved_a11y_source = ctx
3342                    .current_source
3343                    .replace(crate::telemetry::IntentSource::Accessibility);
3344                let mut any_slot = false;
3345                let mut any_handled = false;
3346                if let Some(h) = node.external_handlers.on_access_action_request.as_mut() {
3347                    any_slot = true;
3348                    any_handled |=
3349                        h(*action, *target_node, data.clone(), ctx) == EventResponse::Handled;
3350                }
3351                if let Some(h) = node.handlers.on_access_action_request.as_mut() {
3352                    any_slot = true;
3353                    any_handled |=
3354                        h(*action, *target_node, data.clone(), ctx) == EventResponse::Handled;
3355                }
3356                if let Some(h) = node.external_handlers.on_access_action.as_mut() {
3357                    any_slot = true;
3358                    any_handled |= h(*action, ctx) == EventResponse::Handled;
3359                }
3360                if let Some(h) = node.handlers.on_access_action.as_mut() {
3361                    any_slot = true;
3362                    any_handled |= h(*action, ctx) == EventResponse::Handled;
3363                }
3364                let user_handled = any_slot.then_some(if any_handled {
3365                    EventResponse::Handled
3366                } else {
3367                    EventResponse::Ignored
3368                });
3369
3370                // Builder-level access_action / access_custom_action
3371                // callbacks. These layer on top of any user-installed
3372                // on_access_action / on_access_action_request — both
3373                // fire for the same dispatched event. Drives the
3374                // SwiftUI `.accessibilityAction(...)` parity.
3375                let mut override_handled = false;
3376                if let Some(ov) = node.access_overrides.as_deref_mut() {
3377                    if matches!(action, accesskit::Action::CustomAction) {
3378                        if let Some(accesskit::ActionData::CustomAction(idx)) = data
3379                            && let Some((_, cb)) = ov.custom_actions.get_mut(*idx as usize)
3380                        {
3381                            cb(ctx);
3382                            override_handled = true;
3383                        }
3384                    } else {
3385                        for (a, cb) in ov.actions.iter_mut() {
3386                            if *a == *action {
3387                                cb(ctx);
3388                                override_handled = true;
3389                            }
3390                        }
3391                    }
3392                }
3393
3394                ctx.current_source = saved_a11y_source;
3395                match (user_handled, override_handled) {
3396                    (Some(EventResponse::Handled), _) | (_, true) => Some(EventResponse::Handled),
3397                    (Some(EventResponse::Ignored), false) => Some(EventResponse::Ignored),
3398                    (None, false) => None,
3399                }
3400            }
3401            WidgetEvent::Gesture { gesture } => {
3402                // Pre-recognized gestures from the platform (OS trackpad
3403                // pinch/rotation, double-tap, …) bypass the gesture arena
3404                // and go straight to the matching handler. See §10.
3405                let matched = matches!(
3406                    gesture,
3407                    GestureEvent::PinchStarted { .. }
3408                        | GestureEvent::PinchChanged { .. }
3409                        | GestureEvent::PinchEnded
3410                        | GestureEvent::Swipe { .. }
3411                        | GestureEvent::DoubleTap { .. }
3412                        | GestureEvent::TripleTap { .. }
3413                ) && {
3414                    let has_handler = match gesture {
3415                        GestureEvent::PinchStarted { .. }
3416                        | GestureEvent::PinchChanged { .. }
3417                        | GestureEvent::PinchEnded => node.any_handler(|h| h.on_pinch.is_some()),
3418                        GestureEvent::Swipe { .. } => node.any_handler(|h| h.on_swipe.is_some()),
3419                        GestureEvent::DoubleTap { .. } => {
3420                            node.any_handler(|h| h.on_double_tap.is_some())
3421                        }
3422                        GestureEvent::TripleTap { .. } => {
3423                            node.any_handler(|h| h.on_triple_tap.is_some())
3424                        }
3425                        _ => false,
3426                    };
3427                    if has_handler {
3428                        Self::dispatch_recognized_gesture(node, *gesture, ctx);
3429                    }
3430                    has_handler
3431                };
3432                if matched {
3433                    Some(EventResponse::Handled)
3434                } else {
3435                    None
3436                }
3437            }
3438            WidgetEvent::PointerDown {
3439                position,
3440                button,
3441                modifiers,
3442                ..
3443            } => {
3444                // Raw pointer handler runs first so widgets can intercept
3445                // events that the gesture recognizers won't catch (e.g.
3446                // right-click → context menu). If it returns Handled the
3447                // gesture arena is skipped; otherwise we fall through.
3448                // Only fire for the target — ancestors already fired
3449                // on_pointer_event during the preview pass.
3450                if fire_on_pointer_event {
3451                    let r = fire_event_handler_both(
3452                        &mut node.external_handlers.on_pointer_event,
3453                        &mut node.handlers.on_pointer_event,
3454                        event,
3455                        ctx,
3456                    );
3457                    if r == EventResponse::Handled {
3458                        return Some(EventResponse::Handled);
3459                    }
3460                }
3461                if arena_blocked {
3462                    // This node lost the arbitration for the press: its
3463                    // recognizers stay out of it, and the event goes on
3464                    // bubbling as if the node carried none.
3465                    return None;
3466                }
3467                Self::ensure_gesture_arena(node, node_id, gesture_owners);
3468                if let Some(arena) = node.handlers.gesture_arena.as_mut() {
3469                    let cx = gesture_cx;
3470                    // Implicit capture for the Down..Up sequence so that
3471                    // moves leaving the widget bounds still reach the
3472                    // arena. Without this, a drag that starts inside the
3473                    // widget but crosses its edge before the recognizer
3474                    // latches would be hit-tested to another widget and
3475                    // the press-origin arena would never see a `Move`.
3476                    // Released unconditionally by the `PointerUp` branch
3477                    // in `dispatch_event`.
3478                    //
3479                    // **Implicit**: this is plumbing, not a claim. Routing it
3480                    // through the public `capture_pointer` would enrol every
3481                    // arena-bearing node as a `RawDrag` competitor and decide
3482                    // every mouse sequence at press. See
3483                    // `EventContext::capture_pointer_implicit`.
3484                    ctx.capture_pointer_implicit();
3485                    let result = arena.process(
3486                        &RawPointerEvent::Down {
3487                            position: *position,
3488                            button: *button,
3489                            modifiers: *modifiers,
3490                            pointer: cx.pointer,
3491                            time: cx.now,
3492                        },
3493                        &cx,
3494                    );
3495                    if let Some(gesture) = result {
3496                        Self::dispatch_recognized_gesture(node, gesture, ctx);
3497                    }
3498                    return Some(EventResponse::Handled);
3499                }
3500                None
3501            }
3502            WidgetEvent::PointerUp {
3503                position,
3504                button,
3505                modifiers,
3506                ..
3507            } => {
3508                if fire_on_pointer_event {
3509                    let r = fire_event_handler_both(
3510                        &mut node.external_handlers.on_pointer_event,
3511                        &mut node.handlers.on_pointer_event,
3512                        event,
3513                        ctx,
3514                    );
3515                    if r == EventResponse::Handled {
3516                        return Some(EventResponse::Handled);
3517                    }
3518                }
3519                if arena_blocked {
3520                    return None;
3521                }
3522                if let Some(arena) = node.handlers.gesture_arena.as_mut() {
3523                    let cx = gesture_cx;
3524                    let result = arena.process(
3525                        &RawPointerEvent::Up {
3526                            position: *position,
3527                            button: *button,
3528                            modifiers: *modifiers,
3529                            pointer: cx.pointer,
3530                            time: cx.now,
3531                        },
3532                        &cx,
3533                    );
3534                    if let Some(gesture) = result {
3535                        Self::dispatch_recognized_gesture(node, gesture, ctx);
3536                    }
3537                    return Some(EventResponse::Handled);
3538                }
3539                None
3540            }
3541            WidgetEvent::PointerMove { position, .. } => {
3542                if fire_on_pointer_event {
3543                    let r = fire_event_handler_both(
3544                        &mut node.external_handlers.on_pointer_event,
3545                        &mut node.handlers.on_pointer_event,
3546                        event,
3547                        ctx,
3548                    );
3549                    if r == EventResponse::Handled {
3550                        return Some(EventResponse::Handled);
3551                    }
3552                }
3553                if arena_blocked {
3554                    return None;
3555                }
3556                if let Some(arena) = node.handlers.gesture_arena.as_mut() {
3557                    let cx = gesture_cx;
3558                    let result = arena.process(
3559                        &RawPointerEvent::Move {
3560                            position: *position,
3561                            pointer: cx.pointer,
3562                            time: cx.now,
3563                        },
3564                        &cx,
3565                    );
3566                    if let Some(gesture) = result {
3567                        Self::dispatch_recognized_gesture(node, gesture, ctx);
3568                        // A recognized gesture (DragStarted / DragMoved / …)
3569                        // almost always changes visible state — return
3570                        // `Handled` so the bubble loop marks this widget
3571                        // `needs_paint`, which in turn makes
3572                        // `WidgetTree::needs_redraw()` return true and
3573                        // triggers a `request_redraw` for the next frame.
3574                        // Without this, state updates via bound signals are
3575                        // only observed on the *next* layout/render pass,
3576                        // which in turn is never scheduled because
3577                        // `teksilo-app::update_control_flow` only wakes up when
3578                        // `needs_redraw()` is true.
3579                        return Some(EventResponse::Handled);
3580                    }
3581                    return Some(EventResponse::Ignored);
3582                }
3583                None
3584            }
3585            WidgetEvent::PointerCancel {
3586                reason, pointer, ..
3587            } => {
3588                // Two hooks, and the dedicated one always runs. `on_pointer_cancel`
3589                // is a notification, not a route: a widget releasing what its
3590                // press latched has nothing to consume, and letting it report
3591                // `Handled` would make releasing state look like claiming the
3592                // event. The raw `on_pointer_event` hook keeps its ordinary
3593                // consuming semantics for widgets that drive the whole pointer
3594                // stream themselves.
3595                for slot in [
3596                    &mut node.external_handlers.on_pointer_cancel,
3597                    &mut node.handlers.on_pointer_cancel,
3598                ] {
3599                    if let Some(handler) = slot.as_mut() {
3600                        handler(pointer, *reason, ctx);
3601                    }
3602                }
3603                if fire_on_pointer_event {
3604                    let r = fire_event_handler_both(
3605                        &mut node.external_handlers.on_pointer_event,
3606                        &mut node.handlers.on_pointer_event,
3607                        event,
3608                        ctx,
3609                    );
3610                    if r == EventResponse::Handled {
3611                        return Some(EventResponse::Handled);
3612                    }
3613                }
3614                None
3615            }
3616        }
3617    }
3618
3619    pub(super) fn collect_from_ctx<'ops>(
3620        &mut self,
3621        mut ctx: EventContext<'ops>,
3622        source_widget: WidgetId,
3623    ) {
3624        // Take the ops handle out of ctx up front so we can freely
3625        // reborrow it inside the method without fighting the 'ops
3626        // lifetime propagation when other fields of `ctx` are moved.
3627        // When no ops is set (standalone trees / tests), fall back to
3628        // a stack NoopWindowOps.
3629        let local_ops = ctx.window_ops.take();
3630        let mut noop = crate::window::NoopWindowOps;
3631        let ops: &mut dyn crate::window::WindowOps = match local_ops {
3632            Some(o) => o,
3633            None => &mut noop,
3634        };
3635        if ctx.frame_requested {
3636            self.request_frame();
3637        }
3638        // Declared first, handler second — the order the two used to occur in
3639        // when both wrote the same slot, so a handler that speaks during an
3640        // enter still outranks the node it entered.
3641        if let Some(declared) = ctx.declared_cursor_request {
3642            self.node_declared_cursor = declared;
3643            self.current_cursor = declared;
3644        }
3645        match ctx.cursor_request {
3646            Some(crate::widget::CursorRequest::Set(cursor)) => {
3647                self.current_cursor = cursor;
3648            }
3649            // A withdrawal restores the node-declared cursor rather than
3650            // resetting to `Default`: the handler is stepping back, not
3651            // claiming the cursor is nothing.
3652            Some(crate::widget::CursorRequest::Release) => {
3653                self.current_cursor = self.node_declared_cursor;
3654            }
3655            None => {}
3656        }
3657        // Intents queued through `ctx.send_intent` are anchored at
3658        // the originating widget. Programmatic sends default to
3659        // `propagate_when_disabled = true` — there is no shortcut to
3660        // consult, and propagation is the safe, least-surprising
3661        // default.
3662        for intent in ctx.pending_intents {
3663            self.enqueue_intent(source_widget, intent, true);
3664        }
3665        // Key capture: process cancel before arm, matching the
3666        // handler's call order (the handler sets `cancel_key_capture`
3667        // when it calls `ctx.cancel_key_capture()`, and separately
3668        // stores `pending_key_capture` when it calls
3669        // `ctx.begin_key_capture(...)`). If the handler did both,
3670        // arm wins (whichever was called last on the ctx has
3671        // already overwritten the other field's effect via the
3672        // setter logic).
3673        if ctx.cancel_key_capture {
3674            self.cancel_key_capture();
3675        }
3676        if let Some(slot) = ctx.pending_key_capture {
3677            self.key_capture = Some(slot);
3678        }
3679        // Registry mutations queued by settings-UI buttons.
3680        for mutation in ctx.pending_shortcut_mutations {
3681            match mutation {
3682                crate::widget::ShortcutMutation::RebindPrimary { id, keystroke } => {
3683                    self.shortcut_registry.rebind_primary(id, keystroke);
3684                }
3685                crate::widget::ShortcutMutation::RebindSecondary { id, keystroke } => {
3686                    self.shortcut_registry.rebind_secondary(id, keystroke);
3687                }
3688                crate::widget::ShortcutMutation::ClearOverride { id } => {
3689                    self.shortcut_registry.clear_override(&id);
3690                }
3691            }
3692        }
3693        if ctx.close_request_to_modal {
3694            self.answer_close_request_with_modal(&mut *ops);
3695        }
3696        if ctx.close_window_requested {
3697            self.close_window_requested = true;
3698        }
3699        if ctx.force_close_requested {
3700            self.force_close_requested = true;
3701        }
3702        self.pending_modal_requests
3703            .extend(ctx.modal_requests.into_iter().map(|request| {
3704                crate::modal::QueuedModalRequest {
3705                    source_widget,
3706                    request,
3707                }
3708            }));
3709        // `send_intent_from_focus` starts from the widget focused after the
3710        // dismissals below: they give focus back to where the overlay took
3711        // it from (or the fallback chain's choice), so a row that closes its
3712        // popup and sends from focus reaches the editor the user was in. It
3713        // falls back to the handler's widget only when they leave nothing
3714        // focused (nothing was, when the overlay opened). Its walk is noted
3715        // before they close the overlay it may be in, so it still goes on
3716        // from the widget that overlay was attached to; and the modal it
3717        // stopped at, which, once closed, sends it to the content root.
3718        let focus_intents = std::mem::take(&mut ctx.pending_focus_intents);
3719        let (fallback_crossings, fallback_modal) = if focus_intents.is_empty() {
3720            (Vec::new(), None)
3721        } else {
3722            let modal = self.intent_walk(source_widget, &[]).2;
3723            (self.intent_route(source_widget, &[], true).crossings, modal)
3724        };
3725        if ctx.dismiss_modal && !self.dismiss_modal_for_source(source_widget, &mut *ops) {
3726            self.pending_modal_dismissal = true;
3727        }
3728        for callback in ctx.idle_callbacks {
3729            self.idle_queue.push_boxed(callback);
3730        }
3731        match ctx.dismiss_scope {
3732            Some(crate::widget::DismissScope::All) => {
3733                let mark = self.dismissal_mark();
3734                let dismissed = self.overlay_manager.dismiss_all();
3735                self.dormant_dismissed_content(&dismissed, &mut *ops);
3736                self.return_focus_after_dismissal(None, mark, &mut *ops);
3737            }
3738            Some(crate::widget::DismissScope::AllExceptHosts) => {
3739                self.dismiss_all_overlays_except_hosts(&mut *ops);
3740            }
3741            Some(crate::widget::DismissScope::SelfChain) => {
3742                self.dismiss_self_overlay_chain_for_source(source_widget, &mut *ops);
3743            }
3744            Some(crate::widget::DismissScope::Top) => {
3745                let mark = self.dismissal_mark();
3746                if let Some((_id, content_ids, focus_restore)) = self.overlay_manager.dismiss_top()
3747                {
3748                    self.dormant_dismissed_content(&content_ids, &mut *ops);
3749                    self.return_focus_after_dismissal(focus_restore, mark, &mut *ops);
3750                }
3751            }
3752            None => {
3753                for id in ctx.overlay_dismissals {
3754                    let mark = self.dismissal_mark();
3755                    let dismissed = self.overlay_manager.dismiss(id);
3756                    self.dormant_dismissed_content(&dismissed, &mut *ops);
3757                    self.return_focus_after_dismissal(None, mark, &mut *ops);
3758                }
3759            }
3760        }
3761        // Content-keyed dismissals (`dismiss_overlay_by_content`). Drained
3762        // unconditionally — independent of `dismiss_scope` and of the
3763        // pending delayed-overlay list — so a handler can retract a shown
3764        // reusable overlay it identifies only by content. Resolving the
3765        // id here (not at call time) is what lets the caller skip
3766        // tracking the `OverlayId`.
3767        for content_id in ctx.overlay_content_dismissals {
3768            if let Some(overlay_id) = self.overlay_manager.find_by_content(content_id) {
3769                let mark = self.dismissal_mark();
3770                let dismissed = self.overlay_manager.dismiss(overlay_id);
3771                self.dormant_dismissed_content(&dismissed, &mut *ops);
3772                self.return_focus_after_dismissal(None, mark, &mut *ops);
3773            }
3774        }
3775        // Apply pause/resume queue (ToastHost hover-pause). Drained
3776        // here so the handler-side `ctx.pause_overlay_auto_dismiss(id)`
3777        // is order-independent with `dismiss_overlay(id)` and the
3778        // scope-based dismissals: pause/resume on an overlay that
3779        // was concurrently dismissed is silently dropped (the find
3780        // inside the OverlayManager methods misses on the gone id).
3781        for (id, pause) in ctx.overlay_pause_requests {
3782            if pause {
3783                self.overlay_manager.pause_auto_dismiss(id);
3784            } else {
3785                self.overlay_manager.resume_auto_dismiss(id);
3786            }
3787        }
3788        for preserve_content in ctx.dismiss_descendant_overlays {
3789            self.dismiss_child_overlays_for_source(source_widget, preserve_content, &mut *ops);
3790        }
3791        // After every dismissal above, each of which may hand focus back to
3792        // what its overlay was opened over (a modal, a menu closing its
3793        // chain): `send_intent_from_focus` means that widget, not the row in
3794        // the closing menu that still held focus when the handler ran. With
3795        // nothing focused, it is the handler's widget, across the overlays
3796        // it was in; but a modal that has closed was the whole window to its
3797        // rows (a palette opened with nothing focused), so the intent starts
3798        // where one with no source does, at the content root.
3799        if !focus_intents.is_empty() {
3800            let modal_closed = fallback_modal
3801                .is_some_and(|content| self.overlay_manager.find_by_content(content).is_none());
3802            let start = match self.focused.filter(|id| self.arena.is_active(*id)) {
3803                Some(focus) => Some((focus, None)),
3804                None if modal_closed => self.intent_anchor().map(|root| (root, None)),
3805                // A handler outside the modal that is up (an app callback at
3806                // the content root, a native menu item): as if focus were in
3807                // the modal, which is in front of everything else.
3808                None if fallback_modal.is_none()
3809                    && self.overlay_manager.topmost_modal().is_some() =>
3810                {
3811                    self.focus_or_modal().map(|modal| (modal, None))
3812                }
3813                None => Some((source_widget, Some(fallback_crossings))),
3814            };
3815            if let Some((start, crossings)) = start {
3816                for intent in focus_intents {
3817                    match &crossings {
3818                        None => self.enqueue_intent(start, intent, true),
3819                        Some(crossings) => {
3820                            self.enqueue_intent_crossing(start, intent, true, crossings.clone())
3821                        }
3822                    }
3823                }
3824            }
3825        }
3826        let deferred_row_activations =
3827            self.apply_tree_mutations(std::mem::take(&mut ctx.tree_mutations));
3828        if ctx.request_a11y_update {
3829            self.a11y_dirty = true;
3830        }
3831        if let Some(visible) = ctx.soft_keyboard_request.take() {
3832            self.request_soft_keyboard(visible);
3833        }
3834        // Handed to the tree's own live regions, which schedule the two
3835        // accessibility syncs each message needs. See `crate::announcer`.
3836        for (message, politeness) in std::mem::take(&mut ctx.announcements) {
3837            self.announce_with(message, politeness);
3838        }
3839        for mut req in ctx.overlay_requests {
3840            if req.parent_overlay.is_none() {
3841                req.parent_overlay = self.overlay_ancestor_for_widget(source_widget);
3842            }
3843            if self
3844                .overlay_manager
3845                .find_by_content(req.content_id)
3846                .is_some()
3847            {
3848                continue;
3849            }
3850            let current_focus = self.focused;
3851            self.overlay_manager.show(req);
3852            // Overlay show changes the AT tree shape — mirror the
3853            // `WidgetTree::show_overlay` path. The dismissal sibling
3854            // (`dismiss_overlay_with_ops`) already flips this.
3855            self.a11y_dirty = true;
3856            if let Some(focus_id) = current_focus {
3857                self.record_top_focus_restore(focus_id);
3858            }
3859        }
3860        for (mut req, band) in ctx.overlay_band_requests {
3861            if req.parent_overlay.is_none() {
3862                req.parent_overlay = self.overlay_ancestor_for_widget(source_widget);
3863            }
3864            if self
3865                .overlay_manager
3866                .find_by_content(req.content_id)
3867                .is_some()
3868            {
3869                continue;
3870            }
3871            let content_id = req.content_id;
3872            self.overlay_manager.show_in_band(req, band);
3873            self.arena.activate(content_id);
3874            self.a11y_dirty = true;
3875            // Deliberately no `set_top_focus_restore`: the text-affordance band
3876            // never takes focus from the anchor, so there is nothing to give
3877            // back when it goes.
3878        }
3879        // After the shows, so a handler may raise an overlay and place it in
3880        // the same dispatch.
3881        for (content_id, placement) in ctx.overlay_placement_updates {
3882            if let Some(overlay_id) = self.overlay_manager.find_by_content(content_id) {
3883                self.overlay_manager.update_placement(overlay_id, placement);
3884            }
3885        }
3886        for (content_id, source) in ctx.overlay_placement_sources {
3887            if let Some(overlay_id) = self.overlay_manager.find_by_content(content_id) {
3888                self.overlay_manager
3889                    .set_placement_source(overlay_id, source);
3890            }
3891        }
3892        for (mut req, duration) in ctx.timed_overlay_requests {
3893            if req.parent_overlay.is_none() {
3894                req.parent_overlay = self.overlay_ancestor_for_widget(source_widget);
3895            }
3896            if self
3897                .overlay_manager
3898                .find_by_content(req.content_id)
3899                .is_some()
3900            {
3901                continue;
3902            }
3903            let current_focus = self.focused;
3904            let overlay_id = self.overlay_manager.show_for(req, duration);
3905            self.overlay_manager
3906                .set_shown_at_sim(overlay_id, self.sim_clock);
3907            self.a11y_dirty = true;
3908            if let Some(focus_id) = current_focus {
3909                self.record_top_focus_restore(focus_id);
3910            }
3911        }
3912        for (mut req, progress, duration) in ctx.reveal_overlay_requests {
3913            if req.parent_overlay.is_none() {
3914                req.parent_overlay = self.overlay_ancestor_for_widget(source_widget);
3915            }
3916            if self
3917                .overlay_manager
3918                .find_by_content(req.content_id)
3919                .is_some()
3920            {
3921                continue;
3922            }
3923            let content_id = req.content_id;
3924            let current_focus = self.focused;
3925            let overlay_id = self.overlay_manager.show(req);
3926            self.overlay_manager
3927                .set_shown_at_sim(overlay_id, self.sim_clock);
3928            self.a11y_dirty = true;
3929            if let Some(focus_id) = current_focus {
3930                self.record_top_focus_restore(focus_id);
3931            }
3932            // Drive the caller's progress signal 0 → 1, and register it
3933            // as the overlay's fade-state signal so every dismiss path
3934            // tweens it 1 → 0 and defers removal until it completes — the
3935            // same deferral machinery as `with_fade`, minus `set_opacity`
3936            // (the caller owns how `progress` paints).
3937            self.register_animated_signal(&progress, content_id);
3938            let _ = progress.try_animate_with_options(crate::animation::AnimationRequest {
3939                target: 1.0,
3940                duration,
3941                easing: teksilo_tokens::Easing::EaseOut,
3942                frame_interval: None,
3943                looping: false,
3944                epsilon: 0.0,
3945                max_duration: None,
3946            });
3947            self.overlay_manager
3948                .attach_fade(overlay_id, progress, duration);
3949        }
3950        if let Some((pointer, capture)) = ctx.pointer_capture {
3951            // Per pointer, and by default the pointer whose sample the handler
3952            // was serving — so a mouse call site means exactly what it meant
3953            // before, and two contacts on two widgets hold two captures.
3954            let named = pointer;
3955            let pointer = pointer.unwrap_or_else(|| self.current_pointer_id());
3956            self.set_pointer_capture(pointer, capture.then_some(source_widget));
3957            // An explicit `capture_pointer()` from a handler is an arbitration
3958            // act; the arena's and the drag pipeline's own captures are
3959            // plumbing and route through `capture_pointer_implicit`.
3960            if capture && ctx.explicit_capture && named.is_none() {
3961                self.note_explicit_capture(source_widget);
3962            }
3963        }
3964        if let Some(activation) = ctx.drag_activation_override.take() {
3965            // A press handler chose this node's drag activation for this press.
3966            // Onto the sequence, where it dies with the press — see
3967            // `EventContext::set_drag_activation`.
3968            self.note_drag_activation_override(source_widget, activation);
3969        }
3970        if ctx.recognized_owning_gesture {
3971            // A drag or a swipe recognized on this node owns the rest of the
3972            // press, however the recognizer was reached.
3973            self.note_gesture_recognized(source_widget);
3974        }
3975        if !ctx.gesture_acts.is_empty() {
3976            let acts = std::mem::take(&mut ctx.gesture_acts);
3977            self.apply_gesture_acts(&acts, source_widget);
3978        }
3979        if let Some(reason) = ctx.cancel_pointer_request {
3980            let pointer = self.current_pointer_id();
3981            self.cancel_pointer(pointer, reason, &mut *ops);
3982        }
3983        for (mut request, delay, focus_target, replace_siblings) in ctx.delayed_overlay_requests {
3984            if request.parent_overlay.is_none() {
3985                request.parent_overlay = self.overlay_ancestor_for_widget(source_widget);
3986            }
3987            if self
3988                .overlay_manager
3989                .find_by_content(request.content_id)
3990                .is_some()
3991            {
3992                continue;
3993            }
3994            let content_id = request.content_id;
3995            self.pending_delayed_overlays
3996                .retain(|pending| pending.request.content_id != content_id);
3997            self.pending_delayed_overlays.push(PendingDelayedOverlay {
3998                request,
3999                delay,
4000                focus_target,
4001                replace_siblings,
4002                real_requested_at: std::time::Instant::now(),
4003                sim_requested_at: self.sim_clock,
4004            });
4005            self.arena.mark_needs_paint(source_widget);
4006        }
4007        for content_id in ctx.cancel_delayed_overlays {
4008            self.pending_delayed_overlays
4009                .retain(|pending| pending.request.content_id != content_id);
4010        }
4011        // Apex = the last sample that was still over the anchor, which
4012        // for the intended caller (the anchor's own hover-leave) is the
4013        // point the diagonal starts from. Ops are applied per node as
4014        // its handler returns, so this lands before the next widget's
4015        // hover-enter and before the move's own pointer-leave
4016        // bookkeeping.
4017        for content_id in ctx.safe_region_arm_requests {
4018            if let Some(apex) = self
4019                .previous_pointer_position
4020                .or_else(|| self.hover_owner_position())
4021            {
4022                self.overlay_manager.arm_safe_region(
4023                    content_id,
4024                    apex,
4025                    std::time::Instant::now(),
4026                    self.sim_clock,
4027                );
4028            }
4029        }
4030        for id in ctx.repaint_requests {
4031            self.arena.mark_needs_paint(id);
4032        }
4033        for id in ctx.synthetic_clicks {
4034            // Over the caller's ops, never a standalone dispatch: the
4035            // tapped widget's own handler runs inside this nested
4036            // dispatch, so a standalone one would deny it the
4037            // multi-window API this dispatch already has in hand.
4038            self.synthesise_tap_with_ops(id, &mut *ops);
4039        }
4040        // `clear_focus` first: it emptied the two request lists as it was
4041        // queued, so anything still in them was requested after it.
4042        if ctx.clear_focus_requested {
4043            self.clear_focus_ops(&mut *ops);
4044        }
4045        // Both request kinds go through `request_focus_with_ops`, which holds
4046        // a request for a dormant node (a page this same handler is showing)
4047        // until the next layout pass has woken it, rather than focusing a node
4048        // the pass's revalidation would take focus straight back from.
4049        if let Some(&id) = ctx.focus_requests.last() {
4050            // If the requested widget is itself not focusable (e.g. a
4051            // composite like `TextInput` whose focus-handling lives on
4052            // an inner leaf), walk into the subtree and land on the
4053            // first focusable descendant in document order. This makes
4054            // `ctx.request_focus(some_composite)` Do The Right Thing
4055            // without every caller having to reach into private inner
4056            // ids. `first_focusable_descendant` returns the node itself
4057            // when it's focusable, so the usual leaf-target case is
4058            // still a no-op lookup.
4059            self.request_focus_with_ops(id, super::FocusRequestMode::SelfOrDescendant, &mut *ops);
4060        }
4061        if let Some(&id) = ctx.focus_into_requests.last() {
4062            // "Focus into" semantics: land on the first focusable descendant
4063            // and — unlike `focus_requests` above — do NOT fall back to the
4064            // container itself. A region with no focusable content (and not
4065            // focusable in its own right) leaves focus untouched rather than
4066            // trapping it on a non-interactive node. Drives Enter-on-a-tab →
4067            // into the tab panel.
4068            self.request_focus_with_ops(id, super::FocusRequestMode::Into, &mut *ops);
4069        }
4070
4071        // Rect-based "scroll this into view" requests (`ctx.ensure_visible`).
4072        // Walk outward from the widget whose handler queued the request and
4073        // reveal the rect inside every enclosing scroll container. Run after
4074        // focus so that if the same handler also moved focus, both follows
4075        // settle against the same (pre-relayout) bounds; each dispatch is
4076        // gated on the container not already showing the rect, so ordering is
4077        // harmless. The source widget itself is excluded from the walk — it
4078        // owns revealing an interior rect inside its own viewport.
4079        for req in ctx.scroll_into_view_requests {
4080            self.scroll_rect_into_view(
4081                // Whoever the rect belongs to — the source widget unless the caller
4082                // named another. See `EventContext::ensure_visible_from`.
4083                req.from.unwrap_or(source_widget),
4084                req.rect,
4085                req.margin,
4086                req.align,
4087                req.motion,
4088                &mut *ops,
4089            );
4090        }
4091        // Id-based `ctx.ensure_widget_visible`: resolve to the target's current
4092        // absolute bounds and walk *its* ancestors (skip if it was destroyed
4093        // before the drain). Walking from the target — not `source_widget` —
4094        // means the request reveals that widget wherever it sits, even when the
4095        // handler runs on a different node (a group's roving-key handler
4096        // revealing the child tile it just selected).
4097        for (id, margin) in ctx.scroll_widget_into_view_requests {
4098            if self.arena.get(id).is_some() {
4099                let bounds = self.arena.bounds(id);
4100                self.scroll_rect_into_view(
4101                    id,
4102                    bounds,
4103                    margin,
4104                    crate::event::ScrollAlign::Minimal,
4105                    crate::event::ScrollMotion::Instant,
4106                    &mut *ops,
4107                );
4108            }
4109        }
4110
4111        // Keyboard-highlight tooltip: surface the highlighted (menu) item's
4112        // tooltip immediately and dismiss the previously-highlighted one. Keyed
4113        // on the item id, NOT real focus (which stays on the menu panel for key
4114        // handling). Only the last request per handler is honoured.
4115        if let Some(&id) = ctx.highlight_tooltip_requests.last() {
4116            self.show_highlight_tooltip(id, &mut *ops);
4117        }
4118
4119        // --- Drag and drop ---
4120        if let Some((source_widget, payload, preview_widget)) = ctx.drag_start_request {
4121            let (preview_content_id, preview_overlay_id) = if let Some(preview) = preview_widget {
4122                // `add_boxed` — NOT `arena.insert` — runs the widget's
4123                // `build()` so composite previews (our `DragPreview`
4124                // wrapper in teksilo-widgets, or anything a user supplies)
4125                // actually instantiate their child subtree. Plain
4126                // `arena.insert` stops at the root node, leaves build
4127                // un-fired, and the overlay renders an empty widget.
4128                let content_id = self.add_boxed(preview);
4129                let overlay_id = self
4130                    .overlay_manager
4131                    .show(crate::overlay::OverlayRequest::new(
4132                        content_id,
4133                        source_widget,
4134                        crate::overlay::OverlayPlacement::AtPointer(teksilo_canvas::Point::ZERO),
4135                        crate::overlay::DismissBehavior::Manual,
4136                    ));
4137                // Force the next layout pass to run `position_overlays`
4138                // and `set_content_bounds` — otherwise the preview sits
4139                // at its initial (0, 0) placement forever.
4140                self.arena.mark_needs_layout(content_id);
4141                (Some(content_id), Some(overlay_id))
4142            } else {
4143                (None, None)
4144            };
4145            self.active_drag = Some(crate::drag_state::DragSession {
4146                payload,
4147                // The pointer that armed the drag. `start_drag` is always
4148                // reached from a handler serving a real sample, which is the
4149                // only place this is knowable — from here on the drag runs
4150                // through layout ticks and platform threads that have no
4151                // sample of their own. See `DragSession::pointer`.
4152                pointer: self.current_input.pointer,
4153                source_widget: Some(source_widget),
4154                is_external: false,
4155                current_position: teksilo_canvas::Point::ZERO,
4156                current_target: None,
4157                feedback: crate::drag_state::DropFeedback::NoFeedback,
4158                preview_content_id,
4159                preview_overlay_id,
4160            });
4161            self.set_current_pointer_capture(Some(source_widget));
4162            // Grabbing-hand cursor while the drag is in flight. Reset on
4163            // drop / cancel / source-destroyed below.
4164            self.current_cursor = crate::widget::CursorIcon::Grabbing;
4165        }
4166        if ctx.cancel_drag {
4167            self.cancel_active_drag(&mut *ops);
4168        }
4169
4170        // --- Environment changes (architecture §9.5) ---
4171        if let Some(theme) = ctx.theme_request {
4172            // Stored, not applied: the app layer routes this through
4173            // `WindowManager::set_theme` so every window re-themes, matching
4174            // the app-wide `set_locale` path below. Applying
4175            // `WidgetTree::set_theme` inline would re-theme only the
4176            // originating window.
4177            self.pending_theme_request = Some(theme);
4178        }
4179        if ctx.follow_system_request {
4180            // Stored, not applied: the app layer switches to
4181            // `ThemeMode::Native` and recomputes the theme from the current
4182            // OS colours, fanning it to every window.
4183            self.pending_follow_system_request = true;
4184        }
4185        if let Some(locale) = ctx.locale_request {
4186            // Stored, not applied: the app layer must route this through
4187            // `WindowManager::set_locale` so the `I18nManager`'s active
4188            // locale and direction stay in sync. Applying via
4189            // `WidgetTree::set_locale` alone would leave `tr!` bindings
4190            // reading the old translations.
4191            self.pending_locale_request = Some(locale);
4192        }
4193        if let Some(scale) = ctx.text_scale_request {
4194            // Stored, not applied: the app layer routes this through
4195            // `WindowManager::set_text_scale` so every window re-scales its
4196            // text. Applying `WidgetTree::set_user_text_scale` inline would
4197            // grow only the originating window.
4198            self.pending_text_scale_request = Some(scale);
4199        }
4200        // Last, and with a context of their own: `Space` on a data view's
4201        // focused row runs the row's published toggle, and a checkbox's toggle
4202        // fires the app's `on_change`, which may send an intent or open a
4203        // window. Running them here rather than inside the mutation drain is
4204        // what gives them an `EventContext`; the drain resolved which action to
4205        // run against the live tree and handed it back.
4206        if !deferred_row_activations.is_empty() {
4207            self.run_with_event_context(&mut *ops, move |ctx| {
4208                for action in deferred_row_activations {
4209                    action(ctx);
4210                }
4211            });
4212        }
4213    }
4214
4215    /// Returns the row activations it resolved but could not run: they need an
4216    /// [`EventContext`], and this method has no `ops` to build one from. The
4217    /// caller runs them once the drain is finished, the way
4218    /// [`WidgetTree::run_mount_actions`](crate::WidgetTree::run_mount_actions)
4219    /// does.
4220    #[must_use]
4221    fn apply_tree_mutations(
4222        &mut self,
4223        mutations: Vec<crate::widget::TreeMutation>,
4224    ) -> Vec<std::rc::Rc<dyn Fn(&mut crate::widget::EventContext)>> {
4225        let mut deferred_row_activations = Vec::new();
4226        use crate::binding::BindingLevel;
4227        use crate::widget::TreeMutation;
4228
4229        for mutation in mutations {
4230            match mutation {
4231                TreeMutation::SetDormant(id) => {
4232                    self.park_subtree(id);
4233                }
4234                TreeMutation::Activate(id) => self.arena.activate(id),
4235                TreeMutation::Destroy(id) => {
4236                    // Route through `destroy_subtree`, NOT the bare
4237                    // `arena.destroy`: the latter only unlinks nodes from
4238                    // the slotmap and leaks everything the widget owned —
4239                    // animation-scheduler entries (which hold strong
4240                    // `Signal<f32>` clones, so the widget keeps animating
4241                    // after it's gone), animated-quad slots, event-source
4242                    // subscriptions, registered shortcuts, bindings, and
4243                    // gesture ownership — and leaves `focused`/`hovered`
4244                    // dangling at a removed id. This mirrors the build-time
4245                    // `BuildContext::destroy_subtree`, including dismissing
4246                    // any overlay that still references the subtree so the
4247                    // manager doesn't retain a stale content reference.
4248                    if let Some(overlay_id) = self.overlay_manager().find_by_content(id) {
4249                        self.dismiss_overlay(overlay_id);
4250                    }
4251                    self.destroy_subtree(id);
4252                }
4253                // Build now, not next frame: the same handler is about to show
4254                // an overlay over this node and move focus into it, and both
4255                // read the subtree. See `EventContext::materialize_now`.
4256                TreeMutation::MaterializeNow(id) => {
4257                    if self.arena.get(id).is_some() {
4258                        self.rebuild_single_widget(id);
4259                    }
4260                }
4261                TreeMutation::RowSpaceActivate { row, fallback } => {
4262                    // Resolve against the *live* tree: a data view rebuilds its
4263                    // rows as they realize, so the row that was focused when
4264                    // the key arrived may have been rebuilt since.
4265                    //
4266                    // Resolve here, run later. The action carries an
4267                    // `EventContext` so a row's checkbox fires its `on_change`
4268                    // on this path exactly as it does under the pointer; this
4269                    // method has no `ops` to build one from, so the caller runs
4270                    // it after the drain.
4271                    deferred_row_activations.push(self.keyboard_toggle_in(row).unwrap_or(fallback));
4272                }
4273                TreeMutation::WithWidgetMut { id, dirty, apply } => {
4274                    // Run the typed mutation while `&mut arena` is live, then
4275                    // drop the borrow before dirty-marking (the `mark_*` calls
4276                    // re-borrow the arena). Only dirty-mark a live node so we
4277                    // never call `mark_ancestors_need_layout` on a destroyed id.
4278                    let existed = if let Some(any) =
4279                        self.arena.get_mut(id).and_then(|n| n.widget.as_any_mut())
4280                    {
4281                        apply(any);
4282                        true
4283                    } else {
4284                        false
4285                    };
4286                    if existed {
4287                        match dirty {
4288                            BindingLevel::RepaintOnly => self.arena.mark_needs_paint(id),
4289                            BindingLevel::SubtreeRepaint => self.arena.mark_subtree_needs_paint(id),
4290                            BindingLevel::Relayout => {
4291                                self.arena.mark_needs_layout(id);
4292                                self.arena.mark_ancestors_need_layout(id);
4293                            }
4294                            BindingLevel::Rebuild => {
4295                                self.arena.mark_needs_rebuild(id);
4296                                self.arena.mark_ancestors_need_layout(id);
4297                            }
4298                            BindingLevel::AccessibilityOnly => self.a11y_dirty = true,
4299                        }
4300                    }
4301                }
4302            }
4303        }
4304        deferred_row_activations
4305    }
4306
4307    /// Hit-test at a point for the **mouse, exactly** — the meaning this door
4308    /// has always had, and keeps.
4309    ///
4310    /// A mouse cursor's hot-spot is exact, so neither hit-targeting mechanism
4311    /// applies to it: the outset pre-pass sees zero insets and the miss-only
4312    /// slop pass short-circuits on a zero radius. A caller that holds a pointer
4313    /// should use [`hit_test_for`](Self::hit_test_for) instead, which is the
4314    /// same test for a mouse and the widened one for a finger or a stylus.
4315    pub fn hit_test(&self, point: Point) -> Option<WidgetId> {
4316        self.hit_test_excluding_overlay_and_widget(point, None, None)
4317    }
4318
4319    /// Hit-test at a point on behalf of a named pointer.
4320    ///
4321    /// Runs the exact pass with that pointer's `Widget::hit_outset`, then — only
4322    /// if the exact pass found nothing eligible — the miss-only slop pass. For
4323    /// [`PointerKind::Mouse`](teksilo_tokens::PointerKind::Mouse) this is
4324    /// exactly [`hit_test`](Self::hit_test).
4325    ///
4326    /// Candidates are restricted to the **topmost overlay layer the exact pass
4327    /// entered**: a press inside an open menu can be re-attributed to a menu
4328    /// row, never to a control on the page behind it.
4329    pub fn hit_test_for(
4330        &self,
4331        point: Point,
4332        pointer: &crate::pointer::PointerInfo,
4333    ) -> Option<WidgetId> {
4334        self.hit_test_for_excluding(point, pointer, None, None)
4335    }
4336
4337    /// [`hit_test_for`](Self::hit_test_for) with the drag-and-drop exclusions of
4338    /// [`hit_test_excluding_overlay_and_widget`](Self::hit_test_excluding_overlay_and_widget).
4339    pub fn hit_test_for_excluding(
4340        &self,
4341        point: Point,
4342        pointer: &crate::pointer::PointerInfo,
4343        exclude_overlay: Option<crate::overlay::OverlayId>,
4344        exclude_widget: Option<WidgetId>,
4345    ) -> Option<WidgetId> {
4346        let surfaces = self.text_surfaces();
4347        let read_only = |id: WidgetId| surfaces.is_read_only(id);
4348        let hit =
4349            crate::pointer::hit_slop::HitContext::new(pointer.kind, &self.effective_theme.input)
4350                .direction(self.layout_direction)
4351                .read_only_probe(&read_only);
4352        self.hit_test_with(point, exclude_overlay, exclude_widget, &hit)
4353    }
4354
4355    /// Hit-test at a point, excluding a specific overlay and widget from consideration.
4356    /// Used during drag-and-drop to exclude the preview overlay and its content widget,
4357    /// so they don't block hit-testing of the actual drop targets underneath.
4358    ///
4359    /// **Mouse, exact** — the pointer-aware twin is
4360    /// [`hit_test_for_excluding`](Self::hit_test_for_excluding).
4361    pub fn hit_test_excluding_overlay_and_widget(
4362        &self,
4363        point: Point,
4364        exclude_overlay: Option<crate::overlay::OverlayId>,
4365        exclude_widget: Option<WidgetId>,
4366    ) -> Option<WidgetId> {
4367        self.hit_test_with(
4368            point,
4369            exclude_overlay,
4370            exclude_widget,
4371            &crate::pointer::hit_slop::HitContext::mouse(),
4372        )
4373    }
4374
4375    /// The one hit-test body: overlay first, then the arena, under whichever
4376    /// [`HitContext`](crate::pointer::hit_slop::HitContext) the caller built.
4377    pub(crate) fn hit_test_with(
4378        &self,
4379        point: Point,
4380        exclude_overlay: Option<crate::overlay::OverlayId>,
4381        exclude_widget: Option<WidgetId>,
4382        hit: &crate::pointer::hit_slop::HitContext<'_>,
4383    ) -> Option<WidgetId> {
4384        if let Some(overlay_id) = self.overlay_manager.hit_test(point) {
4385            if Some(overlay_id) == exclude_overlay {
4386                // Skip this excluded overlay, fall through to widget tree
4387            } else if let Some(overlay) = self.overlay_manager.overlay(overlay_id) {
4388                // A modal's scrim dims the window's chrome but leaves it live.
4389                if self.overlay_manager.is_modal_scrim(overlay)
4390                    && let Some(chrome) = self.window_chrome_under_modal(point, exclude_widget, hit)
4391                {
4392                    return Some(chrome);
4393                }
4394                // Scoped to the overlay's content: this is what restricts the
4395                // slop pass's candidates to the topmost layer the exact pass
4396                // entered.
4397                let content_id = overlay.content_id;
4398                if let Some(found) =
4399                    self.arena
4400                        .hit_test_in_subtree_with_slop(content_id, point, exclude_widget, hit)
4401                {
4402                    return Some(found);
4403                }
4404                // The overlay was chosen by its **bounds** and its content
4405                // claimed nothing at this point. For every ordinary overlay
4406                // that is the end of the search — answering `None` is what
4407                // keeps the slop pass inside the one layer the exact pass
4408                // entered, so a near-miss on a menu row cannot be beaten by a
4409                // control behind the menu.
4410                //
4411                // An overlay whose content root declares `event_pass_through`
4412                // is the exception, because that flag already means "what I did
4413                // not claim belongs to whatever is behind me": the tree's
4414                // walker honours it for an ordinary node *after* its children
4415                // miss, and an overlay root is not an exception to it. Without
4416                // this, a viewport-sized pass-through layer — the placement the
4417                // text-affordance band was written for — stops the surface
4418                // under it taking presses at all. The widening is confined to
4419                // that flag: an overlay that does not set it still returns
4420                // here, so no ordinary overlay's candidate set changes.
4421                if !self
4422                    .arena
4423                    .get(content_id)
4424                    .is_some_and(|node| node.event_pass_through)
4425                {
4426                    return None;
4427                }
4428            }
4429        }
4430
4431        if self.overlay_manager.topmost_modal().is_some() {
4432            return self.window_chrome_under_modal(point, exclude_widget, hit);
4433        }
4434
4435        // The walk of the arena's roots honours event_pass_through and
4436        // clips_children. An overlay's content is one of those roots, and an
4437        // inert one is left out: the stack has stepped over it above, and a
4438        // point over it with nothing beneath it on the stack would otherwise
4439        // land in it here, wherever its root falls in the walk.
4440        let mut roots = self.arena.roots();
4441        let inert: Vec<WidgetId> = self
4442            .overlay_manager
4443            .stack
4444            .iter()
4445            .filter(|overlay| overlay.inert)
4446            .map(|overlay| overlay.content_id)
4447            .collect();
4448        if !inert.is_empty() {
4449            roots.retain(|root| !inert.contains(root));
4450        }
4451        self.arena
4452            .hit_test_roots_with_slop(roots, point, exclude_widget, hit)
4453    }
4454}
4455
4456impl WidgetTree {
4457    /// What a point on the page takes while a modal is open: only the
4458    /// window's own chrome (a title bar's drag surface, its window buttons,
4459    /// the resize edges; [`HandlerSet::window_chrome`]). The window system's
4460    /// frame stays live above a dialog in a window, so a window drawing its
4461    /// own frame keeps it live too, as libadwaita's dialogs leave the window
4462    /// draggable and WinUI's leave the caption buttons working.
4463    ///
4464    /// The closest chrome node above the page's own hit takes the point, so a
4465    /// press on app content a drag surface holds (a title) moves the window
4466    /// and never reaches that content. A gesture dead zone on the way, which
4467    /// is how an app puts a control in a title bar, means the point is the
4468    /// app's, and it goes nowhere: the app stays behind its modal.
4469    ///
4470    /// [`HandlerSet::window_chrome`]: crate::widget_builder::HandlerSet::window_chrome
4471    fn window_chrome_under_modal(
4472        &self,
4473        point: Point,
4474        exclude_widget: Option<WidgetId>,
4475        hit: &crate::pointer::hit_slop::HitContext<'_>,
4476    ) -> Option<WidgetId> {
4477        let overlays: Vec<WidgetId> = self
4478            .overlay_manager
4479            .stack
4480            .iter()
4481            .map(|overlay| overlay.content_id)
4482            .collect();
4483        let mut roots = self.arena.roots();
4484        roots.retain(|root| !overlays.contains(root));
4485        let found = self
4486            .arena
4487            .hit_test_roots_with_slop(roots, point, exclude_widget, hit)?;
4488        let mut node = Some(found);
4489        while let Some(id) = node {
4490            let current = self.arena.get(id)?;
4491            if current.window_chrome {
4492                return Some(id);
4493            }
4494            if current.gesture_dead_zone {
4495                return None;
4496            }
4497            node = self.arena.parent(id);
4498        }
4499        None
4500    }
4501}
4502
4503/// Whether this keystroke is one of the chords that ask for a context menu.
4504///
4505/// Three routes, because no single one exists on every platform:
4506///
4507/// * **The dedicated key.** `VK_APPS` on Windows, `keysyms::Menu` on X11 and
4508///   Wayland. `winit-0.30.13`'s AppKit backend references
4509///   `NamedKey::ContextMenu` zero times, so macOS never produces it.
4510/// * **Shift+F10.** The convention Windows, GTK and Qt all honour, and the one
4511///   thing a Windows or Linux keyboard without a Menu key can still reach.
4512/// * **Ctrl+Shift+M on macOS.** Neither of the above is available there: Mac
4513///   keyboards have no Menu key, and F10 is a media key under the default
4514///   "Use F1, F2 etc. as standard function keys = off" setting, so Shift+F10
4515///   may never arrive as F10 at all. Kept off the other platforms, where
4516///   Ctrl+Shift+M is a plausible application binding.
4517///
4518/// Modifiers are matched exactly. Shift+F10 with Ctrl held is a different
4519/// gesture and must reach the application unchanged.
4520fn is_context_menu_chord(key: Key, modifiers: Modifiers) -> bool {
4521    match key {
4522        Key::ContextMenu => modifiers == Modifiers::NONE,
4523        Key::F10 => modifiers == Modifiers::SHIFT,
4524        #[cfg(target_os = "macos")]
4525        Key::M => modifiers == Modifiers::CTRL | Modifiers::SHIFT,
4526        _ => false,
4527    }
4528}
4529
4530#[cfg(test)]
4531mod tests {
4532    use super::*;
4533    use crate::test_widgets::FillWidget;
4534    use crate::widget::CursorIcon;
4535    use crate::widget_builder::WidgetBuilder;
4536
4537    #[test]
4538    fn pointer_enter_leave_synthesized() {
4539        let mut tree = WidgetTree::new();
4540        let widget = tree.add(FillWidget::new());
4541        tree.layout(SizeProposal::exact(100.0, 50.0));
4542        tree.pointer_move(Point::new(50.0, 25.0));
4543        assert_eq!(tree.hovered(), Some(widget));
4544        tree.pointer_move(Point::new(200.0, 200.0));
4545        assert_eq!(tree.hovered(), None);
4546    }
4547
4548    #[test]
4549    fn pointer_hover_updates_current_cursor() {
4550        let mut tree = WidgetTree::new();
4551        tree.add(FillWidget::new().cursor(CursorIcon::ColResize));
4552        tree.layout(SizeProposal::exact(100.0, 50.0));
4553
4554        tree.pointer_move(Point::new(50.0, 25.0));
4555        assert_eq!(tree.current_cursor(), CursorIcon::ColResize);
4556
4557        tree.pointer_move(Point::new(200.0, 200.0));
4558        assert_eq!(tree.current_cursor(), CursorIcon::Default);
4559    }
4560
4561    /// A leaf that declares its cursor from `build()` through
4562    /// `apply_self_handlers`, the route a composing widget takes.
4563    #[derive(Debug)]
4564    struct SelfDeclared(CursorIcon);
4565
4566    impl crate::widget::Widget for SelfDeclared {
4567        fn build(&mut self, ctx: &mut crate::build_context::BuildContext) -> Vec<WidgetId> {
4568            ctx.apply_self_handlers(crate::widget_builder::HandlerSet::new().cursor(self.0));
4569            Vec::new()
4570        }
4571
4572        fn layout_response(
4573            &self,
4574            proposal: SizeProposal,
4575            _ctx: &crate::widget::LayoutContext,
4576        ) -> crate::widget::LayoutResponse {
4577            proposal.resolve(100.0, 50.0).into()
4578        }
4579    }
4580
4581    /// A test reads the cursor two ways: `current_cursor` is the window's
4582    /// running answer and follows the hover, `declared_cursor` is what a node
4583    /// asks for and does not care where the pointer is. Both declaration
4584    /// routes (`.cursor(..)` and `apply_self_handlers`) land in the latter,
4585    /// and "declares nothing" is `None`, distinct from declaring `Default`.
4586    #[test]
4587    fn declared_cursor_reads_what_a_node_asks_for_and_current_cursor_follows_the_hover() {
4588        let over = Point::new(50.0, 25.0);
4589        let away = Point::new(200.0, 200.0);
4590
4591        // `.cursor(..)` through the builder.
4592        let mut tree = WidgetTree::new();
4593        let built = tree.add(FillWidget::new().cursor(CursorIcon::ColResize));
4594        tree.layout(SizeProposal::exact(100.0, 50.0));
4595        assert_eq!(tree.declared_cursor(built), Some(CursorIcon::ColResize));
4596        assert_eq!(
4597            tree.current_cursor(),
4598            CursorIcon::Default,
4599            "not hovered yet"
4600        );
4601        tree.pointer_move(over);
4602        assert_eq!(tree.current_cursor(), CursorIcon::ColResize);
4603        assert_eq!(tree.declared_cursor(built), Some(CursorIcon::ColResize));
4604        tree.pointer_move(away);
4605        assert_eq!(tree.current_cursor(), CursorIcon::Default);
4606        assert_eq!(
4607            tree.declared_cursor(built),
4608            Some(CursorIcon::ColResize),
4609            "the declaration does not depend on the pointer",
4610        );
4611
4612        // `apply_self_handlers` in `build()`.
4613        let mut tree = WidgetTree::new();
4614        let own = tree.add(SelfDeclared(CursorIcon::Crosshair));
4615        tree.layout(SizeProposal::exact(100.0, 50.0));
4616        assert_eq!(tree.declared_cursor(own), Some(CursorIcon::Crosshair));
4617        tree.pointer_move(over);
4618        assert_eq!(tree.current_cursor(), CursorIcon::Crosshair);
4619        tree.pointer_move(away);
4620        assert_eq!(tree.current_cursor(), CursorIcon::Default);
4621
4622        // Nothing declared, and an explicit `Default`.
4623        let mut tree = WidgetTree::new();
4624        let plain = tree.add(FillWidget::new());
4625        tree.layout(SizeProposal::exact(100.0, 50.0));
4626        assert_eq!(tree.declared_cursor(plain), None);
4627        let mut tree = WidgetTree::new();
4628        let explicit = tree.add(FillWidget::new().cursor(CursorIcon::Default));
4629        tree.layout(SizeProposal::exact(100.0, 50.0));
4630        assert_eq!(
4631            tree.declared_cursor(explicit),
4632            Some(CursorIcon::Default),
4633            "declaring the default cursor is not declaring nothing",
4634        );
4635    }
4636
4637    /// A handler's `set_cursor` outlives its dispatch, so a handler that
4638    /// re-decides the cursor on every move needs a way to stop deciding.
4639    ///
4640    /// Going quiet does not do it: the cursor moves only when something writes
4641    /// to it, and the node-declared cursor is written on `PointerEnter` /
4642    /// `PointerLeave` alone — so while the pointer stays inside one node there
4643    /// is no second writer, and the handler's last word simply stands. That is
4644    /// what `release_cursor` withdraws, and it withdraws *to the node's own
4645    /// declaration*, not to `Default`.
4646    #[test]
4647    fn release_cursor_hands_the_cursor_back_to_the_node_that_declared_it() {
4648        // Overrides itself to `Crosshair` on the left third of the widget and
4649        // withdraws everywhere else — the shape of any handler that arbitrates
4650        // its own affordance against the node it sits on.
4651        let mut tree = WidgetTree::new();
4652        tree.add(
4653            FillWidget::new()
4654                .cursor(CursorIcon::ColResize)
4655                .on_pointer_event(|event, ctx| {
4656                    if let WidgetEvent::PointerMove { position, .. } = event {
4657                        if position.x < 30.0 {
4658                            ctx.set_cursor(CursorIcon::Crosshair);
4659                        } else {
4660                            ctx.release_cursor();
4661                        }
4662                    }
4663                    EventResponse::Ignored
4664                }),
4665        );
4666        tree.layout(SizeProposal::exact(100.0, 50.0));
4667
4668        tree.pointer_move(Point::new(10.0, 25.0));
4669        assert_eq!(
4670            tree.current_cursor(),
4671            CursorIcon::Crosshair,
4672            "the handler outranks the node it is attached to",
4673        );
4674        tree.pointer_move(Point::new(60.0, 25.0));
4675        assert_eq!(
4676            tree.current_cursor(),
4677            CursorIcon::ColResize,
4678            "and hands it back to the node, not to Default — no enter/leave \
4679             fires on a move within one node, so nothing else could",
4680        );
4681        tree.pointer_move(Point::new(10.0, 25.0));
4682        assert_eq!(
4683            tree.current_cursor(),
4684            CursorIcon::Crosshair,
4685            "and can take it again"
4686        );
4687        tree.pointer_move(Point::new(200.0, 200.0));
4688        assert_eq!(
4689            tree.current_cursor(),
4690            CursorIcon::Default,
4691            "leaving the node clears both the override and the declaration",
4692        );
4693    }
4694
4695    /// The withdrawal is a no-op for a handler that never spoke, and resolves
4696    /// to `Default` when the chain declares nothing — so a handler may call it
4697    /// unconditionally without having to remember whether it once set a cursor.
4698    #[test]
4699    fn release_cursor_is_a_no_op_with_nothing_to_undo() {
4700        let mut tree = WidgetTree::new();
4701        tree.add(
4702            FillWidget::new()
4703                .cursor(CursorIcon::ColResize)
4704                .on_pointer_event(|event, ctx| {
4705                    if matches!(event, WidgetEvent::PointerMove { .. }) {
4706                        ctx.release_cursor();
4707                    }
4708                    EventResponse::Ignored
4709                }),
4710        );
4711        tree.layout(SizeProposal::exact(100.0, 50.0));
4712        tree.pointer_move(Point::new(50.0, 25.0));
4713        assert_eq!(tree.current_cursor(), CursorIcon::ColResize);
4714
4715        // Same handler over a node that declares nothing.
4716        let mut tree = WidgetTree::new();
4717        tree.add(FillWidget::new().on_pointer_event(|event, ctx| {
4718            if let WidgetEvent::PointerMove { position, .. } = event {
4719                if position.x < 30.0 {
4720                    ctx.set_cursor(CursorIcon::Crosshair);
4721                } else {
4722                    ctx.release_cursor();
4723                }
4724            }
4725            EventResponse::Ignored
4726        }));
4727        tree.layout(SizeProposal::exact(100.0, 50.0));
4728        tree.pointer_move(Point::new(10.0, 25.0));
4729        assert_eq!(tree.current_cursor(), CursorIcon::Crosshair);
4730        tree.pointer_move(Point::new(60.0, 25.0));
4731        assert_eq!(
4732            tree.current_cursor(),
4733            CursorIcon::Default,
4734            "nothing declared a cursor for this chain, so the hand-back \
4735             resolves to Default",
4736        );
4737    }
4738
4739    /// A handler that speaks during the `PointerEnter` itself still outranks
4740    /// the node it entered — and the node's declaration is remembered anyway,
4741    /// so the hand-back has somewhere to go.
4742    ///
4743    /// The two used to share one slot, where the handler's later write erased
4744    /// the declaration outright; they are separate channels now precisely so
4745    /// this case keeps both.
4746    #[test]
4747    fn an_on_hover_override_does_not_erase_the_declaration_it_outranks() {
4748        let mut tree = WidgetTree::new();
4749        tree.add(
4750            FillWidget::new()
4751                .cursor(CursorIcon::ColResize)
4752                .on_hover(|entered, ctx| {
4753                    if entered {
4754                        ctx.set_cursor(CursorIcon::Crosshair);
4755                    }
4756                })
4757                .on_pointer_event(|event, ctx| {
4758                    if let WidgetEvent::PointerMove { position, .. } = event
4759                        && position.x >= 30.0
4760                    {
4761                        ctx.release_cursor();
4762                    }
4763                    EventResponse::Ignored
4764                }),
4765        );
4766        tree.layout(SizeProposal::exact(100.0, 50.0));
4767
4768        tree.pointer_move(Point::new(10.0, 25.0));
4769        assert_eq!(
4770            tree.current_cursor(),
4771            CursorIcon::Crosshair,
4772            "on_hover runs after the node cursor is applied, so it wins",
4773        );
4774        tree.pointer_move(Point::new(60.0, 25.0));
4775        assert_eq!(
4776            tree.current_cursor(),
4777            CursorIcon::ColResize,
4778            "and the node's declaration survived being overridden",
4779        );
4780    }
4781
4782    // A leaf that opts into typed introspection, so `with_widget_mut` /
4783    // `widget_as_any(_mut)` can reach it (the default `as_any_mut` is `None`).
4784    #[derive(Debug)]
4785    struct Bumpable {
4786        value: i32,
4787    }
4788
4789    impl crate::widget::Widget for Bumpable {
4790        fn layout_response(
4791            &self,
4792            proposal: SizeProposal,
4793            _ctx: &crate::widget::LayoutContext,
4794        ) -> crate::widget::LayoutResponse {
4795            proposal.resolve(10.0, 10.0).into()
4796        }
4797        fn as_any(&self) -> Option<&dyn std::any::Any> {
4798            Some(self)
4799        }
4800        fn as_any_mut(&mut self) -> Option<&mut dyn std::any::Any> {
4801            Some(self)
4802        }
4803    }
4804
4805    #[test]
4806    fn with_widget_mut_applies_and_dirty_marks() {
4807        let mut tree = WidgetTree::new();
4808        let id = tree.add(Bumpable { value: 0 });
4809        tree.layout(SizeProposal::exact(100.0, 100.0));
4810
4811        let mut ctx = EventContext::new();
4812        ctx.with_widget_mut::<Bumpable>(id, crate::binding::BindingLevel::Relayout, |b| {
4813            b.value = 42;
4814        });
4815        tree.collect_from_ctx(ctx, id);
4816
4817        let value = tree
4818            .widget_as_any(id)
4819            .and_then(|a| a.downcast_ref::<Bumpable>())
4820            .map(|b| b.value);
4821        assert_eq!(
4822            value,
4823            Some(42),
4824            "the deferred closure must mutate the live widget"
4825        );
4826        assert!(
4827            tree.needs_layout(),
4828            "Relayout dirty level must mark the tree for relayout"
4829        );
4830    }
4831
4832    #[test]
4833    #[cfg(debug_assertions)]
4834    #[should_panic(expected = "not the requested type")]
4835    fn with_widget_mut_wrong_type_panics_in_debug() {
4836        struct Other;
4837        let mut tree = WidgetTree::new();
4838        let id = tree.add(Bumpable { value: 0 });
4839        let mut ctx = EventContext::new();
4840        ctx.with_widget_mut::<Other>(
4841            id,
4842            crate::binding::BindingLevel::RepaintOnly,
4843            |_o: &mut Other| {},
4844        );
4845        // Bumpable opts into as_any_mut, so the closure runs and the
4846        // wrong-type downcast trips the debug_assert.
4847        tree.collect_from_ctx(ctx, id);
4848    }
4849
4850    #[test]
4851    fn with_widget_mut_closure_may_fire_observed_signals() {
4852        // Reentrancy guard. The closure runs inside `apply_tree_mutations`
4853        // while the target arena node is mutably borrowed. If it fires a
4854        // `Signal` whose observer sets *another* signal — the exact
4855        // `SceneView` shape (`item_change_signal` → bump `reconcile_dirty`) —
4856        // nothing may double-borrow the arena. The arena borrow is scoped to
4857        // the closure call and dropped before dirty-marking; signal/observer
4858        // work touches the binding registry, not the arena.
4859        use crate::signal::Signal;
4860        let mut tree = WidgetTree::new();
4861        let id = tree.add(Bumpable { value: 0 });
4862        tree.layout(SizeProposal::exact(100.0, 100.0));
4863
4864        let trigger = Signal::new(0_u64);
4865        let echo = Signal::new(0_u64);
4866        let echo_for_obs = echo.clone();
4867        let _obs = trigger.observe(move |v| echo_for_obs.set(*v));
4868
4869        let trigger_in = trigger.clone();
4870        let mut ctx = EventContext::new();
4871        ctx.with_widget_mut::<Bumpable>(id, crate::binding::BindingLevel::RepaintOnly, move |b| {
4872            b.value = 7;
4873            // Fires `_obs` synchronously, mid-deferred-apply.
4874            trigger_in.set(99);
4875        });
4876        tree.collect_from_ctx(ctx, id); // must not panic / double-borrow
4877
4878        assert_eq!(
4879            echo.get(),
4880            99,
4881            "the observer ran during the deferred mutation"
4882        );
4883        let value = tree
4884            .widget_as_any(id)
4885            .and_then(|a| a.downcast_ref::<Bumpable>())
4886            .map(|b| b.value);
4887        assert_eq!(value, Some(7));
4888    }
4889
4890    #[test]
4891    fn request_accessibility_update_forces_rewalk() {
4892        let mut tree = WidgetTree::new();
4893        let id = tree.add(Bumpable { value: 0 });
4894        tree.layout(SizeProposal::exact(100.0, 100.0));
4895        let _ = tree.sync_accessibility(); // populate cache, clears a11y_dirty
4896        assert!(
4897            !tree.a11y_dirty,
4898            "sync_accessibility should clear the dirty flag"
4899        );
4900
4901        let mut ctx = EventContext::new();
4902        ctx.request_accessibility_update();
4903        tree.collect_from_ctx(ctx, id);
4904        assert!(
4905            tree.a11y_dirty,
4906            "request_accessibility_update must force an AT re-walk"
4907        );
4908    }
4909
4910    #[test]
4911    fn rebuild_dirties_accessibility_tree() {
4912        // Regression for audit Blocker G1: every `BindingLevel::Rebuild`
4913        // consumer (ListView / TreeView / TableView / ComboBox / Calendar /
4914        // DockingLayout / ...) tears down and re-creates its subtree on an
4915        // ordinary model change, allocating fresh WidgetIds and changing the
4916        // AccessKit tree shape. That pass must dirty the cached AT snapshot,
4917        // or screen readers keep reading the pre-mutation tree indefinitely.
4918        let mut tree = WidgetTree::new();
4919        let id = tree.add(Bumpable { value: 0 });
4920        tree.layout(SizeProposal::exact(100.0, 100.0));
4921        let _ = tree.sync_accessibility(); // populate cache, clears a11y_dirty
4922        assert!(
4923            !tree.a11y_dirty,
4924            "sync_accessibility should clear the dirty flag"
4925        );
4926
4927        // Marking for rebuild is exactly what a Rebuild-level binding does;
4928        // the following layout pass drains pending rebuilds.
4929        tree.arena_mark_needs_rebuild_for_testing(id);
4930        tree.layout(SizeProposal::exact(100.0, 100.0));
4931        assert!(
4932            tree.a11y_dirty,
4933            "a rebuild must dirty the AT tree so the next sync re-walks"
4934        );
4935    }
4936
4937    #[test]
4938    fn bound_access_label_change_dirties_accessibility_tree() {
4939        use crate::signal::Signal;
4940        use crate::test_widgets::FillWidget;
4941        use crate::widget_builder::WidgetBuilder;
4942
4943        // Regression for audit G15: a reactive `.access_label(signal)` (and
4944        // likewise description / value) must register at AccessibilityOnly so
4945        // changing the signal re-walks the AT tree and re-resolves the
4946        // announced name. Previously only `access_hidden` was registered, so
4947        // label / description / value updates were invisible to screen readers.
4948        let label = Signal::new("first".to_string());
4949        let mut tree = WidgetTree::new();
4950        let _id = tree.add(FillWidget::new().access_label(label.clone()));
4951        tree.layout(SizeProposal::exact(100.0, 100.0));
4952        let _ = tree.sync_accessibility(); // populate cache, clears a11y_dirty
4953        assert!(!tree.a11y_dirty, "sync_accessibility should clear the flag");
4954
4955        label.set("second".to_string());
4956        tree.layout(SizeProposal::exact(100.0, 100.0));
4957        assert!(
4958            tree.a11y_dirty,
4959            "changing a bound access_label must dirty the AT tree"
4960        );
4961    }
4962
4963    #[test]
4964    fn disabled_ancestor_blocks_event_to_descendant() {
4965        use crate::signal::Signal;
4966        use crate::test_widgets::StackWidget;
4967        use std::cell::Cell;
4968        use std::rc::Rc;
4969
4970        let tapped = Rc::new(Cell::new(false));
4971        let flag = tapped.clone();
4972        let enabled = Signal::new(true);
4973
4974        let mut tree = WidgetTree::new();
4975        let child = tree.add(FillWidget::new().on_tap(move |_pos, _ctx| {
4976            flag.set(true);
4977        }));
4978        let parent = tree.add(StackWidget::new().child(child));
4979        tree.enabled_when(parent, enabled.clone());
4980        tree.layout(SizeProposal::exact(100.0, 50.0));
4981
4982        enabled.set(false);
4983        tree.click(child);
4984        assert!(
4985            !tapped.get(),
4986            "disabled ancestor should block descendant tap"
4987        );
4988
4989        enabled.set(true);
4990        tree.click(child);
4991        assert!(tapped.get(), "re-enabling should restore dispatch");
4992    }
4993
4994    #[test]
4995    fn pointer_positions_are_widget_local_at_nonzero_origin() {
4996        use crate::event::{Modifiers, PointerButton};
4997        use crate::test_widgets::InsetWidget;
4998        use std::cell::Cell;
4999        use std::rc::Rc;
5000
5001        // A 20px inset places the child at window origin (20, 20).
5002        let tap_pos: Rc<Cell<Option<Point>>> = Rc::new(Cell::new(None));
5003        let down_pos: Rc<Cell<Option<Point>>> = Rc::new(Cell::new(None));
5004        let drag_pos: Rc<Cell<Option<Point>>> = Rc::new(Cell::new(None));
5005        let (tp, dp, gp) = (tap_pos.clone(), down_pos.clone(), drag_pos.clone());
5006
5007        let mut tree = WidgetTree::new();
5008        let child = tree.add(
5009            FillWidget::new()
5010                .on_tap(move |ev, _ctx| tp.set(Some(ev.position)))
5011                .on_pointer_event(move |ev, _ctx| {
5012                    if let WidgetEvent::PointerDown { position, .. } = ev {
5013                        dp.set(Some(*position));
5014                    }
5015                    crate::event::EventResponse::Ignored
5016                })
5017                .on_drag(move |phase, _ctx| {
5018                    use crate::gesture::DragPhase;
5019                    match phase {
5020                        DragPhase::Started { position, .. }
5021                        | DragPhase::Moved { position, .. }
5022                        | DragPhase::Ended { position, .. } => gp.set(Some(position)),
5023                        _ => {}
5024                    }
5025                }),
5026        );
5027        let inset = tree.add(InsetWidget::new(20.0).set_child(child));
5028        let _ = inset;
5029        tree.layout(SizeProposal::exact(200.0, 200.0));
5030        assert_eq!(tree.bounds(child).origin(), Point::new(20.0, 20.0));
5031
5032        // A tap at window (50, 40) must reach the handler as local (30, 20).
5033        tree.dispatch_event(WidgetEvent::pointer_down(
5034            Point::new(50.0, 40.0),
5035            PointerButton::Primary,
5036            Modifiers::NONE,
5037        ));
5038        assert_eq!(
5039            down_pos.get(),
5040            Some(Point::new(30.0, 20.0)),
5041            "on_pointer_event PointerDown must be widget-local"
5042        );
5043        tree.dispatch_event(WidgetEvent::pointer_up(
5044            Point::new(50.0, 40.0),
5045            PointerButton::Primary,
5046            Modifiers::NONE,
5047        ));
5048        assert_eq!(
5049            tap_pos.get(),
5050            Some(Point::new(30.0, 20.0)),
5051            "on_tap position must be widget-local"
5052        );
5053
5054        // A drag (down then a move past the recognizer threshold) must
5055        // also deliver widget-local coordinates.
5056        tree.dispatch_event(WidgetEvent::pointer_down(
5057            Point::new(50.0, 40.0),
5058            PointerButton::Primary,
5059            Modifiers::NONE,
5060        ));
5061        // First move crosses the recognizer threshold (DragStarted);
5062        // the second reports a known DragMoved position.
5063        tree.dispatch_event(WidgetEvent::pointer_move(Point::new(65.0, 55.0)));
5064        tree.dispatch_event(WidgetEvent::pointer_move(Point::new(90.0, 70.0)));
5065        assert_eq!(
5066            drag_pos.get(),
5067            Some(Point::new(70.0, 50.0)),
5068            "on_drag position must be widget-local"
5069        );
5070    }
5071
5072    #[test]
5073    fn dormant_widget_not_hit_tested() {
5074        let mut tree = WidgetTree::new();
5075        let widget = tree.add(FillWidget::new());
5076        tree.layout(SizeProposal::exact(100.0, 50.0));
5077
5078        tree.pointer_move(Point::new(50.0, 25.0));
5079        assert_eq!(tree.hovered(), Some(widget));
5080
5081        tree.set_dormant(widget);
5082        tree.pointer_move(Point::new(200.0, 200.0));
5083        tree.pointer_move(Point::new(50.0, 25.0));
5084        assert_eq!(tree.hovered(), None);
5085    }
5086
5087    #[test]
5088    fn ancestor_pointer_handler_does_not_suppress_descendant_hover() {
5089        use crate::event::EventResponse;
5090        use crate::test_widgets::StackWidget;
5091        use std::cell::Cell;
5092        use std::rc::Rc;
5093
5094        // The child reports its own hover transitions via `on_hover`.
5095        let hovered = Rc::new(Cell::new(false));
5096        let h = hovered.clone();
5097
5098        let mut tree = WidgetTree::new();
5099        let child = tree.add(FillWidget::new().on_hover(move |entered, _ctx| h.set(entered)));
5100        // An ancestor whose `on_pointer_event` greedily claims everything it
5101        // previews — exactly the "drag-detecting ancestor" footgun. Before the
5102        // fix it consumed the descendant's `PointerEnter`/`Leave` in the
5103        // preview pass and the child's hover never fired.
5104        tree.add(
5105            StackWidget::new()
5106                .child(child)
5107                .on_pointer_event(|_event, _ctx| EventResponse::Handled),
5108        );
5109        tree.layout(SizeProposal::exact(100.0, 50.0));
5110
5111        tree.pointer_move(Point::new(50.0, 25.0));
5112        assert!(
5113            hovered.get(),
5114            "a greedy ancestor on_pointer_event must NOT swallow the child's PointerEnter"
5115        );
5116
5117        tree.pointer_move(Point::new(500.0, 500.0));
5118        assert!(
5119            !hovered.get(),
5120            "PointerLeave must likewise reach the child despite the ancestor"
5121        );
5122    }
5123
5124    /// **The other direction: a child must not swallow its ancestor's hover.**
5125    ///
5126    /// A row that reveals controls on hover puts interactive children inside
5127    /// itself, and the pointer leaves the row *through* one of them. The child's
5128    /// own `on_hover` used to handle the `PointerLeave` and stop the bubble there,
5129    /// so the row went on believing the pointer was still over it and kept its
5130    /// controls showing after the pointer had gone.
5131    #[test]
5132    fn a_child_hover_handler_does_not_swallow_its_ancestors() {
5133        use crate::test_widgets::StackWidget;
5134        use std::cell::Cell;
5135        use std::rc::Rc;
5136
5137        let (row, button) = (Rc::new(Cell::new(false)), Rc::new(Cell::new(false)));
5138        let (r, b) = (row.clone(), button.clone());
5139
5140        let mut tree = WidgetTree::new();
5141        let child = tree.add(FillWidget::new().on_hover(move |entered, _ctx| b.set(entered)));
5142        tree.add(
5143            StackWidget::new()
5144                .child(child)
5145                .on_hover(move |entered, _ctx| r.set(entered)),
5146        );
5147        tree.layout(SizeProposal::exact(100.0, 50.0));
5148
5149        tree.pointer_move(Point::new(50.0, 25.0));
5150        assert!(button.get(), "the child is hovered");
5151        assert!(row.get(), "and so is the row it is inside");
5152
5153        tree.pointer_move(Point::new(500.0, 500.0));
5154        assert!(!button.get(), "the child heard the leave");
5155        assert!(
5156            !row.get(),
5157            "and so did the row — a container is not still hovered because the \
5158             pointer left it through a button"
5159        );
5160    }
5161
5162    // NOTE: legacy `shortcut_intercepts_before_widget` test removed with
5163    // the ShortcutMap dispatch path. The new shortcut→intent interception
5164    // is built on top of `ShortcutRegistry` + `Action`.
5165
5166    // ── on_key_preview ──────────────────────────────────────────
5167
5168    #[test]
5169    fn key_preview_consumes_before_focused_on_key() {
5170        // root → mid → leaf (focused). Root consumes Enter via
5171        // on_key_preview; the leaf's on_key must NOT fire.
5172        use crate::event::EventResponse;
5173        use crate::test_widgets::StackWidget;
5174        use std::cell::Cell;
5175        use std::rc::Rc;
5176
5177        let leaf_fired = Rc::new(Cell::new(false));
5178        let leaf_flag = leaf_fired.clone();
5179        let preview_fired = Rc::new(Cell::new(false));
5180        let preview_flag = preview_fired.clone();
5181
5182        let mut tree = WidgetTree::new();
5183        let leaf = tree.add(FillWidget::new().focusable().on_key(move |event, _c| {
5184            // Only count KeyDown so the trailing KeyUp from
5185            // press_key doesn't trigger us spuriously.
5186            if matches!(event, WidgetEvent::KeyDown { .. }) {
5187                leaf_flag.set(true);
5188            }
5189            EventResponse::Handled
5190        }));
5191        let mid = tree.add(StackWidget::new().child(leaf));
5192        let _root = tree.add(
5193            StackWidget::new()
5194                .child(mid)
5195                .on_key_preview(move |event, _c| match event {
5196                    WidgetEvent::KeyDown {
5197                        key: Key::Enter, ..
5198                    } => {
5199                        preview_flag.set(true);
5200                        EventResponse::Handled
5201                    }
5202                    _ => EventResponse::Ignored,
5203                }),
5204        );
5205
5206        tree.layout(SizeProposal::exact(100.0, 50.0));
5207        tree.focus(leaf);
5208        tree.press_key(Key::Enter, Modifiers::NONE);
5209
5210        assert!(
5211            preview_fired.get(),
5212            "ancestor on_key_preview must fire for KeyDown on a focused descendant"
5213        );
5214        assert!(
5215            !leaf_fired.get(),
5216            "consuming the event in preview must prevent the focused widget's on_key from running"
5217        );
5218    }
5219
5220    #[test]
5221    fn key_preview_falls_through_when_returning_ignored() {
5222        // Same shape; this time the preview returns Ignored, so
5223        // the leaf's on_key must still fire.
5224        use crate::event::EventResponse;
5225        use crate::test_widgets::StackWidget;
5226        use std::cell::Cell;
5227        use std::rc::Rc;
5228
5229        let leaf_fired = Rc::new(Cell::new(false));
5230        let leaf_flag = leaf_fired.clone();
5231        let preview_fired = Rc::new(Cell::new(false));
5232        let preview_flag = preview_fired.clone();
5233
5234        let mut tree = WidgetTree::new();
5235        let leaf = tree.add(FillWidget::new().focusable().on_key(move |_e, _c| {
5236            leaf_flag.set(true);
5237            EventResponse::Handled
5238        }));
5239        let mid = tree.add(StackWidget::new().child(leaf));
5240        let _root = tree.add(
5241            StackWidget::new()
5242                .child(mid)
5243                .on_key_preview(move |_event, _c| {
5244                    preview_flag.set(true);
5245                    EventResponse::Ignored
5246                }),
5247        );
5248
5249        tree.layout(SizeProposal::exact(100.0, 50.0));
5250        tree.focus(leaf);
5251        tree.press_key(Key::Enter, Modifiers::NONE);
5252
5253        assert!(preview_fired.get(), "preview must always be invoked");
5254        assert!(
5255            leaf_fired.get(),
5256            "preview returning Ignored must not block the focused widget's on_key"
5257        );
5258    }
5259
5260    #[test]
5261    fn key_preview_excludes_focused_target_itself() {
5262        // Strict-ancestors-only: the focused widget's own
5263        // on_key_preview must NOT fire — the preview pass walks
5264        // strict ancestors only.
5265        use crate::event::EventResponse;
5266        use std::cell::Cell;
5267        use std::rc::Rc;
5268
5269        let preview_on_target = Rc::new(Cell::new(false));
5270        let pf = preview_on_target.clone();
5271
5272        let mut tree = WidgetTree::new();
5273        let leaf = tree.add(FillWidget::new().focusable().on_key_preview(move |_e, _c| {
5274            pf.set(true);
5275            EventResponse::Handled
5276        }));
5277        tree.layout(SizeProposal::exact(100.0, 50.0));
5278        tree.focus(leaf);
5279        tree.press_key(Key::Enter, Modifiers::NONE);
5280
5281        assert!(
5282            !preview_on_target.get(),
5283            "the focused widget itself must not see its own on_key_preview"
5284        );
5285    }
5286
5287    #[test]
5288    fn key_preview_root_to_target_order() {
5289        // Two ancestors with on_key_preview attached. The outer
5290        // (root-side) one must fire first; the closer one (still
5291        // ancestor of the focused leaf) fires second.
5292        use crate::event::EventResponse;
5293        use crate::test_widgets::StackWidget;
5294        use std::cell::RefCell;
5295        use std::rc::Rc;
5296
5297        let order: Rc<RefCell<Vec<&'static str>>> = Rc::new(RefCell::new(Vec::new()));
5298        let outer_log = order.clone();
5299        let inner_log = order.clone();
5300
5301        let mut tree = WidgetTree::new();
5302        let leaf = tree.add(FillWidget::new().focusable());
5303        let inner = tree.add(
5304            StackWidget::new()
5305                .child(leaf)
5306                .on_key_preview(move |event, _c| {
5307                    if matches!(event, WidgetEvent::KeyDown { .. }) {
5308                        inner_log.borrow_mut().push("inner");
5309                    }
5310                    EventResponse::Ignored
5311                }),
5312        );
5313        let _outer = tree.add(
5314            StackWidget::new()
5315                .child(inner)
5316                .on_key_preview(move |event, _c| {
5317                    if matches!(event, WidgetEvent::KeyDown { .. }) {
5318                        outer_log.borrow_mut().push("outer");
5319                    }
5320                    EventResponse::Ignored
5321                }),
5322        );
5323
5324        tree.layout(SizeProposal::exact(100.0, 50.0));
5325        tree.focus(leaf);
5326        tree.dispatch_event(WidgetEvent::KeyDown {
5327            key: Key::Enter,
5328            modifiers: Modifiers::NONE,
5329            text: None,
5330        });
5331
5332        assert_eq!(
5333            *order.borrow(),
5334            vec!["outer", "inner"],
5335            "preview must walk root → parent-of-target"
5336        );
5337    }
5338
5339    #[test]
5340    fn access_action_routes_to_cursored_target_not_focus() {
5341        // VoiceOver's VO+Space targets the node under the AT cursor (`b`),
5342        // even when keyboard focus is on a different control (`a`). The action
5343        // must fire on `b`, never get redirected to the focused `a`.
5344        use crate::signal::Signal;
5345        let a_fired = Signal::new(false);
5346        let b_fired = Signal::new(false);
5347        let a_cb = a_fired.clone();
5348        let b_cb = b_fired.clone();
5349
5350        let mut tree = WidgetTree::new();
5351        let a = tree.add(
5352            FillWidget::new().access_action(accesskit::Action::Click, move |_ctx| a_cb.set(true)),
5353        );
5354        let b = tree.add(
5355            FillWidget::new().access_action(accesskit::Action::Click, move |_ctx| b_cb.set(true)),
5356        );
5357        tree.layout(SizeProposal::exact(200.0, 100.0));
5358
5359        tree.focus(a);
5360        tree.dispatch_event(WidgetEvent::AccessAction {
5361            action: accesskit::Action::Click,
5362            target: Some(b),
5363            target_node: crate::accessibility::widget_id_to_node_id(b),
5364            data: None,
5365        });
5366
5367        assert!(b_fired.get(), "the cursored target must receive the action");
5368        assert!(
5369            !a_fired.get(),
5370            "the keyboard-focused widget must NOT receive an action targeting another node"
5371        );
5372    }
5373
5374    #[test]
5375    fn access_action_without_target_is_dropped_not_redirected_to_focus() {
5376        // An action with no (or an inactive) target must be dropped — never
5377        // silently re-routed to whatever holds keyboard focus.
5378        use crate::signal::Signal;
5379        let fired = Signal::new(false);
5380        let cb = fired.clone();
5381
5382        let mut tree = WidgetTree::new();
5383        let widget = tree.add(
5384            FillWidget::new().access_action(accesskit::Action::Click, move |_ctx| cb.set(true)),
5385        );
5386        tree.layout(SizeProposal::exact(200.0, 100.0));
5387
5388        tree.focus(widget);
5389        tree.dispatch_event(WidgetEvent::AccessAction {
5390            action: accesskit::Action::Click,
5391            target: None,
5392            target_node: crate::accessibility::root_node_id(),
5393            data: None,
5394        });
5395
5396        assert!(
5397            !fired.get(),
5398            "a target-less action must not be redirected to the focused widget"
5399        );
5400    }
5401
5402    // NOTE: legacy `scoped_shortcut_fires_when_focused_in_subtree` test
5403    // removed along with the ShortcutMap dispatch path. Scope-aware
5404    // dispatch is handled by the new ShortcutRegistry.
5405
5406    // --- Intent / Action dispatch ------------------------------
5407
5408    #[test]
5409    fn shortcut_fires_matching_action_on_source_widget() {
5410        use crate::action::Action;
5411        use crate::shortcut::{KeyStroke, Shortcut};
5412        use std::cell::Cell;
5413        use std::rc::Rc;
5414
5415        let fired = Rc::new(Cell::new(false));
5416        let fired_flag = fired.clone();
5417
5418        let mut tree = WidgetTree::new();
5419        let widget = tree.add(FillWidget::new().focusable());
5420        tree.push_action(
5421            widget,
5422            Action::new("app.save").on_invoke(move |_intent, _ctx| {
5423                fired_flag.set(true);
5424            }),
5425        );
5426        tree.shortcut_registry_mut().register(
5427            Shortcut::new("app.save")
5428                .primary(KeyStroke::command(Key::S))
5429                .build(),
5430        );
5431
5432        tree.layout(SizeProposal::exact(100.0, 50.0));
5433        tree.focus(widget);
5434
5435        tree.press_key(Key::S, Modifiers::COMMAND);
5436        assert!(fired.get(), "matching action must fire on KeyDown");
5437    }
5438
5439    #[test]
5440    fn global_shortcut_fires_without_focused_widget() {
5441        use crate::action::Action;
5442        use crate::shortcut::{KeyStroke, Shortcut};
5443        use std::cell::Cell;
5444        use std::rc::Rc;
5445
5446        // Regression: a global shortcut must fire even when no widget
5447        // is focused. A root-registered action should still receive
5448        // the intent (anchored at the root as a fallback).
5449        let fired = Rc::new(Cell::new(false));
5450        let fired_flag = fired.clone();
5451
5452        let mut tree = WidgetTree::new();
5453        let root = tree.add(FillWidget::new());
5454        tree.push_action(
5455            root,
5456            Action::new("app.save").on_invoke(move |_intent, _ctx| {
5457                fired_flag.set(true);
5458            }),
5459        );
5460        tree.shortcut_registry_mut().register(
5461            Shortcut::new("app.save")
5462                .primary(KeyStroke::command(Key::S))
5463                .build(),
5464        );
5465
5466        tree.layout(SizeProposal::exact(100.0, 50.0));
5467        // Deliberately no focus() call.
5468
5469        tree.press_key(Key::S, Modifiers::COMMAND);
5470        assert!(
5471            fired.get(),
5472            "global shortcut must fire without a focused widget"
5473        );
5474    }
5475
5476    #[test]
5477    fn global_shortcut_fires_after_focused_widget_destroyed() {
5478        use crate::action::Action;
5479        use crate::shortcut::{KeyStroke, Shortcut};
5480        use std::cell::Cell;
5481        use std::rc::Rc;
5482
5483        // Regression: if the focused widget is destroyed (e.g. during a
5484        // rebuild after a settings-panel rebind), focus must be cleared
5485        // so the next global shortcut falls through to the root-anchor
5486        // path instead of dispatching from a stale, destroyed id.
5487        let fired = Rc::new(Cell::new(false));
5488        let fired_flag = fired.clone();
5489
5490        let mut tree = WidgetTree::new();
5491        let root = tree.add(FillWidget::new());
5492        let focusable = tree.add_child(root, FillWidget::new().focusable());
5493        tree.push_action(
5494            root,
5495            Action::new("app.save").on_invoke(move |_intent, _ctx| {
5496                fired_flag.set(true);
5497            }),
5498        );
5499        tree.shortcut_registry_mut().register(
5500            Shortcut::new("app.save")
5501                .primary(KeyStroke::command(Key::S))
5502                .build(),
5503        );
5504
5505        tree.layout(SizeProposal::exact(100.0, 50.0));
5506        tree.focus(focusable);
5507        assert_eq!(tree.focused(), Some(focusable));
5508
5509        // Destroy the focused subtree (simulates a rebuild that drops
5510        // the currently-focused Rebind button).
5511        tree.destroy_subtree(focusable);
5512        assert_eq!(tree.focused(), None, "focus must clear when destroyed");
5513
5514        tree.press_key(Key::S, Modifiers::COMMAND);
5515        assert!(
5516            fired.get(),
5517            "global shortcut must still fire after the focused widget is destroyed"
5518        );
5519    }
5520
5521    #[test]
5522    fn scoped_shortcut_matches_only_when_focus_in_scope() {
5523        use crate::action::Action;
5524        use crate::shortcut::{KeyStroke, Shortcut, ShortcutScope};
5525        use std::cell::Cell;
5526        use std::rc::Rc;
5527
5528        let fired = Rc::new(Cell::new(0));
5529        let fired_flag = fired.clone();
5530
5531        let mut tree = WidgetTree::new();
5532        let scope_root = tree.add(FillWidget::new().focusable());
5533        let inside = tree.add_child(scope_root, FillWidget::new().focusable());
5534        let outside = tree.add(FillWidget::new().focusable());
5535
5536        tree.push_action(
5537            scope_root,
5538            Action::new("editor.find").on_invoke(move |_i, _c| {
5539                fired_flag.set(fired_flag.get() + 1);
5540            }),
5541        );
5542        tree.shortcut_registry_mut().register(
5543            Shortcut::new("editor.find")
5544                .primary(KeyStroke::command(Key::F))
5545                .scope(ShortcutScope::Scoped(scope_root))
5546                .build(),
5547        );
5548
5549        tree.layout(SizeProposal::exact(200.0, 100.0));
5550
5551        // Focus outside the scope: the shortcut does NOT activate.
5552        tree.focus(outside);
5553        tree.press_key(Key::F, Modifiers::COMMAND);
5554        assert_eq!(
5555            fired.get(),
5556            0,
5557            "scoped shortcut must not fire outside scope"
5558        );
5559
5560        // Focus inside the scope: it fires.
5561        tree.focus(inside);
5562        tree.press_key(Key::F, Modifiers::COMMAND);
5563        assert_eq!(
5564            fired.get(),
5565            1,
5566            "scoped shortcut must fire when focus in scope"
5567        );
5568    }
5569
5570    #[test]
5571    fn same_chord_scoped_first_falls_back_to_global_when_focus_outside() {
5572        // Defect 1: a Scoped binding that sorts first by id must NOT
5573        // shadow the slot when focus is outside its subtree — the
5574        // applicable Global binding fires instead. (`editor.saveBlock`
5575        // < `zzz.global.save`, so the scoped one wins the id-order race
5576        // that `find_by_keystroke` used to settle on.)
5577        use crate::action::Action;
5578        use crate::shortcut::{KeyStroke, Shortcut, ShortcutScope};
5579        use std::cell::Cell;
5580        use std::rc::Rc;
5581
5582        let scoped_fired = Rc::new(Cell::new(0));
5583        let global_fired = Rc::new(Cell::new(0));
5584        let sf = scoped_fired.clone();
5585        let gf = global_fired.clone();
5586
5587        let mut tree = WidgetTree::new();
5588        let root = tree.add(FillWidget::new());
5589        let editor = tree.add_child(root, FillWidget::new().focusable());
5590        let _editor_inner = tree.add_child(editor, FillWidget::new().focusable());
5591        let sidebar = tree.add_child(root, FillWidget::new().focusable());
5592
5593        tree.push_action(
5594            editor,
5595            Action::new("editor.saveBlock").on_invoke(move |_i, _c| sf.set(sf.get() + 1)),
5596        );
5597        tree.push_action(
5598            root,
5599            Action::new("zzz.global.save").on_invoke(move |_i, _c| gf.set(gf.get() + 1)),
5600        );
5601        tree.shortcut_registry_mut().register(
5602            Shortcut::new("editor.saveBlock")
5603                .primary(KeyStroke::command(Key::S))
5604                .scope(ShortcutScope::Scoped(editor))
5605                .build(),
5606        );
5607        tree.shortcut_registry_mut().register(
5608            Shortcut::new("zzz.global.save")
5609                .primary(KeyStroke::command(Key::S))
5610                .build(),
5611        );
5612
5613        tree.layout(SizeProposal::exact(200.0, 100.0));
5614        tree.focus(sidebar);
5615        tree.press_key(Key::S, Modifiers::COMMAND);
5616
5617        assert_eq!(global_fired.get(), 1, "applicable global must fire");
5618        assert_eq!(
5619            scoped_fired.get(),
5620            0,
5621            "inapplicable scoped binding must not eat the chord"
5622        );
5623    }
5624
5625    #[test]
5626    fn same_chord_global_first_yields_to_scoped_when_focus_inside() {
5627        // Defect 2: a Global binding that sorts first by id must yield to
5628        // an in-focus Scoped binding (most-specific-scope wins), then
5629        // reclaim the chord once focus leaves the scope. (`app.save` <
5630        // `editor.saveBlock`, so the global one wins id order.)
5631        use crate::action::Action;
5632        use crate::shortcut::{KeyStroke, Shortcut, ShortcutScope};
5633        use std::cell::Cell;
5634        use std::rc::Rc;
5635
5636        let scoped_fired = Rc::new(Cell::new(0));
5637        let global_fired = Rc::new(Cell::new(0));
5638        let sf = scoped_fired.clone();
5639        let gf = global_fired.clone();
5640
5641        let mut tree = WidgetTree::new();
5642        let root = tree.add(FillWidget::new());
5643        let editor = tree.add_child(root, FillWidget::new().focusable());
5644        let editor_inner = tree.add_child(editor, FillWidget::new().focusable());
5645        let sidebar = tree.add_child(root, FillWidget::new().focusable());
5646
5647        tree.push_action(
5648            editor,
5649            Action::new("editor.saveBlock").on_invoke(move |_i, _c| sf.set(sf.get() + 1)),
5650        );
5651        tree.push_action(
5652            root,
5653            Action::new("app.save").on_invoke(move |_i, _c| gf.set(gf.get() + 1)),
5654        );
5655        tree.shortcut_registry_mut().register(
5656            Shortcut::new("app.save")
5657                .primary(KeyStroke::command(Key::S))
5658                .build(),
5659        );
5660        tree.shortcut_registry_mut().register(
5661            Shortcut::new("editor.saveBlock")
5662                .primary(KeyStroke::command(Key::S))
5663                .scope(ShortcutScope::Scoped(editor))
5664                .build(),
5665        );
5666
5667        tree.layout(SizeProposal::exact(200.0, 100.0));
5668
5669        // Focus inside the editor: the scoped binding wins over global.
5670        tree.focus(editor_inner);
5671        tree.press_key(Key::S, Modifiers::COMMAND);
5672        assert_eq!(
5673            scoped_fired.get(),
5674            1,
5675            "in-focus scoped must win over global"
5676        );
5677        assert_eq!(
5678            global_fired.get(),
5679            0,
5680            "global must yield to the scoped binding"
5681        );
5682
5683        // Focus outside the editor: global reclaims the chord.
5684        tree.focus(sidebar);
5685        tree.press_key(Key::S, Modifiers::COMMAND);
5686        assert_eq!(scoped_fired.get(), 1, "scoped stays put outside its scope");
5687        assert_eq!(
5688            global_fired.get(),
5689            1,
5690            "global fires when focus leaves the scope"
5691        );
5692    }
5693
5694    #[test]
5695    fn propagated_action_lets_ancestor_handle() {
5696        use crate::action::Action;
5697        use crate::intent::IntentResponse;
5698        use crate::shortcut::{KeyStroke, Shortcut};
5699        use std::cell::Cell;
5700        use std::rc::Rc;
5701
5702        let inner_seen = Rc::new(Cell::new(false));
5703        let outer_seen = Rc::new(Cell::new(false));
5704        let inner_flag = inner_seen.clone();
5705        let outer_flag = outer_seen.clone();
5706
5707        let mut tree = WidgetTree::new();
5708        let outer = tree.add(FillWidget::new().focusable());
5709        let inner = tree.add_child(outer, FillWidget::new().focusable());
5710
5711        // Inner observes then propagates; outer consumes.
5712        tree.push_action(
5713            inner,
5714            Action::new("app.save").on_invoke_with_response(move |_i, _c| {
5715                inner_flag.set(true);
5716                IntentResponse::Propagated
5717            }),
5718        );
5719        tree.push_action(
5720            outer,
5721            Action::new("app.save").on_invoke(move |_i, _c| {
5722                outer_flag.set(true);
5723            }),
5724        );
5725        tree.shortcut_registry_mut().register(
5726            Shortcut::new("app.save")
5727                .primary(KeyStroke::command(Key::S))
5728                .build(),
5729        );
5730
5731        tree.layout(SizeProposal::exact(100.0, 50.0));
5732        tree.focus(inner);
5733
5734        tree.press_key(Key::S, Modifiers::COMMAND);
5735        assert!(inner_seen.get(), "inner action observed the intent");
5736        assert!(outer_seen.get(), "outer action reached after Propagated");
5737    }
5738
5739    #[test]
5740    fn handled_action_stops_propagation() {
5741        use crate::action::Action;
5742        use crate::shortcut::{KeyStroke, Shortcut};
5743        use std::cell::Cell;
5744        use std::rc::Rc;
5745
5746        let inner_seen = Rc::new(Cell::new(false));
5747        let outer_seen = Rc::new(Cell::new(false));
5748        let inner_flag = inner_seen.clone();
5749        let outer_flag = outer_seen.clone();
5750
5751        let mut tree = WidgetTree::new();
5752        let outer = tree.add(FillWidget::new().focusable());
5753        let inner = tree.add_child(outer, FillWidget::new().focusable());
5754
5755        tree.push_action(
5756            inner,
5757            Action::new("app.save").on_invoke(move |_i, _c| {
5758                inner_flag.set(true);
5759            }),
5760        );
5761        tree.push_action(
5762            outer,
5763            Action::new("app.save").on_invoke(move |_i, _c| {
5764                outer_flag.set(true);
5765            }),
5766        );
5767        tree.shortcut_registry_mut().register(
5768            Shortcut::new("app.save")
5769                .primary(KeyStroke::command(Key::S))
5770                .build(),
5771        );
5772
5773        tree.layout(SizeProposal::exact(100.0, 50.0));
5774        tree.focus(inner);
5775
5776        tree.press_key(Key::S, Modifiers::COMMAND);
5777        assert!(inner_seen.get());
5778        assert!(!outer_seen.get(), "Handled at inner must stop propagation");
5779    }
5780
5781    #[test]
5782    fn disabled_action_propagates_by_default() {
5783        use crate::action::Action;
5784        use crate::shortcut::{KeyStroke, Shortcut};
5785        use crate::signal::Signal;
5786        use std::cell::Cell;
5787        use std::rc::Rc;
5788
5789        let inner_seen = Rc::new(Cell::new(false));
5790        let outer_seen = Rc::new(Cell::new(false));
5791        let inner_flag = inner_seen.clone();
5792        let outer_flag = outer_seen.clone();
5793
5794        let mut tree = WidgetTree::new();
5795        let outer = tree.add(FillWidget::new().focusable());
5796        let inner = tree.add_child(outer, FillWidget::new().focusable());
5797
5798        let enabled = Signal::new(false);
5799        tree.push_action(
5800            inner,
5801            Action::new("app.save")
5802                .enabled_when(enabled.clone())
5803                .on_invoke(move |_i, _c| {
5804                    inner_flag.set(true);
5805                }),
5806        );
5807        tree.push_action(
5808            outer,
5809            Action::new("app.save").on_invoke(move |_i, _c| {
5810                outer_flag.set(true);
5811            }),
5812        );
5813        tree.shortcut_registry_mut().register(
5814            Shortcut::new("app.save")
5815                .primary(KeyStroke::command(Key::S))
5816                .build(),
5817        );
5818
5819        tree.layout(SizeProposal::exact(100.0, 50.0));
5820        tree.focus(inner);
5821
5822        tree.press_key(Key::S, Modifiers::COMMAND);
5823        assert!(!inner_seen.get(), "disabled inner must not run");
5824        assert!(
5825            outer_seen.get(),
5826            "intent must propagate past disabled inner"
5827        );
5828    }
5829
5830    #[test]
5831    fn disabled_action_with_non_propagating_shortcut_consumes() {
5832        use crate::action::Action;
5833        use crate::shortcut::{KeyStroke, Shortcut};
5834        use crate::signal::Signal;
5835        use std::cell::Cell;
5836        use std::rc::Rc;
5837
5838        let inner_seen = Rc::new(Cell::new(false));
5839        let outer_seen = Rc::new(Cell::new(false));
5840        let inner_flag = inner_seen.clone();
5841        let outer_flag = outer_seen.clone();
5842
5843        let mut tree = WidgetTree::new();
5844        let outer = tree.add(FillWidget::new().focusable());
5845        let inner = tree.add_child(outer, FillWidget::new().focusable());
5846
5847        let enabled = Signal::new(false);
5848        tree.push_action(
5849            inner,
5850            Action::new("app.save")
5851                .enabled_when(enabled.clone())
5852                .on_invoke(move |_i, _c| {
5853                    inner_flag.set(true);
5854                }),
5855        );
5856        tree.push_action(
5857            outer,
5858            Action::new("app.save").on_invoke(move |_i, _c| {
5859                outer_flag.set(true);
5860            }),
5861        );
5862        tree.shortcut_registry_mut().register(
5863            Shortcut::new("app.save")
5864                .primary(KeyStroke::command(Key::S))
5865                .propagate_when_disabled(false)
5866                .build(),
5867        );
5868
5869        tree.layout(SizeProposal::exact(100.0, 50.0));
5870        tree.focus(inner);
5871
5872        tree.press_key(Key::S, Modifiers::COMMAND);
5873        assert!(!inner_seen.get(), "disabled inner still does not run");
5874        assert!(
5875            !outer_seen.get(),
5876            "intent must NOT propagate when shortcut disallows it"
5877        );
5878    }
5879
5880    #[test]
5881    fn send_intent_from_handler_reaches_ancestor_action() {
5882        use crate::action::Action;
5883        use crate::intent::Intent;
5884        use std::cell::Cell;
5885        use std::rc::Rc;
5886
5887        let save_seen = Rc::new(Cell::new(false));
5888        let save_flag = save_seen.clone();
5889
5890        let mut tree = WidgetTree::new();
5891        let root = tree.add(FillWidget::new());
5892        let button = tree.add_child(
5893            root,
5894            FillWidget::new().on_tap(|_pos, ctx| {
5895                ctx.send_intent(Intent::new("app.save"));
5896            }),
5897        );
5898        tree.push_action(
5899            root,
5900            Action::new("app.save").on_invoke(move |_i, _c| {
5901                save_flag.set(true);
5902            }),
5903        );
5904
5905        tree.layout(SizeProposal::exact(100.0, 50.0));
5906        tree.click(button);
5907        assert!(
5908            save_seen.get(),
5909            "ctx.send_intent must reach ancestor action"
5910        );
5911    }
5912
5913    #[test]
5914    fn widget_type_histogram_counts_distinct_types() {
5915        // The histogram surfaces concrete widget types
5916        // by std::any::type_name_of_val. Widgets become active
5917        // after the first layout pass, so we run that before
5918        // checking the histogram.
5919        let mut tree = WidgetTree::new();
5920        let _ = tree.add(FillWidget::new());
5921        let _ = tree.add(FillWidget::new());
5922        let _ = tree.add(FillWidget::new());
5923        tree.layout(SizeProposal::exact(100.0, 100.0));
5924        let histogram = tree.widget_type_histogram();
5925        let total: u32 = histogram.values().sum();
5926        assert!(
5927            total >= 3,
5928            "expected at least 3 active widgets, got {total}: {histogram:?}"
5929        );
5930        let fillwidget_entries: u32 = histogram
5931            .iter()
5932            .filter(|(k, _)| k.contains("FillWidget"))
5933            .map(|(_, v)| *v)
5934            .sum();
5935        assert!(
5936            fillwidget_entries >= 3,
5937            "expected ≥3 FillWidget instances; histogram = {histogram:?}"
5938        );
5939        assert_eq!(tree.active_widget_count() as u32, total);
5940    }
5941
5942    #[test]
5943    fn intent_source_tagged_handler_for_tap_activation() {
5944        // A tap-driven `ctx.send_intent` must surface as
5945        // `IntentSource::Handler` to ancestor actions, not the
5946        // `Programmatic` default of `Intent::new`.
5947        use crate::action::Action;
5948        use crate::intent::Intent;
5949        use crate::telemetry::IntentSource;
5950        use std::cell::Cell;
5951        use std::rc::Rc;
5952        let captured = Rc::new(Cell::new(IntentSource::Unknown));
5953        let captured_for_action = captured.clone();
5954
5955        let mut tree = WidgetTree::new();
5956        let root = tree.add(FillWidget::new());
5957        let button = tree.add_child(
5958            root,
5959            FillWidget::new().on_tap(|_pos, ctx| {
5960                ctx.send_intent(Intent::new("app.save"));
5961            }),
5962        );
5963        tree.push_action(
5964            root,
5965            Action::new("app.save").on_invoke(move |intent, _c| {
5966                captured_for_action.set(intent.source);
5967            }),
5968        );
5969
5970        tree.layout(SizeProposal::exact(100.0, 50.0));
5971        tree.click(button);
5972        assert_eq!(
5973            captured.get(),
5974            IntentSource::Handler,
5975            "tap-driven intent must tag IntentSource::Handler"
5976        );
5977    }
5978
5979    #[test]
5980    fn intent_source_programmatic_when_no_handler_active() {
5981        use crate::intent::Intent;
5982        use crate::telemetry::IntentSource;
5983        let intent = Intent::new("app.demo");
5984        assert_eq!(intent.source, IntentSource::Programmatic);
5985
5986        // ctx.send_intent without a handler scope keeps it Programmatic.
5987        let mut ctx = EventContext::new();
5988        ctx.send_intent(Intent::new("app.demo"));
5989        let queued = ctx.pending_intents.first().expect("intent queued");
5990        assert_eq!(queued.source, IntentSource::Programmatic);
5991    }
5992
5993    #[test]
5994    fn with_intent_source_overrides_for_managed_widgets() {
5995        use crate::intent::Intent;
5996        use crate::telemetry::IntentSource;
5997        let mut ctx = EventContext::new();
5998        ctx.with_intent_source(IntentSource::Menu, |ctx| {
5999            ctx.send_intent(Intent::new("app.demo"));
6000        });
6001        let queued = ctx.pending_intents.first().expect("intent queued");
6002        assert_eq!(
6003            queued.source,
6004            IntentSource::Menu,
6005            "with_intent_source(Menu) must tag the dispatched intent"
6006        );
6007
6008        // After the closure returns, current_source is restored —
6009        // a follow-up send_intent without a wrapping closure goes
6010        // back to the default (no override).
6011        ctx.send_intent(Intent::new("app.next"));
6012        let next = ctx.pending_intents.last().expect("second intent");
6013        assert_eq!(next.source, IntentSource::Programmatic);
6014    }
6015
6016    #[test]
6017    fn disabled_shortcut_falls_through_to_focused_widget() {
6018        use crate::action::Action;
6019        use crate::shortcut::{KeyStroke, Shortcut};
6020        use crate::signal::Signal;
6021        use std::cell::Cell;
6022        use std::rc::Rc;
6023
6024        let action_fired = Rc::new(Cell::new(false));
6025        let on_key_fired = Rc::new(Cell::new(false));
6026        let af = action_fired.clone();
6027        let kf = on_key_fired.clone();
6028
6029        let enabled = Signal::new(false);
6030
6031        let mut tree = WidgetTree::new();
6032        let widget = tree.add(FillWidget::new().focusable().on_key(move |event, _ctx| {
6033            if matches!(
6034                event,
6035                WidgetEvent::KeyDown {
6036                    key: Key::S,
6037                    modifiers,
6038                    ..
6039                } if modifiers.command()
6040            ) {
6041                kf.set(true);
6042                return EventResponse::Handled;
6043            }
6044            EventResponse::Ignored
6045        }));
6046        tree.push_action(
6047            widget,
6048            Action::new("app.save").on_invoke(move |_i, _c| af.set(true)),
6049        );
6050        tree.shortcut_registry_mut().register(
6051            Shortcut::new("app.save")
6052                .primary(KeyStroke::command(Key::S))
6053                .enabled_when(enabled.clone())
6054                .build(),
6055        );
6056
6057        tree.layout(SizeProposal::exact(100.0, 50.0));
6058        tree.focus(widget);
6059
6060        // Disabled: keystroke falls through to on_key.
6061        tree.press_key(Key::S, Modifiers::COMMAND);
6062        assert!(
6063            !action_fired.get(),
6064            "disabled shortcut must not invoke its action"
6065        );
6066        assert!(
6067            on_key_fired.get(),
6068            "disabled shortcut must let KeyDown reach the focused widget"
6069        );
6070
6071        // Re-enable → action fires, on_key does not.
6072        on_key_fired.set(false);
6073        enabled.set(true);
6074        tree.press_key(Key::S, Modifiers::COMMAND);
6075        assert!(action_fired.get(), "re-enabled shortcut must dispatch");
6076        assert!(
6077            !on_key_fired.get(),
6078            "enabled shortcut must consume the KeyDown"
6079        );
6080    }
6081
6082    #[test]
6083    fn keyboard_capture_bypasses_shortcut() {
6084        use crate::action::Action;
6085        use crate::shortcut::{KeyStroke, Shortcut};
6086        use std::cell::Cell;
6087        use std::rc::Rc;
6088
6089        // A focused keyboard-capture surface (e.g. a terminal) must receive
6090        // the accelerator chord itself (⌘S on macOS, Ctrl+S elsewhere), even
6091        // though an ENABLED global shortcut binds it — the whole point of
6092        // GAP 1. A non-capturing widget must yield to the shortcut (the
6093        // control case).
6094        fn run(capture: bool) -> (bool, bool) {
6095            let action_fired = Rc::new(Cell::new(false));
6096            let on_key_fired = Rc::new(Cell::new(false));
6097            let af = action_fired.clone();
6098            let kf = on_key_fired.clone();
6099
6100            let mut tree = WidgetTree::new();
6101            let widget = tree.add(
6102                FillWidget::new()
6103                    .focusable()
6104                    .keyboard_capture(capture)
6105                    .on_key(move |event, _ctx| {
6106                        if matches!(
6107                            event,
6108                            WidgetEvent::KeyDown { key: Key::S, modifiers, .. } if modifiers.command()
6109                        ) {
6110                            kf.set(true);
6111                            return EventResponse::Handled;
6112                        }
6113                        EventResponse::Ignored
6114                    }),
6115            );
6116            tree.push_action(
6117                widget,
6118                Action::new("app.save").on_invoke(move |_i, _c| af.set(true)),
6119            );
6120            tree.shortcut_registry_mut().register(
6121                Shortcut::new("app.save")
6122                    .primary(KeyStroke::command(Key::S))
6123                    .build(),
6124            );
6125
6126            tree.layout(SizeProposal::exact(100.0, 50.0));
6127            tree.focus(widget);
6128            tree.press_key(Key::S, Modifiers::COMMAND);
6129            (action_fired.get(), on_key_fired.get())
6130        }
6131
6132        // Capture on: the shortcut is bypassed, the widget sees the key.
6133        let (action, on_key) = run(true);
6134        assert!(
6135            !action,
6136            "keyboard_capture must suppress the shortcut action"
6137        );
6138        assert!(on_key, "keyboard_capture must deliver the raw KeyDown");
6139
6140        // Capture off (control): the shortcut consumes the key.
6141        let (action, on_key) = run(false);
6142        assert!(action, "without capture the shortcut must fire");
6143        assert!(!on_key, "without capture the widget must not see the key");
6144    }
6145
6146    /// A focused widget that records every `KeyDown` it is handed.
6147    fn key_recorder(
6148        tree: &mut WidgetTree,
6149    ) -> (WidgetId, std::rc::Rc<std::cell::RefCell<Vec<Key>>>) {
6150        let seen = std::rc::Rc::new(std::cell::RefCell::new(Vec::new()));
6151        let log = seen.clone();
6152        let widget = tree.add(FillWidget::new().focusable().on_key(move |event, _ctx| {
6153            if let WidgetEvent::KeyDown { key, .. } = event {
6154                log.borrow_mut().push(*key);
6155            }
6156            EventResponse::Ignored
6157        }));
6158        tree.layout(SizeProposal::exact(100.0, 50.0));
6159        tree.focus(widget);
6160        (widget, seen)
6161    }
6162
6163    #[test]
6164    fn a_shortcut_no_action_takes_leaves_its_key_to_the_focused_widget() {
6165        use crate::action::Action;
6166        use crate::intent::IntentResponse;
6167        use crate::shortcut::{KeyStroke, Shortcut};
6168
6169        let mut tree = WidgetTree::new();
6170        let (widget, seen) = key_recorder(&mut tree);
6171        tree.shortcut_registry_mut().register(
6172            Shortcut::new("app.save")
6173                .primary(KeyStroke::command(Key::S))
6174                .build(),
6175        );
6176
6177        // Nothing handles `app.save`.
6178        tree.press_key(Key::S, Modifiers::COMMAND);
6179        assert_eq!(
6180            *seen.borrow(),
6181            vec![Key::S],
6182            "an unhandled intent must not eat the key"
6183        );
6184
6185        // An action that runs and passes the intent on has not consumed it.
6186        tree.push_action(
6187            widget,
6188            Action::new("app.save").on_invoke_with_response(|_i, _c| IntentResponse::Propagated),
6189        );
6190        tree.press_key(Key::S, Modifiers::COMMAND);
6191        assert_eq!(
6192            seen.borrow().len(),
6193            2,
6194            "a propagated intent must leave the key too"
6195        );
6196
6197        // Deleting the fall-through makes both of the above go red; this is
6198        // the control: a consuming action still takes the key.
6199        let mut tree = WidgetTree::new();
6200        let (widget, seen) = key_recorder(&mut tree);
6201        tree.shortcut_registry_mut().register(
6202            Shortcut::new("app.save")
6203                .primary(KeyStroke::command(Key::S))
6204                .build(),
6205        );
6206        tree.push_action(widget, Action::new("app.save").on_invoke(|_i, _c| {}));
6207        tree.press_key(Key::S, Modifiers::COMMAND);
6208        assert!(
6209            seen.borrow().is_empty(),
6210            "a handled shortcut consumes its key"
6211        );
6212    }
6213
6214    #[test]
6215    fn standard_edit_chords_follow_a_rebind() {
6216        use crate::action::Action;
6217        use crate::shortcut::{KeyStroke, StandardEdit};
6218        use std::cell::Cell;
6219        use std::rc::Rc;
6220
6221        let mut tree = WidgetTree::new();
6222        let (widget, seen) = key_recorder(&mut tree);
6223        let copies = Rc::new(Cell::new(0));
6224        let count = copies.clone();
6225        tree.push_action(
6226            widget,
6227            Action::new(StandardEdit::Copy.id())
6228                .on_invoke(move |_i, _c| count.set(count.get() + 1)),
6229        );
6230
6231        // Registered by `WidgetTree::new`, with no help from the app.
6232        tree.press_key(Key::C, Modifiers::COMMAND);
6233        assert_eq!(copies.get(), 1, "Ctrl+C reaches the edit.copy action");
6234        assert!(seen.borrow().is_empty());
6235
6236        // Move Copy elsewhere: the old chord no longer copies (it reaches the
6237        // widget as a plain key), the new one does.
6238        let elsewhere = KeyStroke::new(Key::Character('à'), Modifiers::CTRL);
6239        tree.shortcut_registry_mut()
6240            .rebind_primary(StandardEdit::Copy.id(), Some(elsewhere));
6241        tree.press_key(Key::C, Modifiers::COMMAND);
6242        assert_eq!(copies.get(), 1, "the replaced chord must not copy");
6243        assert_eq!(*seen.borrow(), vec![Key::C]);
6244        tree.press_key(Key::Character('à'), Modifiers::CTRL);
6245        assert_eq!(copies.get(), 2, "the new chord copies");
6246    }
6247
6248    #[test]
6249    fn ctrl_tab_always_escapes_a_keyboard_capture_surface() {
6250        use std::cell::Cell;
6251        use std::rc::Rc;
6252
6253        // WCAG 2.1.2. A capture surface answers `Handled` to every key —
6254        // that is what it is for — so the "cycle focus only when the focused
6255        // widget did not handle Tab" rule can never get focus out of one.
6256        // Ctrl+Tab / Ctrl+Shift+Tab are therefore reserved by the dispatcher
6257        // and never reach the widget at all.
6258        let saw_key = Rc::new(Cell::new(false));
6259        let sk = saw_key.clone();
6260
6261        let mut tree = WidgetTree::new();
6262        let capture = tree.add(
6263            FillWidget::new()
6264                .focusable()
6265                .keyboard_capture(true)
6266                // The greediest possible handler: everything is consumed.
6267                .on_key(move |_event, _ctx| {
6268                    sk.set(true);
6269                    EventResponse::Handled
6270                }),
6271        );
6272        let neighbour = tree.add(FillWidget::new().focusable());
6273        tree.layout(SizeProposal::exact(100.0, 50.0));
6274
6275        // Plain Tab stays inside: the widget consumed it (a terminal writes
6276        // it to the child as `\t`).
6277        tree.focus(capture);
6278        tree.press_key(Key::Tab, Modifiers::NONE);
6279        assert!(saw_key.get(), "plain Tab must reach the capture surface");
6280        assert_eq!(
6281            tree.focused(),
6282            Some(capture),
6283            "plain Tab must not move focus off a capture surface"
6284        );
6285
6286        // Ctrl+Tab escapes forward, without the widget ever seeing it.
6287        saw_key.set(false);
6288        tree.press_key(Key::Tab, Modifiers::CTRL);
6289        assert!(
6290            !saw_key.get(),
6291            "Ctrl+Tab is reserved and must not reach the capture surface"
6292        );
6293        assert_eq!(
6294            tree.focused(),
6295            Some(neighbour),
6296            "Ctrl+Tab must move focus out of a capture surface"
6297        );
6298
6299        // And backwards.
6300        tree.focus(capture);
6301        tree.press_key(Key::Tab, Modifiers::CTRL | Modifiers::SHIFT);
6302        assert_eq!(
6303            tree.focused(),
6304            Some(neighbour),
6305            "Ctrl+Shift+Tab must move focus out of a capture surface"
6306        );
6307    }
6308
6309    #[test]
6310    fn scope_mismatch_does_not_invoke_on_activate() {
6311        use crate::intent::Intent;
6312        use crate::shortcut::{KeyStroke, Shortcut, ShortcutScope};
6313        use std::cell::Cell;
6314        use std::rc::Rc;
6315
6316        // Regression: before the find/invoke split, `on_activate` ran
6317        // even when the focused widget was outside the shortcut's
6318        // scope, and any side effects on its ctx were silently
6319        // dropped. The closure must now only run when the scope
6320        // check has already passed.
6321        let activated = Rc::new(Cell::new(false));
6322        let activated_flag = activated.clone();
6323
6324        let mut tree = WidgetTree::new();
6325        let scope_root = tree.add(FillWidget::new().focusable());
6326        let outside = tree.add(FillWidget::new().focusable());
6327
6328        tree.shortcut_registry_mut().register(
6329            Shortcut::new("editor.find")
6330                .primary(KeyStroke::command(Key::F))
6331                .scope(ShortcutScope::Scoped(scope_root))
6332                .on_activate(move |_ks, _ctx| {
6333                    activated_flag.set(true);
6334                    Intent::new("editor.find")
6335                })
6336                .build(),
6337        );
6338
6339        tree.layout(SizeProposal::exact(200.0, 100.0));
6340        tree.focus(outside);
6341
6342        tree.press_key(Key::F, Modifiers::COMMAND);
6343        assert!(
6344            !activated.get(),
6345            "on_activate must not run when focus is outside the shortcut's scope"
6346        );
6347    }
6348
6349    #[test]
6350    fn key_capture_runs_callback_and_bypasses_registry() {
6351        use crate::action::Action;
6352        use crate::shortcut::{KeyStroke, Shortcut};
6353        use std::cell::Cell;
6354        use std::rc::Rc;
6355
6356        let action_fired = Rc::new(Cell::new(false));
6357        let af = action_fired.clone();
6358        let captured = Rc::new(Cell::new(None));
6359        let cf = captured.clone();
6360
6361        let mut tree = WidgetTree::new();
6362        let widget = tree.add(FillWidget::new().focusable());
6363        tree.push_action(
6364            widget,
6365            Action::new("app.save").on_invoke(move |_i, _c| af.set(true)),
6366        );
6367        tree.shortcut_registry_mut().register(
6368            Shortcut::new("app.save")
6369                .primary(KeyStroke::command(Key::S))
6370                .build(),
6371        );
6372
6373        tree.layout(SizeProposal::exact(100.0, 50.0));
6374        tree.focus(widget);
6375
6376        let handle = tree.begin_key_capture(move |ks, _reg, _ctx| cf.set(Some(ks)));
6377        assert!(tree.is_capturing_keys());
6378
6379        tree.press_key(Key::S, Modifiers::COMMAND);
6380        assert_eq!(
6381            captured.get(),
6382            Some(KeyStroke::command(Key::S)),
6383            "capture callback must receive the chord"
6384        );
6385        assert!(
6386            !action_fired.get(),
6387            "shortcut action must not fire while capture is armed"
6388        );
6389        assert!(
6390            !tree.is_capturing_keys(),
6391            "capture is one-shot; next KeyDown flows normally"
6392        );
6393        drop(handle);
6394    }
6395
6396    #[test]
6397    fn key_capture_can_rebind_through_registry() {
6398        use crate::shortcut::{KeyStroke, Shortcut};
6399
6400        let mut tree = WidgetTree::new();
6401        let widget = tree.add(FillWidget::new().focusable());
6402        tree.shortcut_registry_mut().register(
6403            Shortcut::new("app.save")
6404                .primary(KeyStroke::command(Key::S))
6405                .build(),
6406        );
6407
6408        tree.layout(SizeProposal::exact(100.0, 50.0));
6409        tree.focus(widget);
6410
6411        // Arm capture: whatever chord comes next, rebind app.save to it.
6412        let _h = tree.begin_key_capture(|ks, reg, _ctx| {
6413            reg.rebind_primary("app.save", Some(ks));
6414        });
6415
6416        tree.press_key(Key::B, Modifiers::COMMAND | Modifiers::SHIFT);
6417        assert_eq!(
6418            tree.shortcut_registry()
6419                .effective("app.save")
6420                .unwrap()
6421                .primary,
6422            Some(KeyStroke::command_shift(Key::B))
6423        );
6424    }
6425
6426    #[test]
6427    fn dropping_capture_handle_cancels_capture() {
6428        use crate::shortcut::{KeyStroke, Shortcut};
6429        use std::cell::Cell;
6430        use std::rc::Rc;
6431
6432        let action_fired = Rc::new(Cell::new(false));
6433        let af = action_fired.clone();
6434        let capture_fired = Rc::new(Cell::new(false));
6435        let cf = capture_fired.clone();
6436
6437        let mut tree = WidgetTree::new();
6438        let widget = tree.add(FillWidget::new().focusable());
6439        tree.push_action(
6440            widget,
6441            crate::action::Action::new("app.save").on_invoke(move |_i, _c| af.set(true)),
6442        );
6443        tree.shortcut_registry_mut().register(
6444            Shortcut::new("app.save")
6445                .primary(KeyStroke::command(Key::S))
6446                .build(),
6447        );
6448        tree.layout(SizeProposal::exact(100.0, 50.0));
6449        tree.focus(widget);
6450
6451        // Arm capture in a scope, then drop the handle before any key
6452        // is pressed. The next KeyDown must fall through to the normal
6453        // shortcut path, firing the action — not the cancelled capture.
6454        {
6455            let _h = tree.begin_key_capture(move |_ks, _reg, _ctx| cf.set(true));
6456            assert!(tree.is_capturing_keys());
6457            // `_h` drops here → cancel.
6458        }
6459        assert!(
6460            !tree.is_capturing_keys(),
6461            "dropping the handle must cancel the capture"
6462        );
6463
6464        tree.press_key(Key::S, Modifiers::COMMAND);
6465        assert!(!capture_fired.get(), "cancelled capture must not fire");
6466        assert!(
6467            action_fired.get(),
6468            "shortcut action runs after capture was cancelled"
6469        );
6470    }
6471
6472    #[test]
6473    fn second_begin_key_capture_does_not_racecancel_first() {
6474        use std::cell::Cell;
6475        use std::rc::Rc;
6476
6477        let first = Rc::new(Cell::new(false));
6478        let second = Rc::new(Cell::new(false));
6479        let f = first.clone();
6480        let s = second.clone();
6481
6482        let mut tree = WidgetTree::new();
6483        let widget = tree.add(FillWidget::new().focusable());
6484        tree.layout(SizeProposal::exact(100.0, 50.0));
6485        tree.focus(widget);
6486
6487        // Arm #1 then replace with #2. #1's handle is later dropped,
6488        // which would have cancelled the active capture under the old
6489        // `Option<Box<FnOnce>>` design — CaptureHandle now ties each
6490        // session to its own slot, so the drop only clears #1's
6491        // (orphaned) slot, not #2.
6492        let h1 = tree.begin_key_capture(move |_ks, _reg, _ctx| f.set(true));
6493        let _h2 = tree.begin_key_capture(move |_ks, _reg, _ctx| s.set(true));
6494        drop(h1);
6495
6496        assert!(
6497            tree.is_capturing_keys(),
6498            "dropping the older handle must not cancel the active capture"
6499        );
6500        tree.press_key(Key::K, Modifiers::COMMAND);
6501        assert!(!first.get());
6502        assert!(second.get(), "newest capture wins");
6503    }
6504
6505    #[test]
6506    fn capture_callback_can_send_intent() {
6507        use crate::action::Action;
6508        use crate::intent::Intent;
6509
6510        use std::cell::Cell;
6511        use std::rc::Rc;
6512
6513        let ran = Rc::new(Cell::new(false));
6514        let flag = ran.clone();
6515
6516        let mut tree = WidgetTree::new();
6517        let widget = tree.add(FillWidget::new().focusable());
6518        tree.push_action(
6519            widget,
6520            Action::new("app.save").on_invoke(move |_i, _c| flag.set(true)),
6521        );
6522        tree.layout(SizeProposal::exact(100.0, 50.0));
6523        tree.focus(widget);
6524
6525        let _h = tree.begin_key_capture(|_ks, _reg, ctx| {
6526            ctx.send_intent(Intent::new("app.save"));
6527        });
6528        tree.press_key(Key::X, Modifiers::COMMAND);
6529        assert!(
6530            ran.get(),
6531            "intent queued from capture callback must dispatch"
6532        );
6533    }
6534
6535    #[test]
6536    fn binding_registry_does_not_accumulate_across_rebuilds() {
6537        use crate::binding::BindingLevel;
6538        use crate::signal::Signal;
6539
6540        #[derive(Debug)]
6541        struct BoundLeaf {
6542            tick: Signal<u64>,
6543        }
6544        impl crate::widget::Widget for BoundLeaf {
6545            fn build(&mut self, ctx: &mut crate::build_context::BuildContext) -> Vec<WidgetId> {
6546                self.tick.bind_to(
6547                    ctx.self_id(),
6548                    ctx.binding_registry(),
6549                    BindingLevel::Relayout,
6550                );
6551                Vec::new()
6552            }
6553            fn layout_response(
6554                &self,
6555                proposal: SizeProposal,
6556                _ctx: &crate::widget::LayoutContext,
6557            ) -> crate::widget::LayoutResponse {
6558                proposal.resolve(10.0, 10.0).into()
6559            }
6560        }
6561
6562        let mut tree = WidgetTree::new();
6563        let tick = Signal::new(0_u64);
6564        let widget = tree.add(BoundLeaf { tick: tick.clone() });
6565        tree.layout(SizeProposal::exact(200.0, 200.0));
6566        let after_first_build = tree.binding_registry().len();
6567        assert!(after_first_build >= 1);
6568
6569        // Force rebuild a handful of times and verify the binding
6570        // count does not keep growing. Pre-fix: each rebuild pushed
6571        // a new entry for the same (widget, signal) pair.
6572        for _ in 0..5 {
6573            tree.arena.mark_needs_rebuild(widget);
6574            tree.layout(SizeProposal::exact(200.0, 200.0));
6575        }
6576        assert_eq!(
6577            tree.binding_registry().len(),
6578            after_first_build,
6579            "bindings must be cleared on rebuild"
6580        );
6581
6582        tree.destroy_subtree(widget);
6583        assert_eq!(
6584            tree.binding_registry().len(),
6585            0,
6586            "bindings must be cleared on destroy"
6587        );
6588        // Silence unused-variable warning for the signal.
6589        let _ = tick;
6590    }
6591
6592    #[test]
6593    fn ctx_destroy_cancels_animations_and_bindings_via_deferred_path() {
6594        // Regression: `EventContext::destroy` queues
6595        // `TreeMutation::Destroy`, which used to be applied with the
6596        // bare `arena.destroy` — unlinking the node but leaking the
6597        // animation-scheduler entry (it holds a strong `Signal<f32>`
6598        // clone, so the widget kept animating after destruction) and
6599        // the widget's bindings. It must route through
6600        // `destroy_subtree` like every other destroy path does.
6601        use crate::binding::BindingLevel;
6602        use crate::signal::Signal;
6603        use std::time::{Duration, Instant};
6604        use teksilo_tokens::Easing;
6605
6606        #[derive(Debug)]
6607        struct BoundLeaf {
6608            tick: Signal<u64>,
6609        }
6610        impl crate::widget::Widget for BoundLeaf {
6611            fn build(&mut self, ctx: &mut crate::build_context::BuildContext) -> Vec<WidgetId> {
6612                self.tick.bind_to(
6613                    ctx.self_id(),
6614                    ctx.binding_registry(),
6615                    BindingLevel::Relayout,
6616                );
6617                Vec::new()
6618            }
6619            fn layout_response(
6620                &self,
6621                proposal: SizeProposal,
6622                _ctx: &crate::widget::LayoutContext,
6623            ) -> crate::widget::LayoutResponse {
6624                proposal.resolve(10.0, 10.0).into()
6625            }
6626        }
6627
6628        let mut tree = WidgetTree::new();
6629        let widget = tree.add(BoundLeaf {
6630            tick: Signal::new(0_u64),
6631        });
6632        tree.layout(SizeProposal::exact(200.0, 200.0));
6633        assert!(tree.binding_registry().len() >= 1);
6634
6635        // Seed an animation owned by the widget — exactly the strong
6636        // `Signal<f32>` clone the scheduler outlives the widget with.
6637        let anim = Signal::<f32>::new_animated(0.0);
6638        tree.animation_scheduler.animate(
6639            &anim,
6640            widget,
6641            1.0,
6642            Duration::from_secs(10),
6643            Easing::Linear,
6644            Instant::now(),
6645        );
6646        assert_eq!(tree.animation_scheduler.active_count(), 1);
6647
6648        // Destroy via the deferred handler-time path.
6649        let mut noop = crate::window::NoopWindowOps;
6650        tree.run_with_event_context(&mut noop, |ctx| ctx.destroy(widget));
6651
6652        assert_eq!(
6653            tree.animation_scheduler.active_count(),
6654            0,
6655            "ctx.destroy must cancel animations owned by the destroyed widget"
6656        );
6657        assert_eq!(
6658            tree.binding_registry().len(),
6659            0,
6660            "ctx.destroy must unregister the destroyed widget's bindings"
6661        );
6662        assert!(
6663            tree.arena.get(widget).is_none(),
6664            "node must be removed from the arena"
6665        );
6666    }
6667
6668    #[test]
6669    fn clear_shortcut_override_via_event_context_restores_default() {
6670        use crate::shortcut::{KeyStroke, Shortcut};
6671
6672        let mut tree = WidgetTree::new();
6673        tree.shortcut_registry_mut().register(
6674            Shortcut::new("app.save")
6675                .primary(KeyStroke::command(Key::S))
6676                .build(),
6677        );
6678        tree.shortcut_registry_mut()
6679            .rebind_primary("app.save", Some(KeyStroke::alt(Key::S)));
6680
6681        let source = tree.add(FillWidget::new());
6682        let mut ctx = EventContext::new();
6683        ctx.clear_shortcut_override("app.save");
6684        tree.collect_from_ctx(ctx, source);
6685
6686        assert_eq!(
6687            tree.shortcut_registry()
6688                .effective("app.save")
6689                .unwrap()
6690                .primary,
6691            Some(KeyStroke::command(Key::S))
6692        );
6693    }
6694
6695    #[test]
6696    fn rebind_shortcut_primary_via_event_context() {
6697        use crate::shortcut::{KeyStroke, Shortcut};
6698
6699        let mut tree = WidgetTree::new();
6700        tree.shortcut_registry_mut().register(
6701            Shortcut::new("app.save")
6702                .primary(KeyStroke::command(Key::S))
6703                .build(),
6704        );
6705        let source = tree.add(FillWidget::new());
6706
6707        let mut ctx = EventContext::new();
6708        ctx.rebind_shortcut_primary("app.save", Some(KeyStroke::alt(Key::S)));
6709        tree.collect_from_ctx(ctx, source);
6710
6711        assert_eq!(
6712            tree.shortcut_registry()
6713                .effective("app.save")
6714                .unwrap()
6715                .primary,
6716            Some(KeyStroke::alt(Key::S))
6717        );
6718    }
6719
6720    #[test]
6721    fn unregister_all_for_owner_called_on_destroy() {
6722        use crate::shortcut::{KeyStroke, Shortcut};
6723
6724        let mut tree = WidgetTree::new();
6725        let widget = tree.add(FillWidget::new());
6726        let widget_owner = widget;
6727        tree.shortcut_registry_mut().register_owned(
6728            Shortcut::new("scoped.thing")
6729                .primary(KeyStroke::command(Key::K))
6730                .build(),
6731            widget_owner,
6732        );
6733        assert!(
6734            tree.shortcut_registry()
6735                .get_default("scoped.thing")
6736                .is_some()
6737        );
6738
6739        tree.destroy_subtree(widget);
6740        assert!(
6741            tree.shortcut_registry()
6742                .get_default("scoped.thing")
6743                .is_none(),
6744            "destroying the owner must unregister its shortcut"
6745        );
6746    }
6747
6748    /// A global action fires for an intent dispatched from a widget in a
6749    /// completely unrelated subtree — proving it is a position-independent
6750    /// fallback (the menu-bar-vs-content case).
6751    #[test]
6752    fn global_action_reached_from_unrelated_source() {
6753        use crate::action::Action;
6754        use crate::intent::Intent;
6755        use std::cell::Cell;
6756        use std::rc::Rc;
6757
6758        #[derive(Debug)]
6759        struct Registrar(Rc<Cell<bool>>);
6760        impl crate::widget::Widget for Registrar {
6761            fn build(&mut self, ctx: &mut crate::build_context::BuildContext) -> Vec<WidgetId> {
6762                let flag = self.0.clone();
6763                ctx.register_action_global(
6764                    Action::new("test.global").on_invoke(move |_i, _c| flag.set(true)),
6765                );
6766                vec![]
6767            }
6768            fn layout_response(
6769                &self,
6770                _p: teksilo_canvas::SizeProposal,
6771                _c: &crate::widget::LayoutContext,
6772            ) -> crate::widget::LayoutResponse {
6773                teksilo_canvas::Size::new(0.0, 0.0).into()
6774            }
6775        }
6776
6777        let mut tree = WidgetTree::new();
6778        let fired = Rc::new(Cell::new(false));
6779        let registrar = tree.add(Registrar(fired.clone()));
6780        let source = tree.add(FillWidget::new()); // unrelated sibling root
6781        let mut ops = crate::window::NoopWindowOps;
6782
6783        tree.dispatch_intent(source, Intent::new("test.global"), true, &mut ops);
6784        assert!(
6785            fired.get(),
6786            "global action must fire from an unrelated source"
6787        );
6788
6789        // And it is torn down with its owner.
6790        fired.set(false);
6791        tree.destroy_subtree(registrar);
6792        tree.dispatch_intent(source, Intent::new("test.global"), true, &mut ops);
6793        assert!(
6794            !fired.get(),
6795            "destroying the owner must remove its global action"
6796        );
6797    }
6798
6799    // --- Transform-aware hit-testing -------------------------------------
6800    //
6801    // `set_transform` scopes are paint-only: the renderer pushes the
6802    // transform around the subtree, so the visually-displayed area is
6803    // shifted relative to `arena.bounds(id)`. Hit-testing must inverse-
6804    // transform the screen-space input point as it descends through each
6805    // transform scope so that a click on the visually-rendered area lands
6806    // on the correct widget. Pre-fix, screen-space `bounds.contains(point)`
6807    // returned the *pre-transform* widget for in-bounds-pre-transform
6808    // points and missed the visually-shifted hit area entirely.
6809
6810    #[test]
6811    fn hit_test_through_translate_scope() {
6812        use crate::test_widgets::StackWidget;
6813        let mut tree = WidgetTree::new();
6814        let child = tree.add(FillWidget::new());
6815        let parent = tree.add(StackWidget::new().child(child));
6816        // Visually shift the entire subtree right by 100px.
6817        tree.set_transform(parent, teksilo_canvas::Transform2D::translate(100.0, 0.0));
6818        tree.layout(SizeProposal::exact(100.0, 50.0));
6819
6820        // (50, 25) is inside the *pre-transform* bounds but the widget is
6821        // visually painted at x=100..200; a click at (50, 25) lands on
6822        // empty space.
6823        assert_eq!(
6824            tree.hit_test(Point::new(50.0, 25.0)),
6825            None,
6826            "pre-transform area is not visually populated and must not hit"
6827        );
6828        // (150, 25) is inside the visually-rendered area (post-translate).
6829        assert_eq!(
6830            tree.hit_test(Point::new(150.0, 25.0)),
6831            Some(child),
6832            "visually-rendered area must hit the child"
6833        );
6834        // Off everything.
6835        assert_eq!(tree.hit_test(Point::new(250.0, 25.0)), None);
6836    }
6837
6838    #[test]
6839    fn hit_test_through_scale_scope() {
6840        use crate::test_widgets::StackWidget;
6841        let mut tree = WidgetTree::new();
6842        let child = tree.add(FillWidget::new());
6843        let parent = tree.add(StackWidget::new().child(child));
6844        // Halve the visual size: pre-transform bounds (0,0,100,50) →
6845        // visually (0,0,50,25).
6846        tree.set_transform(parent, teksilo_canvas::Transform2D::scale(0.5, 0.5));
6847        tree.layout(SizeProposal::exact(100.0, 50.0));
6848
6849        // Inside the visual area.
6850        assert_eq!(tree.hit_test(Point::new(25.0, 12.0)), Some(child));
6851        // Outside the visual area but inside the pre-transform bounds.
6852        // Without the fix this would (incorrectly) hit the child.
6853        assert_eq!(
6854            tree.hit_test(Point::new(75.0, 25.0)),
6855            None,
6856            "scaled-out region must not hit"
6857        );
6858    }
6859
6860    #[test]
6861    fn hit_test_through_nested_transforms_compose() {
6862        use crate::test_widgets::StackWidget;
6863        let mut tree = WidgetTree::new();
6864        let leaf = tree.add(FillWidget::new());
6865        let inner = tree.add(StackWidget::new().child(leaf));
6866        let outer = tree.add(StackWidget::new().child(inner));
6867        // Outer translates by (100, 0); inner additionally scales by 2.
6868        // Effective at leaf = scale(2,2).then(translate(100,0)) — the
6869        // renderer composes deepest-first (see `effective_transform`).
6870        tree.set_transform(outer, teksilo_canvas::Transform2D::translate(100.0, 0.0));
6871        tree.set_transform(inner, teksilo_canvas::Transform2D::scale(2.0, 2.0));
6872        tree.layout(SizeProposal::exact(50.0, 25.0));
6873
6874        // Leaf-local (0, 0) → scale → (0, 0) → translate → (100, 0).
6875        // Leaf-local (50, 25) → scale → (100, 50) → translate → (200, 50).
6876        // So the visual hit area is x in [100, 200], y in [0, 50].
6877        assert_eq!(tree.hit_test(Point::new(150.0, 25.0)), Some(leaf));
6878        assert_eq!(tree.hit_test(Point::new(50.0, 25.0)), None);
6879        assert_eq!(tree.hit_test(Point::new(250.0, 25.0)), None);
6880    }
6881
6882    #[test]
6883    fn hit_test_identity_transform_unchanged() {
6884        // Sanity: an identity transform must not perturb the existing
6885        // hit-test behavior. Guards against accidental over-application
6886        // of inversion on the hot path.
6887        let mut tree = WidgetTree::new();
6888        let widget = tree.add(FillWidget::new());
6889        tree.set_transform(widget, teksilo_canvas::Transform2D::IDENTITY);
6890        tree.layout(SizeProposal::exact(100.0, 50.0));
6891        assert_eq!(tree.hit_test(Point::new(50.0, 25.0)), Some(widget));
6892    }
6893
6894    #[test]
6895    fn arena_effective_transform_composes_ancestors() {
6896        // `arena.effective_transform(id)` must equal the renderer's
6897        // transform-stack top by the time it begins painting `id` —
6898        // i.e. mapping `id`'s pre-transform local point to screen space.
6899        // The renderer's `PushTransform` handler composes as
6900        // `device_t.then(prev_top)` (see `teksilo-render/src/renderer.rs`),
6901        // so the *innermost* transform applies first to a local point.
6902        // For ancestors [outer, inner] both with transforms, this means
6903        // effective = inner.then(outer), NOT outer.then(inner).
6904        // teksilo-scene relies on this to project scene-coord bounds to
6905        // screen space when emitting AT nodes for view-transformed items.
6906        use crate::test_widgets::StackWidget;
6907        let mut tree = WidgetTree::new();
6908        let leaf = tree.add(FillWidget::new());
6909        let inner = tree.add(StackWidget::new().child(leaf));
6910        let outer = tree.add(StackWidget::new().child(inner));
6911        tree.set_transform(outer, teksilo_canvas::Transform2D::translate(100.0, 0.0));
6912        tree.set_transform(inner, teksilo_canvas::Transform2D::scale(2.0, 2.0));
6913        tree.layout(SizeProposal::exact(50.0, 25.0));
6914
6915        let eff = tree.arena.effective_transform(leaf);
6916        let expected = teksilo_canvas::Transform2D::scale(2.0, 2.0)
6917            .then(&teksilo_canvas::Transform2D::translate(100.0, 0.0));
6918        for (a, b) in eff.m.iter().zip(expected.m.iter()) {
6919            assert!(
6920                (a - b).abs() < 1e-5,
6921                "effective_transform mismatch: got {:?}, want {:?}",
6922                eff.m,
6923                expected.m
6924            );
6925        }
6926
6927        // Concrete-point check that pins the composition order without
6928        // relying on matrix equality alone: a leaf-local point at the
6929        // bounds origin (0, 0) should land at screen (100, 0) — scale
6930        // first (still (0,0)), then translate by 100 in x. With the
6931        // wrong composition order it would land at (200, 0).
6932        let screen_origin = eff.apply_point(Point::new(0.0, 0.0));
6933        assert!((screen_origin.x - 100.0).abs() < 1e-5);
6934        assert!((screen_origin.y - 0.0).abs() < 1e-5);
6935        // Far corner: leaf-local (50, 25) → scale → (100, 50) → translate
6936        // by 100 in x → (200, 50).
6937        let screen_corner = eff.apply_point(Point::new(50.0, 25.0));
6938        assert!((screen_corner.x - 200.0).abs() < 1e-5);
6939        assert!((screen_corner.y - 50.0).abs() < 1e-5);
6940    }
6941
6942    // ─── Context-menu factory: position, ctx, None fall-through ─────────
6943
6944    /// A throwaway content widget the factory mounts. We never paint
6945    /// it — the test only checks that it lands in the overlay manager.
6946    #[derive(Debug)]
6947    struct StubMenu;
6948    impl crate::widget::Widget for StubMenu {
6949        fn layout_response(
6950            &self,
6951            _proposal: SizeProposal,
6952            _ctx: &crate::widget::LayoutContext,
6953        ) -> crate::widget::LayoutResponse {
6954            teksilo_canvas::Size::new(100.0, 40.0).into()
6955        }
6956    }
6957
6958    // The keyboard route to a context menu.
6959    //
6960    // Until this existed there was none at all: no `Key::ContextMenu`, no
6961    // Shift+F10, and `Action::ShowContextMenu` appears in zero of the three
6962    // AccessKit adapters, so the assistive-technology route is dead on every
6963    // platform too. A menu reachable only by right-click is a menu a keyboard
6964    // user does not have.
6965
6966    /// A widget that hands the keyboard a different target than itself, the way
6967    /// every data view does: the container has focus, the row is what the menu
6968    /// is about.
6969    #[derive(Debug)]
6970    struct NominatingWidget {
6971        row: std::cell::Cell<Option<WidgetId>>,
6972    }
6973
6974    impl crate::widget::Widget for NominatingWidget {
6975        fn layout_response(
6976            &self,
6977            proposal: SizeProposal,
6978            _ctx: &LayoutContext,
6979        ) -> crate::widget::LayoutResponse {
6980            proposal.resolve(50.0, 20.0).into()
6981        }
6982
6983        fn build(&mut self, ctx: &mut crate::build_context::BuildContext) -> Vec<WidgetId> {
6984            ctx.apply_self_handlers(crate::widget_builder::HandlerSet::new().focusable(true));
6985            Vec::new()
6986        }
6987
6988        fn context_menu_key_target(&self) -> Option<WidgetId> {
6989            self.row.get()
6990        }
6991    }
6992
6993    fn press(tree: &mut WidgetTree, key: Key, modifiers: Modifiers) {
6994        tree.dispatch_event(WidgetEvent::KeyDown {
6995            key,
6996            modifiers,
6997            text: None,
6998        });
6999    }
7000
7001    #[test]
7002    fn the_context_menu_key_opens_the_focused_widget_menu() {
7003        use std::cell::Cell;
7004        use std::rc::Rc;
7005
7006        let opened = Rc::new(Cell::new(false));
7007        let flag = opened.clone();
7008        let mut tree = WidgetTree::new();
7009        let widget = tree.add(
7010            FillWidget::new()
7011                .focusable()
7012                .context_menu(move |_pos, _ctx| {
7013                    flag.set(true);
7014                    Some(Box::new(StubMenu) as Box<dyn crate::widget::Widget>)
7015                }),
7016        );
7017        tree.layout(SizeProposal::exact(200.0, 100.0));
7018        tree.focus(widget);
7019
7020        press(&mut tree, Key::ContextMenu, Modifiers::NONE);
7021        assert!(opened.get(), "the dedicated Menu key must open the menu");
7022    }
7023
7024    /// The chord every Windows and Linux keyboard can reach, including the many
7025    /// that have no dedicated Menu key at all.
7026    #[test]
7027    fn shift_f10_opens_the_focused_widget_menu() {
7028        use std::cell::Cell;
7029        use std::rc::Rc;
7030
7031        let opened = Rc::new(Cell::new(false));
7032        let flag = opened.clone();
7033        let mut tree = WidgetTree::new();
7034        let widget = tree.add(
7035            FillWidget::new()
7036                .focusable()
7037                .context_menu(move |_pos, _ctx| {
7038                    flag.set(true);
7039                    Some(Box::new(StubMenu) as Box<dyn crate::widget::Widget>)
7040                }),
7041        );
7042        tree.layout(SizeProposal::exact(200.0, 100.0));
7043        tree.focus(widget);
7044
7045        press(&mut tree, Key::F10, Modifiers::SHIFT);
7046        assert!(opened.get(), "Shift+F10 must open the menu");
7047    }
7048
7049    /// Modifiers are matched exactly. Ctrl+Shift+F10 is a different gesture and
7050    /// belongs to the application.
7051    #[test]
7052    fn a_near_miss_chord_is_not_a_context_menu_request() {
7053        use std::cell::Cell;
7054        use std::rc::Rc;
7055
7056        let opened = Rc::new(Cell::new(false));
7057        let flag = opened.clone();
7058        let mut tree = WidgetTree::new();
7059        let widget = tree.add(
7060            FillWidget::new()
7061                .focusable()
7062                .context_menu(move |_pos, _ctx| {
7063                    flag.set(true);
7064                    Some(Box::new(StubMenu) as Box<dyn crate::widget::Widget>)
7065                }),
7066        );
7067        tree.layout(SizeProposal::exact(200.0, 100.0));
7068        tree.focus(widget);
7069
7070        press(&mut tree, Key::F10, Modifiers::SHIFT | Modifiers::CTRL);
7071        press(&mut tree, Key::F10, Modifiers::NONE);
7072        assert!(!opened.get(), "only Shift+F10 exactly asks for a menu");
7073    }
7074
7075    /// The correction the design needed. A data view is focusable and its rows
7076    /// are not, so "the focused widget" is the list, and the menu a user asked
7077    /// for on row 4 would have been the list's own.
7078    #[test]
7079    fn the_keyboard_target_can_be_a_row_rather_than_the_focused_container() {
7080        use std::cell::Cell;
7081        use std::rc::Rc;
7082
7083        let menu_owner = Rc::new(Cell::new(None::<&'static str>));
7084
7085        let row_flag = menu_owner.clone();
7086        let container_flag = menu_owner.clone();
7087
7088        let mut tree = WidgetTree::new();
7089        let row = tree.add(FillWidget::new().context_menu(move |_pos, _ctx| {
7090            row_flag.set(Some("row"));
7091            Some(Box::new(StubMenu) as Box<dyn crate::widget::Widget>)
7092        }));
7093        let container = tree.add(
7094            crate::test_widgets::StackWidget::new()
7095                .child(row)
7096                .context_menu(move |_pos, _ctx| {
7097                    container_flag.set(Some("container"));
7098                    Some(Box::new(StubMenu) as Box<dyn crate::widget::Widget>)
7099                }),
7100        );
7101        tree.layout(SizeProposal::exact(200.0, 100.0));
7102
7103        // The container is focused, and nominates the row.
7104        let nominator = tree.add(NominatingWidget {
7105            row: std::cell::Cell::new(Some(row)),
7106        });
7107        tree.layout(SizeProposal::exact(200.0, 100.0));
7108        tree.focus(nominator);
7109        let _ = container;
7110
7111        press(&mut tree, Key::ContextMenu, Modifiers::NONE);
7112        assert_eq!(
7113            menu_owner.get(),
7114            Some("row"),
7115            "the nominated row's factory must be the one that runs"
7116        );
7117    }
7118
7119    /// Nothing on the chain owns a factory, so the framework must not swallow
7120    /// the key: a widget that wants to handle Shift+F10 itself still can.
7121    #[test]
7122    fn the_chord_falls_through_when_there_is_no_menu_to_show() {
7123        use std::cell::Cell;
7124        use std::rc::Rc;
7125
7126        let saw_key = Rc::new(Cell::new(false));
7127        let flag = saw_key.clone();
7128        let mut tree = WidgetTree::new();
7129        let widget = tree.add(FillWidget::new().focusable().on_key(move |ev, _ctx| {
7130            if matches!(ev, WidgetEvent::KeyDown { key: Key::F10, .. }) {
7131                flag.set(true);
7132            }
7133            crate::event::EventResponse::Ignored
7134        }));
7135        tree.layout(SizeProposal::exact(200.0, 100.0));
7136        tree.focus(widget);
7137
7138        press(&mut tree, Key::F10, Modifiers::SHIFT);
7139        assert!(
7140            saw_key.get(),
7141            "with no factory anywhere, the key must reach the widget"
7142        );
7143    }
7144
7145    /// Every route to a menu tells the factory what asked for it, because only
7146    /// a pointer's point is a place the user chose. A text field's factory
7147    /// moves the caret to its point for a right-click; told nothing, it did the
7148    /// same for Shift+F10, and the menu's Paste wrote into the middle of the
7149    /// field.
7150    #[test]
7151    fn each_route_to_a_menu_tells_the_factory_what_asked_for_it() {
7152        use crate::widget_builder::ContextMenuTrigger;
7153        use std::cell::RefCell;
7154        use std::rc::Rc;
7155
7156        let seen = Rc::new(RefCell::new(Vec::new()));
7157        let log = seen.clone();
7158        let mut tree = WidgetTree::new();
7159        let widget = tree.add(
7160            FillWidget::new()
7161                .focusable()
7162                .context_menu(move |_pos, ctx| {
7163                    log.borrow_mut().push(ctx.context_menu_trigger());
7164                    Some(Box::new(StubMenu) as Box<dyn crate::widget::Widget>)
7165                }),
7166        );
7167        tree.layout(SizeProposal::exact(200.0, 100.0));
7168        tree.focus(widget);
7169        let inside = tree.bounds(widget).center();
7170
7171        press(&mut tree, Key::F10, Modifiers::SHIFT);
7172        press(&mut tree, Key::Escape, Modifiers::NONE);
7173        press(&mut tree, Key::ContextMenu, Modifiers::NONE);
7174        press(&mut tree, Key::Escape, Modifiers::NONE);
7175        tree.dispatch_event(WidgetEvent::pointer_down(
7176            inside,
7177            crate::event::PointerButton::Secondary,
7178            Modifiers::NONE,
7179        ));
7180        tree.dispatch_event(WidgetEvent::pointer_up(
7181            inside,
7182            crate::event::PointerButton::Secondary,
7183            Modifiers::NONE,
7184        ));
7185        press(&mut tree, Key::Escape, Modifiers::NONE);
7186        tree.dispatch_event(WidgetEvent::AccessAction {
7187            action: accesskit::Action::ShowContextMenu,
7188            target: Some(widget),
7189            target_node: crate::accessibility::widget_id_to_node_id(widget),
7190            data: None,
7191        });
7192        press(&mut tree, Key::Escape, Modifiers::NONE);
7193        tree.long_press_at(teksilo_tokens::PointerKind::Touch, inside);
7194
7195        assert_eq!(
7196            *seen.borrow(),
7197            vec![
7198                Some(ContextMenuTrigger::Keyboard),
7199                Some(ContextMenuTrigger::Keyboard),
7200                Some(ContextMenuTrigger::Pointer),
7201                Some(ContextMenuTrigger::Accessibility),
7202                Some(ContextMenuTrigger::Pointer),
7203            ],
7204            "Shift+F10, the Menu key, a right-click, the assistive action and a \
7205             hold, in that order"
7206        );
7207    }
7208
7209    #[test]
7210    fn context_menu_factory_receives_click_position() {
7211        use crate::event::{Modifiers, PointerButton};
7212        use std::cell::Cell;
7213        use std::rc::Rc;
7214
7215        let captured_position = Rc::new(Cell::new(None::<Point>));
7216        let cap = captured_position.clone();
7217        let mut tree = WidgetTree::new();
7218        let widget = tree.add(FillWidget::new().context_menu(move |pos, _ctx| {
7219            cap.set(Some(pos));
7220            Some(Box::new(StubMenu) as Box<dyn crate::widget::Widget>)
7221        }));
7222        tree.layout(SizeProposal::exact(200.0, 100.0));
7223
7224        let click = Point::new(73.0, 42.0);
7225        tree.dispatch_event(WidgetEvent::pointer_down(
7226            click,
7227            PointerButton::Secondary,
7228            Modifiers::NONE,
7229        ));
7230
7231        let got = captured_position.get();
7232        assert_eq!(
7233            got,
7234            Some(click),
7235            "factory must receive the click position; got {:?}",
7236            got
7237        );
7238        let _ = widget;
7239    }
7240
7241    #[test]
7242    fn context_menu_factory_returning_none_falls_through_to_parent() {
7243        use crate::event::{Modifiers, PointerButton};
7244        use crate::test_widgets::StackWidget;
7245        use std::cell::Cell;
7246        use std::rc::Rc;
7247
7248        // Outer factory always returns Some(StubMenu); inner factory
7249        // returns None. Right-click should walk past the inner and
7250        // mount the outer's menu.
7251        let outer_called = Rc::new(Cell::new(0_u32));
7252        let outer_flag = outer_called.clone();
7253        let mut tree = WidgetTree::new();
7254        let inner = tree.add(FillWidget::new().context_menu(|_pos, _ctx| None));
7255        let _outer = tree.add(
7256            StackWidget::new()
7257                .child(inner)
7258                .context_menu(move |_pos, _ctx| {
7259                    outer_flag.set(outer_flag.get() + 1);
7260                    Some(Box::new(StubMenu) as Box<dyn crate::widget::Widget>)
7261                }),
7262        );
7263        tree.layout(SizeProposal::exact(200.0, 100.0));
7264
7265        tree.dispatch_event(WidgetEvent::pointer_down(
7266            Point::new(50.0, 25.0),
7267            PointerButton::Secondary,
7268            Modifiers::NONE,
7269        ));
7270
7271        assert_eq!(
7272            outer_called.get(),
7273            1,
7274            "inner returning None must fall through to the outer factory"
7275        );
7276    }
7277
7278    #[test]
7279    fn context_menu_factory_none_throughout_chain_does_not_show_overlay() {
7280        use crate::event::{Modifiers, PointerButton};
7281
7282        // Single factory returning None → no overlay shown, no panic.
7283        let mut tree = WidgetTree::new();
7284        tree.add(FillWidget::new().context_menu(|_pos, _ctx| None));
7285        tree.layout(SizeProposal::exact(200.0, 100.0));
7286
7287        let overlay_count_before = tree.overlay_manager.len();
7288        tree.dispatch_event(WidgetEvent::pointer_down(
7289            Point::new(50.0, 25.0),
7290            PointerButton::Secondary,
7291            Modifiers::NONE,
7292        ));
7293        let overlay_count_after = tree.overlay_manager.len();
7294        assert_eq!(
7295            overlay_count_before, overlay_count_after,
7296            "a factory returning None must not mount any overlay"
7297        );
7298    }
7299
7300    // ---- Reconcile-on-rebuild (`preserves_children_on_rebuild`) ----------
7301    //
7302    // These pin the contract that the preserve path RECONCILES: it keeps the
7303    // children a rebuild re-attaches (and any subtree re-parented into the new
7304    // tree) while reaping the ones it drops — so memoizing widgets are both
7305    // stateful and leak-free. Regression guard for the orphan-leak the old
7306    // "preserve = destroy nothing" behaviour caused.
7307
7308    /// `build()` mints a fresh child every time and returns only it, abandoning
7309    /// the previous one. Used to prove dropped children are reaped, not leaked.
7310    #[derive(Debug)]
7311    struct FreshChildHost {
7312        preserve: bool,
7313    }
7314    impl Widget for FreshChildHost {
7315        fn build(&mut self, ctx: &mut crate::build_context::BuildContext) -> Vec<WidgetId> {
7316            vec![ctx.add(FillWidget::new())]
7317        }
7318        fn layout_response(
7319            &self,
7320            p: SizeProposal,
7321            _c: &LayoutContext,
7322        ) -> crate::widget::LayoutResponse {
7323            p.resolve(10.0, 10.0).into()
7324        }
7325        fn preserves_children_on_rebuild(&self) -> bool {
7326            self.preserve
7327        }
7328    }
7329
7330    #[test]
7331    fn reconcile_reaps_dropped_children_no_leak() {
7332        // preserve=false (destroy-all) and preserve=true (reconcile) must BOTH
7333        // keep the arena bounded when a rebuild drops its old child. Before the
7334        // reconcile fix, preserve=true grew the arena (and the active set) by
7335        // one stranded orphan per rebuild.
7336        for preserve in [false, true] {
7337            let mut tree = WidgetTree::new();
7338            let host = tree.add(FreshChildHost { preserve });
7339            tree.layout(SizeProposal::exact(100.0, 100.0));
7340            let total0 = tree.arena.len();
7341            let active0 = tree.active_widget_count();
7342            for _ in 0..5 {
7343                tree.arena_mark_needs_rebuild_for_testing(host);
7344                tree.layout(SizeProposal::exact(100.0, 100.0));
7345            }
7346            assert_eq!(
7347                tree.arena.len(),
7348                total0,
7349                "preserve={preserve}: dropped children must be reaped, not leaked"
7350            );
7351            assert_eq!(
7352                tree.active_widget_count(),
7353                active0,
7354                "preserve={preserve}: no stranded still-active orphans"
7355            );
7356        }
7357    }
7358
7359    /// `build()` mints one **detached** node every time — the shape of every
7360    /// pre-built popup in the widget crate (a dropdown, a calendar, a
7361    /// tooltip's cascade children): parked dormant, shown later through an
7362    /// overlay, and deliberately not a child, since activation and paint both
7363    /// descend through `children`.
7364    #[derive(Debug)]
7365    struct DetachedContentHost {
7366        preserve: bool,
7367    }
7368    impl Widget for DetachedContentHost {
7369        fn build(&mut self, ctx: &mut crate::build_context::BuildContext) -> Vec<WidgetId> {
7370            let popup = ctx.add_detached(FillWidget::new());
7371            ctx.set_dormant(popup);
7372            vec![ctx.add(FillWidget::new())]
7373        }
7374        fn layout_response(
7375            &self,
7376            p: SizeProposal,
7377            _c: &LayoutContext,
7378        ) -> crate::widget::LayoutResponse {
7379            p.resolve(10.0, 10.0).into()
7380        }
7381        fn preserves_children_on_rebuild(&self) -> bool {
7382            self.preserve
7383        }
7384    }
7385
7386    #[test]
7387    fn rebuilding_reaps_detached_content_no_leak() {
7388        // A parentless node is reachable from no walk at all — not the child
7389        // teardown, not the accessibility tree, not `active_widget_count`. Held
7390        // by a bare `ctx.add` it simply accumulated: one stranded popup per
7391        // rebuild, for the lifetime of the process. `add_detached` records the
7392        // ownership edge that makes it reapable.
7393        for preserve in [false, true] {
7394            let mut tree = WidgetTree::new();
7395            let host = tree.add(DetachedContentHost { preserve });
7396            tree.layout(SizeProposal::exact(100.0, 100.0));
7397            let total0 = tree.arena.len();
7398            for _ in 0..5 {
7399                tree.arena_mark_needs_rebuild_for_testing(host);
7400                tree.layout(SizeProposal::exact(100.0, 100.0));
7401            }
7402            assert_eq!(
7403                tree.arena.len(),
7404                total0,
7405                "preserve={preserve}: the previous build's detached content must be reaped"
7406            );
7407        }
7408    }
7409
7410    #[test]
7411    fn destroying_a_host_reaps_its_detached_content() {
7412        let mut tree = WidgetTree::new();
7413        let outer = tree.add(FillWidget::new());
7414        tree.layout(SizeProposal::exact(100.0, 100.0));
7415        let empty = tree.arena.len();
7416
7417        let host = tree.add_child(outer, DetachedContentHost { preserve: false });
7418        tree.layout(SizeProposal::exact(100.0, 100.0));
7419        assert!(tree.arena.len() > empty);
7420
7421        tree.destroy_subtree(host);
7422        assert_eq!(
7423            tree.arena.len(),
7424            empty,
7425            "the popup must die with the widget that built it"
7426        );
7427    }
7428
7429    /// Memoizes one child and re-attaches the same id every build.
7430    #[derive(Debug)]
7431    struct StableChildHost {
7432        child: Option<WidgetId>,
7433        probe: std::rc::Rc<std::cell::Cell<Option<WidgetId>>>,
7434    }
7435    impl Widget for StableChildHost {
7436        fn build(&mut self, ctx: &mut crate::build_context::BuildContext) -> Vec<WidgetId> {
7437            let id = match self.child {
7438                Some(id) => id,
7439                None => {
7440                    let id = ctx.add(FillWidget::new());
7441                    self.child = Some(id);
7442                    self.probe.set(Some(id));
7443                    id
7444                }
7445            };
7446            vec![id]
7447        }
7448        fn layout_response(
7449            &self,
7450            p: SizeProposal,
7451            _c: &LayoutContext,
7452        ) -> crate::widget::LayoutResponse {
7453            p.resolve(10.0, 10.0).into()
7454        }
7455        fn preserves_children_on_rebuild(&self) -> bool {
7456            true
7457        }
7458    }
7459
7460    #[test]
7461    fn reconcile_preserves_reattached_child() {
7462        let probe = std::rc::Rc::new(std::cell::Cell::new(None));
7463        let mut tree = WidgetTree::new();
7464        let host = tree.add(StableChildHost {
7465            child: None,
7466            probe: probe.clone(),
7467        });
7468        tree.layout(SizeProposal::exact(100.0, 100.0));
7469        let child = probe.get().expect("child mounted");
7470        let total0 = tree.arena.len();
7471        for _ in 0..5 {
7472            tree.arena_mark_needs_rebuild_for_testing(host);
7473            tree.layout(SizeProposal::exact(100.0, 100.0));
7474        }
7475        assert!(
7476            tree.arena.is_active(child),
7477            "the re-attached child must survive every rebuild"
7478        );
7479        assert_eq!(tree.arena.len(), total0, "no growth — same child reused");
7480    }
7481
7482    /// Re-homes a node returned from its `build()` under itself.
7483    #[derive(Debug)]
7484    struct Wrapper {
7485        child: WidgetId,
7486    }
7487    impl Widget for Wrapper {
7488        fn build(&mut self, _ctx: &mut crate::build_context::BuildContext) -> Vec<WidgetId> {
7489            vec![self.child]
7490        }
7491        fn layout_response(
7492            &self,
7493            p: SizeProposal,
7494            _c: &LayoutContext,
7495        ) -> crate::widget::LayoutResponse {
7496            p.resolve(10.0, 10.0).into()
7497        }
7498    }
7499
7500    /// Memoizes a body, then wraps it in a FRESH `Wrapper` each build —
7501    /// re-parenting the body out of the previous (now dropped) wrapper. This is
7502    /// the TabWidget / CompositeTooltip pattern in miniature.
7503    #[derive(Debug)]
7504    struct ReparentHost {
7505        body: Option<WidgetId>,
7506        probe: std::rc::Rc<std::cell::Cell<Option<WidgetId>>>,
7507    }
7508    impl Widget for ReparentHost {
7509        fn build(&mut self, ctx: &mut crate::build_context::BuildContext) -> Vec<WidgetId> {
7510            let body = match self.body {
7511                Some(id) => id,
7512                None => {
7513                    let id = ctx.add(FillWidget::new());
7514                    self.body = Some(id);
7515                    self.probe.set(Some(id));
7516                    id
7517                }
7518            };
7519            vec![ctx.add(Wrapper { child: body })]
7520        }
7521        fn layout_response(
7522            &self,
7523            p: SizeProposal,
7524            _c: &LayoutContext,
7525        ) -> crate::widget::LayoutResponse {
7526            p.resolve(10.0, 10.0).into()
7527        }
7528        fn preserves_children_on_rebuild(&self) -> bool {
7529            true
7530        }
7531    }
7532
7533    #[test]
7534    fn reconcile_spares_reparented_survivor() {
7535        // The memoized body is re-parented into a fresh wrapper each rebuild;
7536        // the old wrapper is dropped. The body must survive (it is re-homed),
7537        // and the old wrappers must be reaped (no leak). This is the exact
7538        // failure that destroyed TabWidget's static panel before the fix: the
7539        // parent-authoritative recursion + single-node arena removal spare the
7540        // re-homed body while still reaping the dropped wrapper subtree.
7541        let probe = std::rc::Rc::new(std::cell::Cell::new(None));
7542        let mut tree = WidgetTree::new();
7543        let host = tree.add(ReparentHost {
7544            body: None,
7545            probe: probe.clone(),
7546        });
7547        tree.layout(SizeProposal::exact(100.0, 100.0));
7548        let body = probe.get().expect("body mounted");
7549        let total0 = tree.arena.len();
7550        for _ in 0..5 {
7551            tree.arena_mark_needs_rebuild_for_testing(host);
7552            tree.layout(SizeProposal::exact(100.0, 100.0));
7553        }
7554        assert!(
7555            tree.arena.is_active(body),
7556            "the re-parented body must survive — it was moved into the new tree, \
7557             not swept with the dropped wrapper"
7558        );
7559        assert_eq!(
7560            tree.arena.len(),
7561            total0,
7562            "dropped wrappers reaped — no per-rebuild leak"
7563        );
7564    }
7565
7566    // -----------------------------------------------------------------
7567    // EventContext::ensure_visible / ensure_widget_visible — the
7568    // rect/id-based outer-scroll chase drained in `collect_from_ctx`.
7569    // -----------------------------------------------------------------
7570
7571    /// A `clips_children` container that places its single child at a fixed
7572    /// vertical offset — used to give a child arena bounds *outside* the
7573    /// container's viewport so the id-based `ensure_widget_visible` walk has a
7574    /// reason to dispatch `ScrollIntoView`.
7575    #[derive(Debug)]
7576    struct BelowContainer {
7577        child: Option<WidgetId>,
7578        offset: f32,
7579    }
7580
7581    impl crate::widget::Widget for BelowContainer {
7582        fn layout_response(
7583            &self,
7584            proposal: SizeProposal,
7585            _ctx: &crate::widget::LayoutContext,
7586        ) -> crate::widget::LayoutResponse {
7587            proposal.resolve(0.0, 0.0).into()
7588        }
7589        fn place_children(
7590            &self,
7591            bounds: Rect,
7592            _proposal: SizeProposal,
7593            children: &mut [crate::widget::WidgetPlacement],
7594            _ctx: &crate::widget::LayoutContext,
7595        ) {
7596            for c in children.iter_mut() {
7597                c.origin = Point::new(bounds.x, bounds.y + self.offset);
7598                c.size = bounds.size();
7599            }
7600        }
7601        fn children(&self) -> Vec<WidgetId> {
7602            self.child.into_iter().collect()
7603        }
7604    }
7605
7606    /// A `clips_children` container that records the `ScrollIntoView` it
7607    /// receives, so a test can assert what the framework dispatched to it.
7608    fn recording_scroll_container(
7609        tree: &mut WidgetTree,
7610        child: WidgetId,
7611        recorded: std::rc::Rc<std::cell::Cell<Option<Rect>>>,
7612    ) -> WidgetId {
7613        use crate::test_widgets::StackWidget;
7614        tree.add(
7615            StackWidget::new()
7616                .child(child)
7617                .on_scroll(move |ev, _ctx| match ev {
7618                    WidgetEvent::ScrollIntoView { target_bounds, .. } => {
7619                        recorded.set(Some(*target_bounds));
7620                        EventResponse::Handled
7621                    }
7622                    _ => EventResponse::Ignored,
7623                })
7624                .clips_children(true),
7625        )
7626    }
7627
7628    #[test]
7629    fn ensure_visible_dispatches_scroll_into_view_to_clipping_ancestor() {
7630        use std::cell::Cell;
7631        use std::rc::Rc;
7632        let recorded: Rc<Cell<Option<Rect>>> = Rc::new(Cell::new(None));
7633        let mut tree = WidgetTree::new();
7634        let actor = tree.add(FillWidget::new());
7635        let _container = recording_scroll_container(&mut tree, actor, recorded.clone());
7636        tree.layout(SizeProposal::exact(100.0, 100.0));
7637
7638        // A rect well below the 100px viewport — the container must be asked to
7639        // reveal it.
7640        let target = Rect::new(10.0, 500.0, 20.0, 15.0);
7641        let mut ctx = EventContext::new();
7642        ctx.ensure_visible(target);
7643        tree.collect_from_ctx(ctx, actor);
7644
7645        assert_eq!(
7646            recorded.get(),
7647            Some(target),
7648            "ensure_visible(rect) must dispatch ScrollIntoView with the exact rect \
7649             to the clips_children ancestor"
7650        );
7651    }
7652
7653    #[test]
7654    fn ensure_visible_is_noop_when_rect_already_visible() {
7655        use std::cell::Cell;
7656        use std::rc::Rc;
7657        let recorded: Rc<Cell<Option<Rect>>> = Rc::new(Cell::new(None));
7658        let mut tree = WidgetTree::new();
7659        let actor = tree.add(FillWidget::new());
7660        let _container = recording_scroll_container(&mut tree, actor, recorded.clone());
7661        tree.layout(SizeProposal::exact(100.0, 100.0));
7662
7663        // Fully inside the viewport → the ancestor already shows it, so no
7664        // ScrollIntoView is dispatched.
7665        let mut ctx = EventContext::new();
7666        ctx.ensure_visible(Rect::new(10.0, 10.0, 20.0, 15.0));
7667        tree.collect_from_ctx(ctx, actor);
7668
7669        assert_eq!(
7670            recorded.get(),
7671            None,
7672            "a rect already inside the viewport must not trigger a scroll"
7673        );
7674    }
7675
7676    #[test]
7677    fn ensure_visible_margin_forces_scroll_near_edge() {
7678        use std::cell::Cell;
7679        use std::rc::Rc;
7680        let recorded: Rc<Cell<Option<Rect>>> = Rc::new(Cell::new(None));
7681        let mut tree = WidgetTree::new();
7682        let actor = tree.add(FillWidget::new());
7683        let _container = recording_scroll_container(&mut tree, actor, recorded.clone());
7684        tree.layout(SizeProposal::exact(100.0, 100.0));
7685
7686        // Rect at y=95..99 is visible at margin 0, but with a 10px margin its
7687        // padded bottom (109) spills past the 100px viewport → scroll.
7688        let rect = Rect::new(10.0, 95.0, 20.0, 4.0);
7689        let mut ctx = EventContext::new();
7690        ctx.ensure_visible_with_margin(rect, 10.0);
7691        tree.collect_from_ctx(ctx, actor);
7692
7693        assert_eq!(
7694            recorded.get(),
7695            Some(rect),
7696            "the margin must widen the visibility test so a near-edge rect scrolls"
7697        );
7698    }
7699
7700    /// A `clips_children` container that records the alignment and motion of the
7701    /// `ScrollIntoView` it receives.
7702    fn recording_align_container(
7703        tree: &mut WidgetTree,
7704        child: WidgetId,
7705        recorded: std::rc::Rc<
7706            std::cell::Cell<Option<(crate::event::ScrollAlign, crate::event::ScrollMotion)>>,
7707        >,
7708    ) -> WidgetId {
7709        use crate::test_widgets::StackWidget;
7710        tree.add(
7711            StackWidget::new()
7712                .child(child)
7713                .on_scroll(move |ev, _ctx| match ev {
7714                    WidgetEvent::ScrollIntoView { align, motion, .. } => {
7715                        recorded.set(Some((*align, *motion)));
7716                        EventResponse::Handled
7717                    }
7718                    _ => EventResponse::Ignored,
7719                })
7720                .clips_children(true),
7721        )
7722    }
7723
7724    #[test]
7725    fn ensure_visible_aligned_scrolls_even_when_already_visible() {
7726        use std::cell::Cell;
7727        use std::rc::Rc;
7728        let recorded: Rc<Cell<Option<Rect>>> = Rc::new(Cell::new(None));
7729        let mut tree = WidgetTree::new();
7730        let actor = tree.add(FillWidget::new());
7731        let _container = recording_scroll_container(&mut tree, actor, recorded.clone());
7732        tree.layout(SizeProposal::exact(100.0, 100.0));
7733
7734        // Comfortably inside the viewport — a *minimal* reveal would decline
7735        // (see `ensure_visible_is_noop_when_rect_already_visible`). A pin must
7736        // still fire: re-asserting unconditionally is the whole difference
7737        // between "keep it on screen" and "hold it at this height".
7738        let target = Rect::new(10.0, 10.0, 20.0, 15.0);
7739        let mut ctx = EventContext::new();
7740        ctx.ensure_visible_aligned(target, 0.5, crate::event::ScrollMotion::Instant);
7741        tree.collect_from_ctx(ctx, actor);
7742
7743        assert_eq!(
7744            recorded.get(),
7745            Some(target),
7746            "an aligned reveal must dispatch even when the rect is already visible"
7747        );
7748    }
7749
7750    #[test]
7751    fn ensure_visible_aligned_forwards_fraction_and_motion() {
7752        use std::cell::Cell;
7753        use std::rc::Rc;
7754        let recorded: Rc<Cell<Option<(crate::event::ScrollAlign, crate::event::ScrollMotion)>>> =
7755            Rc::new(Cell::new(None));
7756        let mut tree = WidgetTree::new();
7757        let actor = tree.add(FillWidget::new());
7758        let _container = recording_align_container(&mut tree, actor, recorded.clone());
7759        tree.layout(SizeProposal::exact(100.0, 100.0));
7760
7761        let mut ctx = EventContext::new();
7762        ctx.ensure_visible_aligned(
7763            Rect::new(10.0, 10.0, 20.0, 15.0),
7764            0.25,
7765            crate::event::ScrollMotion::Smooth,
7766        );
7767        tree.collect_from_ctx(ctx, actor);
7768
7769        assert_eq!(
7770            recorded.get(),
7771            Some((
7772                crate::event::ScrollAlign::Fraction(0.25),
7773                crate::event::ScrollMotion::Smooth
7774            )),
7775            "the container must receive the requested fraction and motion verbatim"
7776        );
7777    }
7778
7779    #[test]
7780    fn ensure_visible_aligned_clamps_the_fraction() {
7781        use std::cell::Cell;
7782        use std::rc::Rc;
7783        let recorded: Rc<Cell<Option<(crate::event::ScrollAlign, crate::event::ScrollMotion)>>> =
7784            Rc::new(Cell::new(None));
7785        let mut tree = WidgetTree::new();
7786        let actor = tree.add(FillWidget::new());
7787        let _container = recording_align_container(&mut tree, actor, recorded.clone());
7788        tree.layout(SizeProposal::exact(100.0, 100.0));
7789
7790        let mut ctx = EventContext::new();
7791        ctx.ensure_visible_aligned(
7792            Rect::new(10.0, 10.0, 20.0, 15.0),
7793            4.2,
7794            crate::event::ScrollMotion::Instant,
7795        );
7796        tree.collect_from_ctx(ctx, actor);
7797
7798        assert_eq!(
7799            recorded.get().map(|(a, _)| a),
7800            Some(crate::event::ScrollAlign::Fraction(1.0)),
7801            "an out-of-range fraction must clamp rather than aim the pin off-screen"
7802        );
7803    }
7804
7805    #[test]
7806    fn plain_ensure_visible_requests_minimal_alignment() {
7807        use std::cell::Cell;
7808        use std::rc::Rc;
7809        let recorded: Rc<Cell<Option<(crate::event::ScrollAlign, crate::event::ScrollMotion)>>> =
7810            Rc::new(Cell::new(None));
7811        let mut tree = WidgetTree::new();
7812        let actor = tree.add(FillWidget::new());
7813        let _container = recording_align_container(&mut tree, actor, recorded.clone());
7814        tree.layout(SizeProposal::exact(100.0, 100.0));
7815
7816        let mut ctx = EventContext::new();
7817        ctx.ensure_visible(Rect::new(10.0, 500.0, 20.0, 15.0));
7818        tree.collect_from_ctx(ctx, actor);
7819
7820        assert_eq!(
7821            recorded.get(),
7822            Some((
7823                crate::event::ScrollAlign::Minimal,
7824                crate::event::ScrollMotion::Instant
7825            )),
7826            "the pre-existing reveal API must keep its exact semantics"
7827        );
7828    }
7829
7830    #[test]
7831    fn only_the_innermost_container_aligns() {
7832        use std::cell::Cell;
7833        use std::rc::Rc;
7834        let inner_rec: Rc<Cell<Option<(crate::event::ScrollAlign, crate::event::ScrollMotion)>>> =
7835            Rc::new(Cell::new(None));
7836        let outer_rec: Rc<Cell<Option<(crate::event::ScrollAlign, crate::event::ScrollMotion)>>> =
7837            Rc::new(Cell::new(None));
7838
7839        let mut tree = WidgetTree::new();
7840        let actor = tree.add(FillWidget::new());
7841        let inner = recording_align_container(&mut tree, actor, inner_rec.clone());
7842        let _outer = recording_align_container(&mut tree, inner, outer_rec.clone());
7843        tree.layout(SizeProposal::exact(100.0, 100.0));
7844
7845        // Off-screen, so the outer container is asked too (a `Minimal` request
7846        // is gated on visibility).
7847        let mut ctx = EventContext::new();
7848        ctx.ensure_visible_aligned(
7849            Rect::new(10.0, 500.0, 20.0, 15.0),
7850            0.5,
7851            crate::event::ScrollMotion::Instant,
7852        );
7853        tree.collect_from_ctx(ctx, actor);
7854
7855        assert_eq!(
7856            inner_rec.get().map(|(a, _)| a),
7857            Some(crate::event::ScrollAlign::Fraction(0.5)),
7858            "the innermost clipping ancestor owns the pin"
7859        );
7860        assert_eq!(
7861            outer_rec.get().map(|(a, _)| a),
7862            Some(crate::event::ScrollAlign::Minimal),
7863            "an outer container must only bring the inner viewport into view — a \
7864             fraction names a height in one viewport, not in every ancestor's"
7865        );
7866    }
7867
7868    #[test]
7869    fn a_clipper_that_does_not_scroll_passes_the_pin_on() {
7870        // The shape of every capped text column: the editor inside a `MaxSize`
7871        // (which clips once a cap is set, and has no `on_scroll`) inside the
7872        // page's scroll area. The wrapper cannot act on a `ScrollIntoView`, so
7873        // it must not be the one the pin is spent on. Otherwise the scroll
7874        // area is handed a plain reveal and typewriter scrolling silently
7875        // becomes ordinary caret-following.
7876        use crate::test_widgets::StackWidget;
7877        use std::cell::Cell;
7878        use std::rc::Rc;
7879        let outer_rec: Rc<Cell<Option<(crate::event::ScrollAlign, crate::event::ScrollMotion)>>> =
7880            Rc::new(Cell::new(None));
7881
7882        let mut tree = WidgetTree::new();
7883        let actor = tree.add(FillWidget::new());
7884        let clipper = tree.add(StackWidget::new().child(actor).clips_children_on(true));
7885        let _scroller = recording_align_container(&mut tree, clipper, outer_rec.clone());
7886        tree.layout(SizeProposal::exact(100.0, 100.0));
7887
7888        // Inside the viewport, so only a pin (never a minimal reveal) reaches
7889        // the scroller at all.
7890        let mut ctx = EventContext::new();
7891        ctx.ensure_visible_aligned(
7892            Rect::new(10.0, 10.0, 20.0, 15.0),
7893            0.5,
7894            crate::event::ScrollMotion::Instant,
7895        );
7896        tree.collect_from_ctx(ctx, actor);
7897
7898        assert_eq!(
7899            outer_rec.get().map(|(a, _)| a),
7900            Some(crate::event::ScrollAlign::Fraction(0.5)),
7901            "a clipping wrapper with no scroll handler must pass the pin through \
7902             to the scroll container above it"
7903        );
7904    }
7905
7906    #[test]
7907    fn a_scroller_that_declines_to_move_still_holds_the_pin() {
7908        // What the scroller does with the pin is its own business: a `SceneView`
7909        // already holding the target where asked answers `Ignored`, since it
7910        // moved nothing. That is not an invitation for the next container out
7911        // to align a rectangle inside a viewport it does not own.
7912        use crate::test_widgets::StackWidget;
7913        use std::cell::Cell;
7914        use std::rc::Rc;
7915        let inner_rec: Rc<Cell<Option<crate::event::ScrollAlign>>> = Rc::new(Cell::new(None));
7916        let outer_rec: Rc<Cell<Option<(crate::event::ScrollAlign, crate::event::ScrollMotion)>>> =
7917            Rc::new(Cell::new(None));
7918
7919        let mut tree = WidgetTree::new();
7920        let actor = tree.add(FillWidget::new());
7921        let rec = inner_rec.clone();
7922        let inner = tree.add(
7923            StackWidget::new()
7924                .child(actor)
7925                .on_scroll(move |ev, _ctx| match ev {
7926                    WidgetEvent::ScrollIntoView { align, .. } => {
7927                        rec.set(Some(*align));
7928                        EventResponse::Ignored
7929                    }
7930                    _ => EventResponse::Ignored,
7931                })
7932                .clips_children(true),
7933        );
7934        let _outer = recording_align_container(&mut tree, inner, outer_rec.clone());
7935        tree.layout(SizeProposal::exact(100.0, 100.0));
7936
7937        // Off-screen, so the outer container is asked too.
7938        let mut ctx = EventContext::new();
7939        ctx.ensure_visible_aligned(
7940            Rect::new(10.0, 500.0, 20.0, 15.0),
7941            0.5,
7942            crate::event::ScrollMotion::Instant,
7943        );
7944        tree.collect_from_ctx(ctx, actor);
7945
7946        assert_eq!(
7947            inner_rec.get(),
7948            Some(crate::event::ScrollAlign::Fraction(0.5)),
7949            "the innermost scroller is offered the pin"
7950        );
7951        assert_eq!(
7952            outer_rec.get().map(|(a, _)| a),
7953            Some(crate::event::ScrollAlign::Minimal),
7954            "declining to move must not pass the pin outward"
7955        );
7956    }
7957
7958    #[test]
7959    fn ensure_widget_visible_uses_target_arena_bounds() {
7960        use std::cell::Cell;
7961        use std::rc::Rc;
7962        let recorded: Rc<Cell<Option<Rect>>> = Rc::new(Cell::new(None));
7963        let mut tree = WidgetTree::new();
7964        // Target lives 500px below the container's top — off the viewport.
7965        let target = tree.add(FillWidget::new());
7966        let rec = recorded.clone();
7967        let container = tree.add(
7968            BelowContainer {
7969                child: Some(target),
7970                offset: 500.0,
7971            }
7972            .on_scroll(move |ev, _ctx| match ev {
7973                WidgetEvent::ScrollIntoView { target_bounds, .. } => {
7974                    rec.set(Some(*target_bounds));
7975                    EventResponse::Handled
7976                }
7977                _ => EventResponse::Ignored,
7978            })
7979            .clips_children(true),
7980        );
7981        tree.layout(SizeProposal::exact(100.0, 100.0));
7982
7983        let expected = tree.bounds(target);
7984        assert!(
7985            expected.y > 100.0,
7986            "fixture sanity: the target must sit below the viewport (y={})",
7987            expected.y
7988        );
7989
7990        // The source widget is irrelevant for the id-based walk — it starts
7991        // from the *target's* parent — so pass the container itself.
7992        let mut ctx = EventContext::new();
7993        ctx.ensure_widget_visible(target);
7994        tree.collect_from_ctx(ctx, container);
7995
7996        assert_eq!(
7997            recorded.get(),
7998            Some(expected),
7999            "ensure_widget_visible(id) must dispatch ScrollIntoView with the \
8000             target's current arena bounds"
8001        );
8002    }
8003
8004    #[test]
8005    fn ensure_widget_visible_ignores_missing_widget() {
8006        // A never-mounted id must neither panic nor dispatch a spurious scroll.
8007        use std::cell::Cell;
8008        use std::rc::Rc;
8009        let recorded: Rc<Cell<Option<Rect>>> = Rc::new(Cell::new(None));
8010        let mut tree = WidgetTree::new();
8011        let actor = tree.add(FillWidget::new());
8012        let _container = recording_scroll_container(&mut tree, actor, recorded.clone());
8013        tree.layout(SizeProposal::exact(100.0, 100.0));
8014
8015        let mut ctx = EventContext::new();
8016        ctx.ensure_widget_visible(WidgetId::default());
8017        tree.collect_from_ctx(ctx, actor); // must not panic
8018
8019        assert_eq!(
8020            recorded.get(),
8021            None,
8022            "an unmounted id must not trigger a scroll"
8023        );
8024    }
8025
8026    #[test]
8027    fn context_menu_inside_a_modal_keeps_the_modal() {
8028        // Regression: right-clicking a widget that lives inside an open modal must
8029        // open its context menu WITHOUT tearing down the modal. `show_context_menu_for`
8030        // used to `dismiss_all()`, which closed the very overlay hosting the editor.
8031        use crate::event::{Modifiers, PointerButton, WidgetEvent};
8032        use crate::overlay::{DismissBehavior, OverlayPlacement, OverlayRequest};
8033        use crate::test_widgets::{FillWidget, StackWidget};
8034
8035        let mut tree = WidgetTree::new();
8036        // A container standing in for the modal's content subtree, with the editor
8037        // (a right-clickable widget) inside it.
8038        let modal_content = tree.add(StackWidget::new());
8039        let _editor = tree.add_child(
8040            modal_content,
8041            FillWidget::new()
8042                .context_menu(|_pos, _ctx| Some(Box::new(FillWidget::new()) as Box<dyn Widget>)),
8043        );
8044        tree.layout(SizeProposal::exact(200.0, 100.0));
8045
8046        let modal = tree.overlay_manager.show(OverlayRequest::new(
8047            modal_content,
8048            modal_content,
8049            OverlayPlacement::Centered,
8050            DismissBehavior::EscapeKey,
8051        ));
8052        // Give the overlay real bounds so the right-click hit-tests inside it.
8053        tree.overlay_manager
8054            .stack
8055            .iter_mut()
8056            .find(|o| o.id == modal)
8057            .unwrap()
8058            .bounds = Rect::new(0.0, 0.0, 200.0, 100.0);
8059        assert_eq!(tree.overlay_manager.len(), 1);
8060
8061        // Right-click the editor inside the modal.
8062        tree.dispatch_event(WidgetEvent::pointer_down(
8063            Point::new(50.0, 25.0),
8064            PointerButton::Secondary,
8065            Modifiers::NONE,
8066        ));
8067
8068        assert!(
8069            tree.overlay_manager.active_ids().contains(&modal),
8070            "the modal must survive opening a context menu inside it"
8071        );
8072        assert_eq!(
8073            tree.overlay_manager.len(),
8074            2,
8075            "the context menu should now be open on top of the surviving modal"
8076        );
8077    }
8078}
8079
8080/// The stage-1 input ingress: the two sample doors, the scroll routing rule,
8081/// and the guarantee that a mouse still behaves exactly as it did.
8082#[cfg(test)]
8083mod input_ingress_tests {
8084    use super::*;
8085    use crate::event::{EventResponse, Modifiers, PointerButton, ScrollDelta};
8086    use crate::pointer::{
8087        EventTime, PointerId, PointerInfo, PointerPhase, PointerSample, ScrollPhase, ScrollSample,
8088        ScrollSource,
8089    };
8090    use crate::test_widgets::FillWidget;
8091    use crate::widget::{LayoutContext, WidgetPlacement};
8092    use crate::widget_builder::WidgetBuilder;
8093    use std::cell::RefCell;
8094    use std::rc::Rc;
8095
8096    /// A container that lays children out side by side across its bounds, so a
8097    /// hit test at a given x picks a specific child.
8098    ///
8099    /// Local rather than shared: the common `StackWidget` deliberately stacks
8100    /// its children at one origin, which is the opposite of what a routing test
8101    /// needs.
8102    #[derive(Debug)]
8103    struct RowWidget {
8104        children: Vec<WidgetId>,
8105    }
8106
8107    impl crate::widget::Widget for RowWidget {
8108        fn layout_response(
8109            &self,
8110            proposal: SizeProposal,
8111            _ctx: &LayoutContext,
8112        ) -> crate::widget::LayoutResponse {
8113            proposal.resolve(0.0, 0.0).into()
8114        }
8115
8116        fn place_children(
8117            &self,
8118            bounds: Rect,
8119            _proposal: SizeProposal,
8120            children: &mut [WidgetPlacement],
8121            _ctx: &LayoutContext,
8122        ) {
8123            let n = children.len().max(1) as f32;
8124            let w = bounds.width / n;
8125            for (i, child) in children.iter_mut().enumerate() {
8126                child.origin = Point::new(bounds.x + w * i as f32, bounds.y);
8127                child.size = teksilo_canvas::Size::new(w, bounds.height);
8128            }
8129        }
8130
8131        fn children(&self) -> Vec<WidgetId> {
8132            self.children.clone()
8133        }
8134    }
8135
8136    /// Everything a widget observes of a pointer interaction, as text, so two
8137    /// runs can be compared for exact equality rather than field by field.
8138    fn record(drive: impl FnOnce(&mut WidgetTree)) -> Vec<String> {
8139        let log: Rc<RefCell<Vec<String>>> = Rc::new(RefCell::new(Vec::new()));
8140
8141        let mut tree = WidgetTree::new();
8142        let pointer_log = log.clone();
8143        let hover_log = log.clone();
8144        tree.add(
8145            FillWidget::new()
8146                .on_pointer_event(move |event, _ctx| {
8147                    pointer_log.borrow_mut().push(format!("{event:?}"));
8148                    EventResponse::Ignored
8149                })
8150                .on_hover(move |entered, _ctx| {
8151                    hover_log.borrow_mut().push(format!("hover({entered})"));
8152                }),
8153        );
8154        tree.layout(SizeProposal::exact(100.0, 100.0));
8155
8156        drive(&mut tree);
8157        log.borrow().clone()
8158    }
8159
8160    /// The load-bearing compatibility claim of this package: lowering a mouse
8161    /// `PointerSample` produces the *same* `WidgetEvent` stream, in the same
8162    /// order, as writing the events out by hand. If this ever diverges, the
8163    /// door has started meaning something different from the events it lowers
8164    /// to.
8165    #[test]
8166    fn a_mouse_sample_reproduces_todays_event_stream() {
8167        let inside = Point::new(40.0, 40.0);
8168        let moved = Point::new(60.0, 55.0);
8169        let outside = Point::new(400.0, 400.0);
8170
8171        let legacy = record(|tree| {
8172            tree.dispatch_event(WidgetEvent::pointer_move(inside));
8173            tree.dispatch_event(WidgetEvent::pointer_down(
8174                inside,
8175                PointerButton::Primary,
8176                Modifiers::NONE,
8177            ));
8178            tree.dispatch_event(WidgetEvent::pointer_move(moved));
8179            tree.dispatch_event(WidgetEvent::pointer_up(
8180                moved,
8181                PointerButton::Primary,
8182                Modifiers::NONE,
8183            ));
8184            tree.dispatch_event(WidgetEvent::pointer_move(outside));
8185        });
8186
8187        let sampled = record(|tree| {
8188            let t = EventTime::ZERO;
8189            tree.dispatch_pointer(PointerSample::mouse(PointerPhase::Move, inside, t));
8190            tree.dispatch_pointer(
8191                PointerSample::mouse(PointerPhase::Down, inside, t)
8192                    .with_button(PointerButton::Primary),
8193            );
8194            tree.dispatch_pointer(PointerSample::mouse(PointerPhase::Move, moved, t));
8195            tree.dispatch_pointer(
8196                PointerSample::mouse(PointerPhase::Up, moved, t)
8197                    .with_button(PointerButton::Primary),
8198            );
8199            tree.dispatch_pointer(PointerSample::mouse(PointerPhase::Move, outside, t));
8200        });
8201
8202        assert_eq!(legacy, sampled);
8203        assert!(
8204            legacy.contains(&"hover(true)".to_string())
8205                && legacy.contains(&"hover(false)".to_string()),
8206            "the fixture must actually exercise enter and leave: {legacy:?}"
8207        );
8208    }
8209
8210    /// A press with no button — what a bare direct-pointer contact reports —
8211    /// still reads as the primary press, because that is what a tap has always
8212    /// been.
8213    #[test]
8214    fn a_buttonless_press_lowers_to_primary() {
8215        let events = record(|tree| {
8216            tree.dispatch_pointer(PointerSample::mouse(
8217                PointerPhase::Down,
8218                Point::new(20.0, 20.0),
8219                EventTime::ZERO,
8220            ));
8221        });
8222        assert!(
8223            events.iter().any(|e| e.contains("button: Primary")),
8224            "{events:?}"
8225        );
8226    }
8227
8228    /// A mouse press and release delivered as samples, as a test writes them
8229    /// by hand with timestamps of its own, form a tap: the sample door reaches
8230    /// the tap recognizer, not only raw `on_pointer_event` handlers. A port
8231    /// review reported the opposite for 0.16.0 and it did not reproduce; this
8232    /// pins it, with a stamp unrelated to the tree's clock on purpose.
8233    #[test]
8234    fn a_sampled_press_and_release_form_a_tap() {
8235        let taps = Rc::new(std::cell::Cell::new(0));
8236        let seen = taps.clone();
8237        let mut tree = WidgetTree::new();
8238        tree.add(FillWidget::new().on_tap(move |_event, _ctx| seen.set(seen.get() + 1)));
8239        tree.layout(SizeProposal::exact(100.0, 100.0));
8240
8241        let at = Point::new(50.0, 50.0);
8242        tree.dispatch_pointer(PointerSample::mouse(
8243            PointerPhase::Down,
8244            at,
8245            EventTime::from_millis(0),
8246        ));
8247        tree.dispatch_pointer(PointerSample::mouse(
8248            PointerPhase::Up,
8249            at,
8250            EventTime::from_millis(5),
8251        ));
8252
8253        assert_eq!(taps.get(), 1);
8254    }
8255
8256    // --- scroll routing --------------------------------------------------
8257
8258    /// Two leaves side by side across a 200-wide tree: `top` owns x < 100,
8259    /// `bottom` owns x >= 100.
8260    fn scroll_fixture() -> (WidgetTree, Rc<RefCell<Vec<&'static str>>>) {
8261        let hits: Rc<RefCell<Vec<&'static str>>> = Rc::new(RefCell::new(Vec::new()));
8262        let mut tree = WidgetTree::new();
8263
8264        let leading_hits = hits.clone();
8265        let trailing_hits = hits.clone();
8266        let leading = tree.add(FillWidget::new().on_scroll(move |_event, _ctx| {
8267            leading_hits.borrow_mut().push("leading");
8268            EventResponse::Handled
8269        }));
8270        let trailing = tree.add(FillWidget::new().on_scroll(move |_event, _ctx| {
8271            trailing_hits.borrow_mut().push("trailing");
8272            EventResponse::Handled
8273        }));
8274        tree.add(RowWidget {
8275            children: vec![leading, trailing],
8276        });
8277        tree.layout(SizeProposal::exact(200.0, 100.0));
8278        (tree, hits)
8279    }
8280
8281    fn notch() -> ScrollDelta {
8282        ScrollDelta::Lines { x: 0.0, y: -1.0 }
8283    }
8284
8285    /// The mouse path: a wheel notch carries no position, so it routes by
8286    /// hover exactly as it always has. This is the no-op claim.
8287    #[test]
8288    fn a_positionless_scroll_routes_by_hover() {
8289        let (mut tree, hits) = scroll_fixture();
8290
8291        tree.pointer_move(Point::new(150.0, 50.0)); // hover the trailing leaf
8292        tree.dispatch_event(WidgetEvent::scroll(notch(), Modifiers::NONE));
8293        assert_eq!(*hits.borrow(), vec!["trailing"]);
8294
8295        tree.pointer_move(Point::new(50.0, 50.0)); // hover the leading leaf
8296        tree.dispatch_scroll(ScrollSample::wheel(
8297            notch(),
8298            Modifiers::NONE,
8299            EventTime::ZERO,
8300        ));
8301        assert_eq!(*hits.borrow(), vec!["trailing", "leading"]);
8302    }
8303
8304    /// A positioned scroll routes by hit test, *against* the hover. This is
8305    /// the only thing that makes a synthesised touch pan routable at all: a
8306    /// contact never writes hover, so hover would send the pan to whatever the
8307    /// mouse last touched — or nowhere.
8308    #[test]
8309    fn a_positioned_scroll_routes_by_hit_test() {
8310        let (mut tree, hits) = scroll_fixture();
8311        tree.pointer_move(Point::new(150.0, 50.0)); // hover the TRAILING leaf
8312
8313        tree.dispatch_event(WidgetEvent::scroll_at(
8314            notch(),
8315            Modifiers::NONE,
8316            Point::new(50.0, 50.0), // …but scroll over the LEADING one
8317        ));
8318        assert_eq!(*hits.borrow(), vec!["leading"]);
8319
8320        tree.dispatch_scroll(
8321            ScrollSample::wheel(notch(), Modifiers::NONE, EventTime::ZERO)
8322                .at(Point::new(150.0, 50.0)),
8323        );
8324        assert_eq!(*hits.borrow(), vec!["leading", "trailing"]);
8325    }
8326
8327    /// With nothing hovered and nothing focused a positionless scroll goes
8328    /// nowhere — the pre-existing behaviour, pinned rather than left
8329    /// incidental.
8330    #[test]
8331    fn a_positionless_scroll_with_no_hover_goes_nowhere() {
8332        let (mut tree, hits) = scroll_fixture();
8333        tree.dispatch_event(WidgetEvent::scroll(notch(), Modifiers::NONE));
8334        assert!(hits.borrow().is_empty());
8335    }
8336
8337    // --- the per-dispatch snapshot ---------------------------------------
8338
8339    /// A handler can ask which pointer it is serving, and what phase and
8340    /// source a scroll had.
8341    #[test]
8342    fn a_handler_sees_the_sample_it_is_serving() {
8343        let seen: Rc<RefCell<Vec<(ScrollPhase, ScrollSource, Option<Point>)>>> =
8344            Rc::new(RefCell::new(Vec::new()));
8345        let sink = seen.clone();
8346
8347        let mut tree = WidgetTree::new();
8348        // A `ScrollSource::TouchPan` sample is delivered along the pan
8349        // claimants and nowhere else (see `widget_tree::pan_arbiter`), so the
8350        // fixture has to be a pan surface for the sample below to reach it at
8351        // all. Nothing about what this test *asserts* changes — only that the
8352        // widget it asserts against is now the kind of widget a touch pan is
8353        // addressed to.
8354        tree.add(
8355            FillWidget::new()
8356                .scroll_container(crate::pointer::touch_action::PanAxes::BOTH)
8357                .on_scroll(move |_event, ctx| {
8358                    sink.borrow_mut().push((
8359                        ctx.scroll_phase(),
8360                        ctx.scroll_source(),
8361                        ctx.pointer_position(),
8362                    ));
8363                    EventResponse::Handled
8364                }),
8365        );
8366        tree.layout(SizeProposal::exact(100.0, 100.0));
8367
8368        tree.dispatch_scroll(ScrollSample {
8369            delta: notch(),
8370            position: Some(Point::new(50.0, 50.0)),
8371            phase: ScrollPhase::Momentum,
8372            source: ScrollSource::TouchPan,
8373            pointer: PointerInfo::mouse(EventTime::from_millis(12)),
8374            modifiers: Modifiers::NONE,
8375        });
8376
8377        assert_eq!(
8378            *seen.borrow(),
8379            vec![(
8380                ScrollPhase::Momentum,
8381                ScrollSource::TouchPan,
8382                Some(Point::new(50.0, 50.0))
8383            )]
8384        );
8385    }
8386
8387    /// Outside a pointer dispatch a handler sees the default mouse — the same
8388    /// answer every such handler got before pointers were distinguishable.
8389    #[test]
8390    fn a_legacy_event_reports_the_mouse_at_the_epoch() {
8391        let seen: Rc<RefCell<Option<(PointerId, ScrollPhase)>>> = Rc::new(RefCell::new(None));
8392        let sink = seen.clone();
8393
8394        let mut tree = WidgetTree::new();
8395        tree.add(FillWidget::new().on_pointer_event(move |_event, ctx| {
8396            *sink.borrow_mut() = Some((ctx.pointer().id, ctx.scroll_phase()));
8397            EventResponse::Ignored
8398        }));
8399        tree.layout(SizeProposal::exact(100.0, 100.0));
8400        tree.dispatch_event(WidgetEvent::pointer_move(Point::new(50.0, 50.0)));
8401
8402        assert_eq!(
8403            *seen.borrow(),
8404            Some((PointerId::MOUSE, ScrollPhase::Discrete))
8405        );
8406    }
8407
8408    /// The snapshot is saved and restored around a dispatch, so a nested one
8409    /// (a synthetic click, a scroll-into-view walk) does not strand the outer
8410    /// sample's view of the world.
8411    #[test]
8412    fn the_snapshot_is_restored_after_a_dispatch() {
8413        let mut tree = WidgetTree::new();
8414        tree.add(FillWidget::new());
8415        tree.layout(SizeProposal::exact(100.0, 100.0));
8416
8417        let before = tree.current_input.clone();
8418        tree.dispatch_scroll(
8419            ScrollSample::wheel(notch(), Modifiers::NONE, EventTime::ZERO)
8420                .at(Point::new(10.0, 10.0)),
8421        );
8422        assert_eq!(tree.current_input, before);
8423    }
8424}
8425
8426#[cfg(test)]
8427mod press_and_focus_tests {
8428    //! The framework press, focus-on-release for direct pointers, and the one
8429    //! `focus_visible` signal — driven through the real ingress doors against
8430    //! real trees.
8431
8432    use std::cell::{Cell, RefCell};
8433    use std::rc::Rc;
8434    use teksilo_canvas::{Point, SizeProposal};
8435
8436    use crate::WidgetId;
8437    use crate::event::{EventResponse, Key, Modifiers, PointerButton, WidgetEvent};
8438    use crate::focus::FocusOrigin;
8439    use crate::pointer::clock::ManualClock;
8440    use crate::pointer::touch_action::PanClaim;
8441    use crate::pointer::{
8442        BackendDeviceKey, EventTime, PointerId, PointerIdAllocator, PointerInfo, PointerPhase,
8443        PointerSample,
8444    };
8445    use crate::test_widgets::{FillWidget, StackWidget};
8446    use crate::widget_builder::WidgetBuilder;
8447    use crate::widget_tree::WidgetTree;
8448
8449    // -----------------------------------------------------------------
8450    // Fixtures
8451    // -----------------------------------------------------------------
8452
8453    /// A fresh contact identity, minted through the real allocator.
8454    fn contact_id() -> PointerId {
8455        use std::sync::atomic::{AtomicU64, Ordering};
8456        static NEXT: AtomicU64 = AtomicU64::new(1);
8457        PointerIdAllocator::global().begin(
8458            BackendDeviceKey::new(0x0B11),
8459            NEXT.fetch_add(1, Ordering::Relaxed),
8460        )
8461    }
8462
8463    fn contact(id: PointerId, phase: PointerPhase, at: Point, t: EventTime) -> PointerSample {
8464        PointerSample {
8465            pointer: PointerInfo::touch(id, t),
8466            phase,
8467            position: at,
8468            button: None,
8469            modifiers: Modifiers::NONE,
8470            coalesced: Vec::new(),
8471        }
8472    }
8473
8474    /// A tree on a clock the test drives, so every deadline in these tests is
8475    /// virtual.
8476    fn tree_on_a_clock() -> (WidgetTree, Rc<ManualClock>) {
8477        let mut tree = WidgetTree::new();
8478        let clock = Rc::new(ManualClock::new(EventTime::ZERO));
8479        tree.set_input_clock(clock.clone());
8480        (tree, clock)
8481    }
8482
8483    /// A tappable leaf with a framework press signal installed on it, plus the
8484    /// signal itself.
8485    ///
8486    /// `on_tap` is what gives the node a gesture arena, which is what makes it
8487    /// the press owner — the same thing a `Button` gets from its own tap
8488    /// handler.
8489    fn tappable(tree: &mut WidgetTree) -> (WidgetId, crate::signal::Signal<bool>) {
8490        let id = tree.add(FillWidget::new().focusable().on_tap(|_e, _c| {}));
8491        let signal = tree.pressed_signal(id);
8492        (id, signal)
8493    }
8494
8495    // -----------------------------------------------------------------
8496    // The enum
8497    // -----------------------------------------------------------------
8498
8499    /// `FocusOrigin` now names the device behind a pointer focus, and the two
8500    /// accessors that replaced `== FocusOrigin::Pointer` answer for every arm.
8501    #[test]
8502    fn a_pointer_origin_names_its_device() {
8503        use teksilo_tokens::{PenKind, PointerKind};
8504
8505        assert!(FocusOrigin::Pointer(PointerKind::Touch).is_pointer());
8506        assert!(FocusOrigin::Pointer(PointerKind::Pen(PenKind::Pen)).is_pointer());
8507        assert!(FocusOrigin::POINTER.is_pointer());
8508        assert!(!FocusOrigin::Keyboard.is_pointer());
8509        assert!(!FocusOrigin::Programmatic.is_pointer());
8510        assert!(!FocusOrigin::Accessibility.is_pointer());
8511
8512        assert_eq!(
8513            FocusOrigin::Pointer(PointerKind::Touch).pointer_kind(),
8514            Some(PointerKind::Touch),
8515        );
8516        assert_eq!(FocusOrigin::Keyboard.pointer_kind(), None);
8517        assert_eq!(
8518            FocusOrigin::POINTER.pointer_kind(),
8519            Some(PointerKind::Unknown),
8520            "a widget deriving its own origin says so rather than naming a device it never saw",
8521        );
8522    }
8523
8524    /// The `:focus-visible` verdict, per origin. `Programmatic` abstains — a
8525    /// scripted focus declares no modality, so the ring stays where the user's
8526    /// last real interaction left it.
8527    #[test]
8528    fn only_a_real_navigation_declares_a_modality() {
8529        use teksilo_tokens::PointerKind;
8530
8531        assert_eq!(FocusOrigin::Keyboard.focus_visible(), Some(true));
8532        assert_eq!(FocusOrigin::Accessibility.focus_visible(), Some(true));
8533        assert_eq!(
8534            FocusOrigin::Pointer(PointerKind::Touch).focus_visible(),
8535            Some(false),
8536        );
8537        assert_eq!(FocusOrigin::Programmatic.focus_visible(), None);
8538    }
8539
8540    /// The three Tier-3 configs still carry `Signal<Option<FocusOrigin>>`, and
8541    /// a style reading one still gets what it was written against.
8542    #[test]
8543    fn the_tier_three_configs_are_unchanged() {
8544        let origin: crate::signal::Signal<Option<FocusOrigin>> =
8545            crate::signal::Signal::new(Some(FocusOrigin::Keyboard));
8546        let slider: crate::signal::Signal<Option<FocusOrigin>> = origin.clone();
8547        let splitter: crate::signal::Signal<Option<FocusOrigin>> = origin.clone();
8548        let segmented: crate::signal::Signal<Option<FocusOrigin>> = origin.clone();
8549        for field in [slider, splitter, segmented] {
8550            assert_eq!(field.get(), Some(FocusOrigin::Keyboard));
8551        }
8552        origin.set(Some(FocusOrigin::POINTER));
8553        assert_ne!(
8554            origin.get(),
8555            Some(FocusOrigin::Keyboard),
8556            "the `== Some(Keyboard)` test every consumer makes still discriminates",
8557        );
8558    }
8559
8560    // -----------------------------------------------------------------
8561    // focus-visible per kind
8562    // -----------------------------------------------------------------
8563
8564    /// Keyboard focus, then a touch tap, leaves no ring.
8565    ///
8566    /// The behaviour predates this package; what is new is that the focus the
8567    /// tap installs lands on the **release**, so this pins that moving the
8568    /// assignment did not leave a keyboard ring standing over a control the
8569    /// finger just took.
8570    #[test]
8571    fn a_touch_tap_after_keyboard_focus_leaves_no_ring() {
8572        let (mut tree, _clock) = tree_on_a_clock();
8573        let a = tree.add(FillWidget::new().focusable());
8574        let b = tree.add(FillWidget::new().focusable());
8575        let root = tree.add(SideBySide {
8576            children: vec![a, b],
8577        });
8578        tree.layout(SizeProposal::exact(200.0, 100.0));
8579        let _ = root;
8580
8581        let visible = tree.focus_visible_signal();
8582        tree.press_key(Key::Tab, Modifiers::NONE);
8583        assert_eq!(tree.focused(), Some(a));
8584        assert!(visible.get(), "keyboard navigation reveals the ring");
8585
8586        let id = contact_id();
8587        let at = tree.bounds(b).center();
8588        tree.dispatch_pointer(contact(id, PointerPhase::Down, at, EventTime::ZERO));
8589        tree.dispatch_pointer(contact(
8590            id,
8591            PointerPhase::Up,
8592            at,
8593            EventTime::from_millis(30),
8594        ));
8595
8596        assert_eq!(tree.focused(), Some(b), "the release moved focus");
8597        assert!(!visible.get(), "and the ring did not come with it");
8598        assert_eq!(
8599            tree.focus_origin(),
8600            Some(FocusOrigin::Pointer(teksilo_tokens::PointerKind::Touch)),
8601        );
8602    }
8603
8604    /// An assistive `Action::Focus` reveals the ring. The user is navigating —
8605    /// they are simply not doing it with a key — and this used to route through
8606    /// `Programmatic`, which declares nothing and left a screen-reader user
8607    /// with an invisible focus after any click.
8608    #[test]
8609    fn an_assistive_focus_reveals_the_ring() {
8610        let mut tree = WidgetTree::new();
8611        let a = tree.add(FillWidget::new().focusable());
8612        let b = tree.add(FillWidget::new().focusable());
8613        let root = tree.add(SideBySide {
8614            children: vec![a, b],
8615        });
8616        tree.layout(SizeProposal::exact(200.0, 50.0));
8617        let _ = root;
8618        let visible = tree.focus_visible_signal();
8619
8620        tree.click(a);
8621        assert_eq!(tree.focused(), Some(a));
8622        assert!(!visible.get(), "the click hid it");
8623
8624        tree.dispatch_event(WidgetEvent::AccessAction {
8625            target: Some(b),
8626            action: accesskit::Action::Focus,
8627            target_node: crate::accessibility::widget_id_to_node_id(b),
8628            data: None,
8629        });
8630        assert_eq!(tree.focused(), Some(b));
8631        assert!(visible.get(), "an assistive move is a navigation");
8632        assert_eq!(tree.focus_origin(), Some(FocusOrigin::Accessibility));
8633    }
8634
8635    /// A view-like owner of two items it can point at, inside a focusable
8636    /// ancestor whose handler takes any `Focus` (a card selecting itself), the
8637    /// two beside another focusable control.
8638    struct ItemFocusFixture {
8639        tree: WidgetTree,
8640        other: WidgetId,
8641        /// A container around the owner that takes no focus.
8642        group: WidgetId,
8643        owner: WidgetId,
8644        /// The owner refuses this one, as a calendar refuses a day the arrows
8645        /// cannot reach.
8646        refused: WidgetId,
8647        taken: WidgetId,
8648        /// A plain label, advertising no `Focus`.
8649        label: WidgetId,
8650        cursor: Rc<Cell<Option<accesskit::NodeId>>>,
8651        catch_all: Rc<Cell<u32>>,
8652    }
8653
8654    fn item_focus_fixture() -> ItemFocusFixture {
8655        let advertises_focus = |b: &mut crate::accessibility::AccessNodeBuilder| {
8656            b.add_action(accesskit::Action::Focus)
8657        };
8658        let mut tree = WidgetTree::new();
8659        let other = tree.add(FillWidget::new().focusable());
8660        let refused = tree.add(FillWidget::new().access_customize(advertises_focus));
8661        let taken = tree.add(FillWidget::new().access_customize(advertises_focus));
8662        let label = tree.add(FillWidget::new());
8663        let cursor: Rc<Cell<Option<accesskit::NodeId>>> = Rc::new(Cell::new(None));
8664        let owner_slot: Rc<Cell<Option<WidgetId>>> = Rc::new(Cell::new(None));
8665        let taken_node = crate::accessibility::widget_id_to_node_id(taken);
8666        let owner = tree.add(
8667            SideBySide {
8668                children: vec![refused, taken],
8669            }
8670            .focusable(true)
8671            .on_access_action_request({
8672                let cursor = cursor.clone();
8673                let owner_slot = owner_slot.clone();
8674                move |action, node, _data, ctx| {
8675                    if action != accesskit::Action::Focus || node != taken_node {
8676                        return EventResponse::Ignored;
8677                    }
8678                    cursor.set(Some(node));
8679                    if let Some(owner) = owner_slot.get() {
8680                        ctx.request_focus(owner);
8681                    }
8682                    EventResponse::Handled
8683                }
8684            }),
8685        );
8686        owner_slot.set(Some(owner));
8687        // A container that is not focusable, as a `GroupBox` is.
8688        let group = tree.add(SideBySide {
8689            children: vec![owner],
8690        });
8691        let catch_all = Rc::new(Cell::new(0));
8692        let card = tree.add(
8693            SideBySide {
8694                children: vec![group, label],
8695            }
8696            .focusable(true)
8697            .on_access_action({
8698                let catch_all = catch_all.clone();
8699                move |action, _ctx| {
8700                    if action != accesskit::Action::Focus {
8701                        return EventResponse::Ignored;
8702                    }
8703                    catch_all.set(catch_all.get() + 1);
8704                    EventResponse::Handled
8705                }
8706            }),
8707        );
8708        tree.add(SideBySide {
8709            children: vec![other, card],
8710        });
8711        tree.layout(SizeProposal::exact(400.0, 50.0));
8712        ItemFocusFixture {
8713            tree,
8714            other,
8715            group,
8716            owner,
8717            refused,
8718            taken,
8719            label,
8720            cursor,
8721            catch_all,
8722        }
8723    }
8724
8725    fn assistive_focus(tree: &mut WidgetTree, id: WidgetId) -> bool {
8726        tree.dispatch_access_action(
8727            crate::accessibility::widget_id_to_node_id(id),
8728            accesskit::Action::Focus,
8729            None,
8730            &mut crate::window::NoopWindowOps,
8731        )
8732    }
8733
8734    /// An assistive `Focus` on an item a widget points at through its
8735    /// `active_descendant` goes to that widget, which moves its cursor to
8736    /// the item and takes keyboard focus itself, as an arrow key would. The
8737    /// item takes no keys: focusing its own node left the widget naming no
8738    /// descendant and the keys going nowhere useful. The ancestor above the
8739    /// owner, which takes any `Focus`, is not asked.
8740    #[test]
8741    fn an_assistive_focus_on_an_item_goes_to_the_widget_that_points_at_it() {
8742        let mut f = item_focus_fixture();
8743        let visible = f.tree.focus_visible_signal();
8744        f.tree.click(f.other);
8745        assert!(!visible.get());
8746
8747        assert!(
8748            assistive_focus(&mut f.tree, f.taken),
8749            "the widget that points at the item took it"
8750        );
8751        let item = crate::accessibility::widget_id_to_node_id(f.taken);
8752        assert_eq!(f.cursor.get(), Some(item), "its cursor moved to the item");
8753        assert_eq!(
8754            f.tree.focused(),
8755            Some(f.owner),
8756            "the keyboard is on the widget, not on the item"
8757        );
8758        assert!(visible.get(), "an assistive move is a navigation");
8759        assert_eq!(f.tree.focus_origin(), Some(FocusOrigin::Accessibility));
8760        assert_eq!(
8761            f.catch_all.get(),
8762            0,
8763            "no ancestor above the owner was asked"
8764        );
8765    }
8766
8767    /// An item its owner refuses gets no focus: the keyboard is not parked on
8768    /// a node that takes no keys, no ancestor above the owner takes it in its
8769    /// place, and the action is reported unhandled.
8770    #[test]
8771    fn an_item_its_owner_refuses_takes_no_assistive_focus() {
8772        let mut f = item_focus_fixture();
8773        f.tree.click(f.other);
8774        assert!(!assistive_focus(&mut f.tree, f.refused));
8775        assert_eq!(f.tree.focused(), Some(f.other), "focus did not move");
8776        assert_eq!(f.cursor.get(), None);
8777        assert_eq!(f.catch_all.get(), 0);
8778    }
8779
8780    /// A node that advertises no `Focus` (a label) is offered to no one and
8781    /// reports the action unhandled, whatever an ancestor's handler takes.
8782    #[test]
8783    fn a_node_that_offers_no_focus_takes_no_assistive_focus() {
8784        let mut f = item_focus_fixture();
8785        f.tree.click(f.other);
8786        assert!(!assistive_focus(&mut f.tree, f.label));
8787        assert_eq!(f.tree.focused(), Some(f.other));
8788        assert_eq!(f.catch_all.get(), 0);
8789    }
8790
8791    /// A greyed item (a menu row the arrows still highlight) is still offered
8792    /// to its owner; an item in a disabled container is offered to no one,
8793    /// not to an ancestor above the container either.
8794    #[test]
8795    fn a_greyed_item_reaches_its_owner_and_a_disabled_container_takes_nothing() {
8796        let mut f = item_focus_fixture();
8797        let item_enabled = crate::signal::Signal::new(false);
8798        f.tree.enabled_when(f.taken, item_enabled.clone());
8799        f.tree.layout(SizeProposal::exact(400.0, 50.0));
8800        f.tree.click(f.other);
8801        assert!(assistive_focus(&mut f.tree, f.taken), "a greyed item");
8802        assert_eq!(f.tree.focused(), Some(f.owner));
8803
8804        let mut f = item_focus_fixture();
8805        f.tree
8806            .enabled_when(f.group, crate::signal::Signal::new(false));
8807        f.tree.layout(SizeProposal::exact(400.0, 50.0));
8808        f.tree.click(f.other);
8809        assert!(
8810            !assistive_focus(&mut f.tree, f.taken),
8811            "a disabled container"
8812        );
8813        assert_eq!(f.tree.focused(), Some(f.other));
8814        assert_eq!(f.cursor.get(), None);
8815        assert_eq!(f.catch_all.get(), 0);
8816    }
8817
8818    /// A composite with a Tab stop inside (a `DateEdit` root that advertises
8819    /// `Focus`) is no item: the focus lands on its stop, and the ancestor that
8820    /// takes any `Focus` is not asked.
8821    #[test]
8822    fn a_composite_in_a_catch_all_ancestor_gets_its_stop() {
8823        let mut tree = WidgetTree::new();
8824        let other = tree.add(FillWidget::new().focusable());
8825        let leaf = tree.add(FillWidget::new().focusable());
8826        let composite = tree.add(
8827            SideBySide {
8828                children: vec![leaf],
8829            }
8830            .access_customize(|b| b.add_action(accesskit::Action::Focus)),
8831        );
8832        let catch_all = Rc::new(Cell::new(0));
8833        let card = tree.add(
8834            SideBySide {
8835                children: vec![composite],
8836            }
8837            .focusable(true)
8838            .on_access_action({
8839                let catch_all = catch_all.clone();
8840                move |action, _ctx| {
8841                    if action == accesskit::Action::Focus {
8842                        catch_all.set(catch_all.get() + 1);
8843                        return EventResponse::Handled;
8844                    }
8845                    EventResponse::Ignored
8846                }
8847            }),
8848        );
8849        tree.add(SideBySide {
8850            children: vec![other, card],
8851        });
8852        tree.layout(SizeProposal::exact(400.0, 50.0));
8853        tree.click(other);
8854        assert!(assistive_focus(&mut tree, composite));
8855        assert_eq!(tree.focused(), Some(leaf), "the keyboard is on its stop");
8856        assert_eq!(catch_all.get(), 0);
8857    }
8858
8859    /// A focusable widget that publishes one synthetic child, advertising
8860    /// `Focus` or not.
8861    #[derive(Debug)]
8862    struct SyntheticOwner {
8863        advertises: bool,
8864    }
8865
8866    impl crate::widget::Widget for SyntheticOwner {
8867        fn layout_response(
8868            &self,
8869            proposal: SizeProposal,
8870            _ctx: &crate::widget::LayoutContext,
8871        ) -> crate::widget::LayoutResponse {
8872            proposal.resolve(0.0, 0.0).into()
8873        }
8874
8875        fn accessibility(&self, builder: &mut crate::accessibility::AccessNodeBuilder) {
8876            let advertises = self.advertises;
8877            builder.push_scene_child(1, crate::accessibility::SyntheticKind::ChartMark, |child| {
8878                child.set_role(accesskit::Role::GraphicsObject);
8879                if advertises {
8880                    child.add_action(accesskit::Action::Focus);
8881                }
8882            });
8883        }
8884    }
8885
8886    /// A focusable ancestor that takes any `Focus`, counting them.
8887    fn catch_all_card(tree: &mut WidgetTree, child: WidgetId) -> (WidgetId, Rc<Cell<u32>>) {
8888        let catch_all = Rc::new(Cell::new(0));
8889        let card = tree.add(
8890            SideBySide {
8891                children: vec![child],
8892            }
8893            .focusable(true)
8894            .on_access_action({
8895                let catch_all = catch_all.clone();
8896                move |action, _ctx| {
8897                    if action == accesskit::Action::Focus {
8898                        catch_all.set(catch_all.get() + 1);
8899                        return EventResponse::Handled;
8900                    }
8901                    EventResponse::Ignored
8902                }
8903            }),
8904        );
8905        (card, catch_all)
8906    }
8907
8908    /// A disabled owner of synthetic items, or a disabled composite, is no
8909    /// greyed item: a `Focus` aimed at it is offered to no ancestor, and
8910    /// nothing takes it.
8911    #[test]
8912    fn a_disabled_synthetic_owner_or_composite_offers_nothing_upward() {
8913        let mut tree = WidgetTree::new();
8914        let other = tree.add(FillWidget::new().focusable());
8915        let owner = tree.add(SyntheticOwner { advertises: true }.focusable(true));
8916        let leaf = tree.add(FillWidget::new().focusable());
8917        let composite = tree.add(
8918            SideBySide {
8919                children: vec![leaf],
8920            }
8921            .access_customize(|b| b.add_action(accesskit::Action::Focus)),
8922        );
8923        let group = tree.add(SideBySide {
8924            children: vec![owner, composite],
8925        });
8926        let (card, catch_all) = catch_all_card(&mut tree, group);
8927        tree.add(SideBySide {
8928            children: vec![other, card],
8929        });
8930        tree.layout(SizeProposal::exact(400.0, 50.0));
8931        let _ = tree.sync_accessibility();
8932        tree.enabled_when(owner, crate::signal::Signal::new(false));
8933        tree.enabled_when(composite, crate::signal::Signal::new(false));
8934        tree.layout(SizeProposal::exact(400.0, 50.0));
8935        tree.click(other);
8936
8937        let mark = crate::accessibility::synthetic_node_id(
8938            owner,
8939            1,
8940            crate::accessibility::SyntheticKind::ChartMark,
8941        );
8942        let handled = tree.dispatch_access_action(
8943            mark,
8944            accesskit::Action::Focus,
8945            None,
8946            &mut crate::window::NoopWindowOps,
8947        );
8948        assert!(!handled, "a disabled owner's item");
8949        assert!(
8950            !assistive_focus(&mut tree, composite),
8951            "a disabled composite"
8952        );
8953        assert_eq!(tree.focused(), Some(other));
8954        assert_eq!(catch_all.get(), 0, "no ancestor was asked");
8955    }
8956
8957    /// A synthetic node that advertises no `Focus` is offered to no one; the
8958    /// framework focuses its owner, as it always did.
8959    #[test]
8960    fn a_synthetic_node_that_offers_no_focus_is_offered_to_no_one() {
8961        let mut tree = WidgetTree::new();
8962        let other = tree.add(FillWidget::new().focusable());
8963        // Not focusable itself, so the offer would climb to the card.
8964        let owner = tree.add(SyntheticOwner { advertises: false });
8965        let (card, catch_all) = catch_all_card(&mut tree, owner);
8966        tree.add(SideBySide {
8967            children: vec![other, card],
8968        });
8969        tree.layout(SizeProposal::exact(400.0, 50.0));
8970        let _ = tree.sync_accessibility();
8971        tree.click(other);
8972        let mark = crate::accessibility::synthetic_node_id(
8973            owner,
8974            1,
8975            crate::accessibility::SyntheticKind::ChartMark,
8976        );
8977        let _ = tree.dispatch_access_action(
8978            mark,
8979            accesskit::Action::Focus,
8980            None,
8981            &mut crate::window::NoopWindowOps,
8982        );
8983        assert_eq!(catch_all.get(), 0, "no handler was asked");
8984    }
8985
8986    /// A handler that answers `Focus` and moves nothing, with the keyboard on
8987    /// another control, is no success: the action is reported unhandled and
8988    /// the mouse-focused control gets no ring.
8989    #[test]
8990    fn an_answer_that_moves_no_focus_is_no_success() {
8991        let mut tree = WidgetTree::new();
8992        let other = tree.add(FillWidget::new().focusable());
8993        let item = tree
8994            .add(FillWidget::new().access_customize(|b| b.add_action(accesskit::Action::Focus)));
8995        let owner = tree.add(
8996            SideBySide {
8997                children: vec![item],
8998            }
8999            .focusable(true)
9000            .on_access_action(|action, _ctx| {
9001                if action == accesskit::Action::Focus {
9002                    EventResponse::Handled
9003                } else {
9004                    EventResponse::Ignored
9005                }
9006            }),
9007        );
9008        tree.add(SideBySide {
9009            children: vec![other, owner],
9010        });
9011        tree.layout(SizeProposal::exact(400.0, 50.0));
9012        let visible = tree.focus_visible_signal();
9013        tree.click(other);
9014        assert!(!assistive_focus(&mut tree, item), "reported unhandled");
9015        assert_eq!(tree.focused(), Some(other));
9016        assert!(!visible.get(), "no ring on the mouse-focused control");
9017    }
9018
9019    /// A programmatic focus abstains: it declares no modality, so the ring
9020    /// stays exactly where the last real interaction left it. This is what
9021    /// `Button` / `Checkbox`'s pre-existing focus-ring tests pin, and what
9022    /// browsers do for `element.focus()`.
9023    #[test]
9024    fn a_programmatic_focus_leaves_the_modality_alone() {
9025        let mut tree = WidgetTree::new();
9026        let a = tree.add(FillWidget::new().focusable());
9027        let b = tree.add(FillWidget::new().focusable());
9028        let root = tree.add(SideBySide {
9029            children: vec![a, b],
9030        });
9031        tree.layout(SizeProposal::exact(200.0, 100.0));
9032        let _ = root;
9033        let visible = tree.focus_visible_signal();
9034
9035        tree.press_key(Key::Tab, Modifiers::NONE);
9036        assert_eq!(tree.focused(), Some(a));
9037        assert!(visible.get());
9038        tree.focus(b);
9039        assert!(
9040            visible.get(),
9041            "a scripted focus does not hide a keyboard ring"
9042        );
9043
9044        tree.click(a);
9045        assert!(!visible.get());
9046        tree.focus(b);
9047        assert!(
9048            !visible.get(),
9049            "and does not reveal one after a click either",
9050        );
9051    }
9052
9053    // -----------------------------------------------------------------
9054    // Activation on release
9055    // -----------------------------------------------------------------
9056
9057    /// A mouse focuses on press, exactly as it always has.
9058    #[test]
9059    fn a_mouse_still_focuses_on_press() {
9060        let mut tree = WidgetTree::new();
9061        let w = tree.add(FillWidget::new().focusable());
9062        tree.layout(SizeProposal::exact(100.0, 50.0));
9063        let center = tree.bounds(w).center();
9064
9065        tree.dispatch_event(WidgetEvent::pointer_down(
9066            center,
9067            PointerButton::Primary,
9068            Modifiers::NONE,
9069        ));
9070        assert_eq!(
9071            tree.focused(),
9072            Some(w),
9073            "focus lands on the press for an indirect pointer",
9074        );
9075    }
9076
9077    /// A finger's focus waits for the release.
9078    #[test]
9079    fn a_finger_focuses_on_release() {
9080        let (mut tree, _clock) = tree_on_a_clock();
9081        let w = tree.add(FillWidget::new().focusable());
9082        tree.layout(SizeProposal::exact(100.0, 50.0));
9083        let center = tree.bounds(w).center();
9084
9085        let id = contact_id();
9086        tree.dispatch_pointer(contact(id, PointerPhase::Down, center, EventTime::ZERO));
9087        assert_eq!(
9088            tree.focused(),
9089            None,
9090            "a finger that has only landed has chosen nothing yet",
9091        );
9092
9093        tree.dispatch_pointer(contact(
9094            id,
9095            PointerPhase::Up,
9096            center,
9097            EventTime::from_millis(40),
9098        ));
9099        assert_eq!(tree.focused(), Some(w));
9100        assert_eq!(
9101            tree.focus_origin().and_then(FocusOrigin::pointer_kind),
9102            Some(teksilo_tokens::PointerKind::Touch),
9103            "the origin names the device that delivered it",
9104        );
9105    }
9106
9107    /// …and only when the release lands back on the same focusable. A finger
9108    /// that presses one control, slides onto its neighbour and lifts has
9109    /// activated nothing and must move focus nowhere.
9110    #[test]
9111    fn a_release_on_a_different_focusable_moves_no_focus() {
9112        let (mut tree, _clock) = tree_on_a_clock();
9113        let a = tree.add(FillWidget::new().focusable());
9114        let b = tree.add(FillWidget::new().focusable());
9115        let root = tree.add(SideBySide {
9116            children: vec![a, b],
9117        });
9118        tree.layout(SizeProposal::exact(200.0, 50.0));
9119        let _ = root;
9120
9121        let on_a = tree.bounds(a).center();
9122        let on_b = tree.bounds(b).center();
9123        let id = contact_id();
9124        tree.dispatch_pointer(contact(id, PointerPhase::Down, on_a, EventTime::ZERO));
9125        tree.dispatch_pointer(contact(
9126            id,
9127            PointerPhase::Move,
9128            on_b,
9129            EventTime::from_millis(20),
9130        ));
9131        tree.dispatch_pointer(contact(
9132            id,
9133            PointerPhase::Up,
9134            on_b,
9135            EventTime::from_millis(40),
9136        ));
9137
9138        assert_eq!(
9139            tree.focused(),
9140            None,
9141            "the guard is `the release landed on the same focusable as the press`",
9142        );
9143    }
9144
9145    // -----------------------------------------------------------------
9146    // The press visual
9147    // -----------------------------------------------------------------
9148
9149    /// A mouse press lights the visual at once and the release clears it —
9150    /// the pre-touch rule, and no press-feedback delay anywhere near it.
9151    #[test]
9152    fn a_mouse_press_visual_is_unchanged() {
9153        let mut tree = WidgetTree::new();
9154        let (w, pressed) = tappable(&mut tree);
9155        tree.layout(SizeProposal::exact(100.0, 50.0));
9156        let center = tree.bounds(w).center();
9157
9158        assert!(!pressed.get(), "not pressed at rest");
9159        tree.dispatch_event(WidgetEvent::pointer_down(
9160            center,
9161            PointerButton::Primary,
9162            Modifiers::NONE,
9163        ));
9164        assert!(pressed.get(), "an indirect pointer lights up on the press");
9165        assert!(
9166            !tree.press_pending(w),
9167            "and never waits: a mouse opens no pan session, so there is no \
9168             ambiguity to wait out",
9169        );
9170        assert_eq!(tree.pressed_by(w), Some(PointerId::MOUSE));
9171
9172        tree.dispatch_event(WidgetEvent::pointer_up(
9173            center,
9174            PointerButton::Primary,
9175            Modifiers::NONE,
9176        ));
9177        assert!(!pressed.get(), "the release clears it");
9178        assert_eq!(tree.pressed_by(w), None);
9179    }
9180
9181    /// A slide off the target clears the visual, and sliding back on restores
9182    /// it. WCAG 2.2 SC 2.5.2's abort gesture, and reversible right up to the
9183    /// release.
9184    #[test]
9185    fn a_slide_off_clears_the_visual_and_re_entry_restores_it() {
9186        let (mut tree, _clock) = tree_on_a_clock();
9187        let (w, pressed) = tappable(&mut tree);
9188        tree.layout(SizeProposal::exact(100.0, 200.0));
9189        let inside = tree.bounds(w).center();
9190        let outside = Point::new(inside.x, inside.y + 400.0);
9191
9192        let id = contact_id();
9193        tree.dispatch_pointer(contact(id, PointerPhase::Down, inside, EventTime::ZERO));
9194        assert!(
9195            pressed.get(),
9196            "nothing here claims a pan, so no delay applies"
9197        );
9198
9199        tree.dispatch_pointer(contact(
9200            id,
9201            PointerPhase::Move,
9202            outside,
9203            EventTime::from_millis(20),
9204        ));
9205        assert!(!pressed.get(), "the press has left its target");
9206        assert!(!tree.press_is_inside(w));
9207        assert_eq!(
9208            tree.pressed_by(w),
9209            Some(id),
9210            "the contact still holds the press — it is the *visual* that is off",
9211        );
9212
9213        tree.dispatch_pointer(contact(
9214            id,
9215            PointerPhase::Move,
9216            inside,
9217            EventTime::from_millis(40),
9218        ));
9219        assert!(pressed.get(), "sliding back on restores it");
9220
9221        tree.dispatch_pointer(contact(
9222            id,
9223            PointerPhase::Up,
9224            inside,
9225            EventTime::from_millis(60),
9226        ));
9227        assert!(!pressed.get());
9228    }
9229
9230    /// A second contact cannot clear the first's visual. Its own release
9231    /// removes only the press it owns.
9232    #[test]
9233    fn a_second_contact_cannot_clear_the_first_visual() {
9234        let (mut tree, _clock) = tree_on_a_clock();
9235        let (w, pressed) = tappable(&mut tree);
9236        tree.layout(SizeProposal::exact(100.0, 50.0));
9237        let bounds = tree.bounds(w);
9238        let first_at = Point::new(bounds.x + 20.0, bounds.y + 25.0);
9239        let second_at = Point::new(bounds.x + 70.0, bounds.y + 25.0);
9240
9241        let first = contact_id();
9242        let second = contact_id();
9243        tree.dispatch_pointer(contact(
9244            first,
9245            PointerPhase::Down,
9246            first_at,
9247            EventTime::ZERO,
9248        ));
9249        assert!(pressed.get());
9250        assert_eq!(tree.pressed_by(w), Some(first));
9251
9252        tree.dispatch_pointer(contact(
9253            second,
9254            PointerPhase::Down,
9255            second_at,
9256            EventTime::from_millis(10),
9257        ));
9258        assert_eq!(
9259            tree.pressed_by(w),
9260            Some(first),
9261            "under `MultiContact::First` the second contact is terminated before \
9262             it reaches the arena at all",
9263        );
9264
9265        tree.dispatch_pointer(contact(
9266            second,
9267            PointerPhase::Up,
9268            second_at,
9269            EventTime::from_millis(20),
9270        ));
9271        assert!(
9272            pressed.get(),
9273            "so the second contact's release cannot clear a visual it never owned",
9274        );
9275        assert_eq!(tree.pressed_by(w), Some(first));
9276
9277        tree.dispatch_pointer(contact(
9278            first,
9279            PointerPhase::Up,
9280            first_at,
9281            EventTime::from_millis(30),
9282        ));
9283        assert!(!pressed.get(), "the owner's release does clear it");
9284    }
9285
9286    /// A cancel clears the visual. The node is never sent an `Up` to clear it
9287    /// from, so nothing else could.
9288    #[test]
9289    fn a_cancel_clears_the_visual() {
9290        let (mut tree, _clock) = tree_on_a_clock();
9291        let (w, pressed) = tappable(&mut tree);
9292        tree.layout(SizeProposal::exact(100.0, 50.0));
9293        let center = tree.bounds(w).center();
9294
9295        let id = contact_id();
9296        tree.dispatch_pointer(contact(id, PointerPhase::Down, center, EventTime::ZERO));
9297        assert!(pressed.get());
9298
9299        tree.dispatch_pointer(contact(
9300            id,
9301            PointerPhase::Cancel,
9302            center,
9303            EventTime::from_millis(20),
9304        ));
9305        assert!(!pressed.get(), "a press that was taken away is not painted");
9306        assert_eq!(tree.pressed_by(w), None);
9307    }
9308
9309    /// A peer winning the arbitration clears the visual. The pressed control is
9310    /// never told; only the router knows it has lost the press.
9311    #[test]
9312    fn a_pan_claim_clears_the_visual() {
9313        let (mut tree, clock) = tree_on_a_clock();
9314        let (row, pressed) = tappable(&mut tree);
9315        let list = tree.add(
9316            StackWidget::new()
9317                .child(row)
9318                .pan_claim(PanClaim::vertical())
9319                .on_scroll(|_e, _c| EventResponse::Handled),
9320        );
9321        tree.layout(SizeProposal::exact(200.0, 400.0));
9322        let _ = list;
9323        let start = Point::new(100.0, 200.0);
9324
9325        let id = contact_id();
9326        tree.dispatch_pointer(contact(id, PointerPhase::Down, start, EventTime::ZERO));
9327        // Inside a claimant, so the visual waits.
9328        assert!(tree.press_pending(row));
9329        clock.set(EventTime::from_millis(100));
9330        tree.tick_gestures(std::time::Instant::now());
9331        assert!(pressed.get(), "…and appears once the delay has elapsed");
9332
9333        // Past the touch profile's 36 dp pan slop: the list claims.
9334        tree.dispatch_pointer(contact(
9335            id,
9336            PointerPhase::Move,
9337            Point::new(100.0, 260.0),
9338            EventTime::from_millis(120),
9339        ));
9340        assert!(
9341            !pressed.get(),
9342            "the row lost the press to the list and must stop advertising it",
9343        );
9344        assert_eq!(tree.pressed_by(row), None);
9345    }
9346
9347    // -----------------------------------------------------------------
9348    // Which button may raise the visual
9349    // -----------------------------------------------------------------
9350
9351    /// The visual answers to the same buttons the activation does. A node
9352    /// carrying a plain `on_tap` accepts `PRIMARY` and nothing else, so a
9353    /// middle, back or forward press must light nothing up — the press it
9354    /// would be advertising can never complete.
9355    #[test]
9356    fn a_button_the_control_cannot_act_on_raises_no_visual() {
9357        let taps = Rc::new(Cell::new(0u32));
9358        let count = taps.clone();
9359        let mut tree = WidgetTree::new();
9360        let w = tree.add(FillWidget::new().focusable().on_tap(move |_e, _c| {
9361            count.set(count.get() + 1);
9362        }));
9363        let pressed = tree.pressed_signal(w);
9364        tree.layout(SizeProposal::exact(100.0, 50.0));
9365        let center = tree.bounds(w).center();
9366
9367        for button in [
9368            PointerButton::Middle,
9369            PointerButton::Back,
9370            PointerButton::Forward,
9371        ] {
9372            tree.dispatch_event(WidgetEvent::pointer_down(center, button, Modifiers::NONE));
9373            assert!(
9374                !pressed.get(),
9375                "{button:?} cannot activate an `on_tap` node, so it must not light one up",
9376            );
9377            assert_eq!(tree.pressed_by(w), None, "and owns no visual to clear");
9378            tree.dispatch_event(WidgetEvent::pointer_up(center, button, Modifiers::NONE));
9379            assert_eq!(
9380                taps.get(),
9381                0,
9382                "the tap recognizer refuses {button:?} too — that is the point",
9383            );
9384        }
9385
9386        // …and the button it does act on is untouched.
9387        tree.dispatch_event(WidgetEvent::pointer_down(
9388            center,
9389            PointerButton::Primary,
9390            Modifiers::NONE,
9391        ));
9392        assert!(pressed.get(), "a primary press lights up as it always has");
9393        assert_eq!(tree.pressed_by(w), Some(PointerId::MOUSE));
9394        tree.dispatch_event(WidgetEvent::pointer_up(
9395            center,
9396            PointerButton::Primary,
9397            Modifiers::NONE,
9398        ));
9399        assert!(!pressed.get());
9400        assert_eq!(taps.get(), 1);
9401    }
9402
9403    /// The case a real user hits: a right-click on a control with no context
9404    /// menu. The secondary arm finds nothing to open and falls through to the
9405    /// ordinary press path, which must still raise nothing.
9406    #[test]
9407    fn a_secondary_press_with_no_context_menu_raises_no_visual() {
9408        let mut tree = WidgetTree::new();
9409        let (w, pressed) = tappable(&mut tree);
9410        tree.layout(SizeProposal::exact(100.0, 50.0));
9411        let center = tree.bounds(w).center();
9412
9413        tree.dispatch_event(WidgetEvent::pointer_down(
9414            center,
9415            PointerButton::Secondary,
9416            Modifiers::NONE,
9417        ));
9418        assert!(
9419            !pressed.get(),
9420            "nothing opened, and nothing may look pressed either",
9421        );
9422        assert_eq!(tree.pressed_by(w), None);
9423        assert!(!tree.press_is_inside(w));
9424    }
9425
9426    /// A widget that widened its own mask keeps the visual on the buttons it
9427    /// widened to: the gate reads the node's declared acceptance, it does not
9428    /// hardcode `PRIMARY`.
9429    #[test]
9430    fn a_widened_mask_widens_the_visual_with_it() {
9431        use crate::event::ButtonMask;
9432
9433        let mut tree = WidgetTree::new();
9434        let w = tree.add(
9435            FillWidget::new()
9436                .on_tap(|_e, _c| {})
9437                .accept_tap_buttons(ButtonMask::PRIMARY | ButtonMask::MIDDLE),
9438        );
9439        let pressed = tree.pressed_signal(w);
9440        tree.layout(SizeProposal::exact(100.0, 50.0));
9441        let center = tree.bounds(w).center();
9442
9443        tree.dispatch_event(WidgetEvent::pointer_down(
9444            center,
9445            PointerButton::Middle,
9446            Modifiers::NONE,
9447        ));
9448        assert!(pressed.get(), "this node really does act on a middle-click");
9449
9450        tree.dispatch_event(WidgetEvent::pointer_up(
9451            center,
9452            PointerButton::Middle,
9453            Modifiers::NONE,
9454        ));
9455        assert!(!pressed.get());
9456    }
9457
9458    /// A press that raises no visual still records the focus a direct pointer
9459    /// defers to its release. A stylus barrel button reports `Secondary`, and
9460    /// a pen that presses a control and lifts on it has chosen that control
9461    /// whether or not the button lit it up — the record exists for the focus,
9462    /// not only for the visual.
9463    #[test]
9464    fn a_press_that_raises_no_visual_still_defers_its_focus() {
9465        use teksilo_tokens::{PenKind, PointerKind};
9466
9467        let (mut tree, _clock) = tree_on_a_clock();
9468        let (w, pressed) = tappable(&mut tree);
9469        tree.layout(SizeProposal::exact(100.0, 50.0));
9470        let center = tree.bounds(w).center();
9471
9472        let id = contact_id();
9473        let barrel = |phase, t| PointerSample {
9474            pointer: PointerInfo {
9475                kind: PointerKind::Pen(PenKind::Pen),
9476                ..PointerInfo::touch(id, t)
9477            },
9478            phase,
9479            position: center,
9480            button: Some(PointerButton::Secondary),
9481            modifiers: Modifiers::NONE,
9482            coalesced: Vec::new(),
9483        };
9484
9485        tree.dispatch_pointer(barrel(PointerPhase::Down, EventTime::ZERO));
9486        assert!(!pressed.get(), "the barrel button activates nothing here");
9487        assert_eq!(tree.pressed_by(w), None);
9488        assert_eq!(
9489            tree.focused(),
9490            None,
9491            "a direct pointer has chosen nothing until it lifts",
9492        );
9493
9494        tree.dispatch_pointer(barrel(PointerPhase::Up, EventTime::from_millis(40)));
9495        assert_eq!(
9496            tree.focused(),
9497            Some(w),
9498            "the deferral is not button-gated: the release landed where the press did",
9499        );
9500        assert_eq!(
9501            tree.focus_origin().and_then(FocusOrigin::pointer_kind),
9502            Some(PointerKind::Pen(PenKind::Pen)),
9503        );
9504    }
9505
9506    // -----------------------------------------------------------------
9507    // The press-feedback delay
9508    // -----------------------------------------------------------------
9509
9510    /// The delay applies only inside a pan claimant — a control nothing can
9511    /// scroll out from under has no ambiguity to wait out.
9512    #[test]
9513    fn the_feedback_delay_applies_only_inside_a_claimant() {
9514        // Outside a claimant: immediate.
9515        let (mut tree, _clock) = tree_on_a_clock();
9516        let (w, pressed) = tappable(&mut tree);
9517        tree.layout(SizeProposal::exact(200.0, 400.0));
9518        let id = contact_id();
9519        let at = tree.bounds(w).center();
9520        tree.dispatch_pointer(contact(id, PointerPhase::Down, at, EventTime::ZERO));
9521        assert!(
9522            !tree.press_pending(w),
9523            "no claimant above it, so nothing to rule out",
9524        );
9525        assert!(pressed.get());
9526
9527        // Inside one: withheld, then released by the delay.
9528        let (mut tree, clock) = tree_on_a_clock();
9529        let (row, pressed) = tappable(&mut tree);
9530        let list = tree.add(
9531            StackWidget::new()
9532                .child(row)
9533                .pan_claim(PanClaim::vertical())
9534                .on_scroll(|_e, _c| EventResponse::Handled),
9535        );
9536        tree.layout(SizeProposal::exact(200.0, 400.0));
9537        let _ = list;
9538        let id = contact_id();
9539        let at = Point::new(100.0, 200.0);
9540        tree.dispatch_pointer(contact(id, PointerPhase::Down, at, EventTime::ZERO));
9541        assert!(tree.press_pending(row), "a finger might be about to scroll");
9542        assert!(!pressed.get(), "so the row does not flash");
9543        assert!(
9544            tree.press_is_inside(row),
9545            "the press is real; only its visual is being withheld",
9546        );
9547
9548        clock.set(EventTime::from_millis(99));
9549        tree.tick_gestures(std::time::Instant::now());
9550        assert!(!pressed.get(), "99 ms is under the 100 ms delay");
9551
9552        clock.set(EventTime::from_millis(100));
9553        tree.tick_gestures(std::time::Instant::now());
9554        assert!(pressed.get(), "and 100 ms is it");
9555        assert!(!tree.press_pending(row));
9556    }
9557
9558    /// A mouse pressing inside the very same claimant waits for nothing: an
9559    /// indirect pointer opens no pan session, so the delay never reaches it.
9560    #[test]
9561    fn a_mouse_inside_a_claimant_never_waits() {
9562        let mut tree = WidgetTree::new();
9563        let (row, pressed) = tappable(&mut tree);
9564        let list = tree.add(
9565            StackWidget::new()
9566                .child(row)
9567                .pan_claim(PanClaim::vertical())
9568                .on_scroll(|_e, _c| EventResponse::Handled),
9569        );
9570        tree.layout(SizeProposal::exact(200.0, 400.0));
9571        let _ = list;
9572
9573        tree.dispatch_event(WidgetEvent::pointer_down(
9574            Point::new(100.0, 200.0),
9575            PointerButton::Primary,
9576            Modifiers::NONE,
9577        ));
9578        assert!(!tree.press_pending(row));
9579        assert!(pressed.get(), "Compact with a mouse is exactly as it was");
9580    }
9581
9582    // -----------------------------------------------------------------
9583    // The EventContext queries
9584    // -----------------------------------------------------------------
9585
9586    /// The three queries `teksilo-widgets`' `common/interaction.rs` consumes,
9587    /// read from inside a real handler.
9588    #[test]
9589    fn a_handler_can_read_the_press_it_is_inside() {
9590        let (mut tree, _clock) = tree_on_a_clock();
9591        let seen: Rc<RefCell<Vec<(bool, bool, bool)>>> = Rc::new(RefCell::new(Vec::new()));
9592        let log = seen.clone();
9593        let row = tree.add(FillWidget::new().on_tap(|_e, _c| {}).on_pointer_event(
9594            move |event, ctx| {
9595                if matches!(event, WidgetEvent::PointerUp { .. }) {
9596                    log.borrow_mut().push((
9597                        ctx.is_pressed(),
9598                        ctx.press_is_inside(),
9599                        ctx.press_pending(),
9600                    ));
9601                }
9602                EventResponse::Ignored
9603            },
9604        ));
9605        let list = tree.add(
9606            StackWidget::new()
9607                .child(row)
9608                .pan_claim(PanClaim::vertical())
9609                .on_scroll(|_e, _c| EventResponse::Handled),
9610        );
9611        tree.layout(SizeProposal::exact(200.0, 400.0));
9612        let _ = list;
9613
9614        let id = contact_id();
9615        let at = Point::new(100.0, 200.0);
9616        tree.dispatch_pointer(contact(id, PointerPhase::Down, at, EventTime::ZERO));
9617        tree.dispatch_pointer(contact(
9618            id,
9619            PointerPhase::Up,
9620            at,
9621            EventTime::from_millis(30),
9622        ));
9623
9624        assert_eq!(
9625            seen.borrow().as_slice(),
9626            &[(false, true, true)],
9627            "released inside the claimant before the delay elapsed: inside, \
9628             pending, and therefore not yet showing",
9629        );
9630    }
9631
9632    /// A handler outside any press reads three falses rather than a panic or a
9633    /// stale answer.
9634    #[test]
9635    fn a_handler_outside_a_press_reads_nothing() {
9636        let mut tree = WidgetTree::new();
9637        let asked = Rc::new(Cell::new(false));
9638        let flag = asked.clone();
9639        let w = tree.add(FillWidget::new().focusable().on_key(move |_e, ctx| {
9640            flag.set(ctx.is_pressed() || ctx.press_is_inside() || ctx.press_pending());
9641            EventResponse::Ignored
9642        }));
9643        tree.layout(SizeProposal::exact(100.0, 50.0));
9644        tree.focus(w);
9645        tree.press_key(Key::ArrowDown, Modifiers::NONE);
9646        assert!(!asked.get());
9647    }
9648
9649    /// A completed interaction leaves no press behind, and the leak detector
9650    /// says so — it now reads the press table, which it could not before this
9651    /// package landed one.
9652    #[test]
9653    fn a_completed_press_leaves_the_detector_clean() {
9654        let (mut tree, _clock) = tree_on_a_clock();
9655        let (w, pressed) = tappable(&mut tree);
9656        tree.layout(SizeProposal::exact(100.0, 50.0));
9657        let at = tree.bounds(w).center();
9658
9659        let id = contact_id();
9660        tree.dispatch_pointer(contact(id, PointerPhase::Down, at, EventTime::ZERO));
9661        assert!(pressed.get());
9662        tree.dispatch_pointer(contact(
9663            id,
9664            PointerPhase::Up,
9665            at,
9666            EventTime::from_millis(30),
9667        ));
9668        tree.assert_no_leaked_pointer_state();
9669    }
9670
9671    /// …and it would have caught the opposite. Driven by holding the press open
9672    /// rather than by faking state, so the assertion is about the real exit
9673    /// path.
9674    #[test]
9675    fn the_detector_reports_a_press_still_held() {
9676        let (mut tree, _clock) = tree_on_a_clock();
9677        let (w, _pressed) = tappable(&mut tree);
9678        tree.layout(SizeProposal::exact(100.0, 50.0));
9679        let at = tree.bounds(w).center();
9680
9681        let id = contact_id();
9682        tree.dispatch_pointer(contact(id, PointerPhase::Down, at, EventTime::ZERO));
9683        let held = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
9684            tree.assert_no_leaked_pointer_state()
9685        }));
9686        let message = *held
9687            .expect_err("a live press is leaked state")
9688            .downcast::<String>()
9689            .expect("the detector panics with a message");
9690        assert!(
9691            message.contains("is still pressed by"),
9692            "the press is named in the report, got: {message}",
9693        );
9694    }
9695
9696    /// A container that lays its children out side by side, so a hit test at a
9697    /// given x picks a specific child. `StackWidget` deliberately stacks at one
9698    /// origin, which is the opposite of what a release-elsewhere test needs.
9699    #[derive(Debug)]
9700    struct SideBySide {
9701        children: Vec<WidgetId>,
9702    }
9703
9704    impl crate::widget::Widget for SideBySide {
9705        fn layout_response(
9706            &self,
9707            proposal: SizeProposal,
9708            _ctx: &crate::widget::LayoutContext,
9709        ) -> crate::widget::LayoutResponse {
9710            proposal.resolve(0.0, 0.0).into()
9711        }
9712
9713        fn place_children(
9714            &self,
9715            bounds: teksilo_canvas::Rect,
9716            _proposal: SizeProposal,
9717            children: &mut [crate::widget::WidgetPlacement],
9718            _ctx: &crate::widget::LayoutContext,
9719        ) {
9720            let n = children.len().max(1) as f32;
9721            let w = bounds.width / n;
9722            for (i, child) in children.iter_mut().enumerate() {
9723                child.origin = Point::new(bounds.x + w * i as f32, bounds.y);
9724                child.size = teksilo_canvas::Size::new(w, bounds.height);
9725            }
9726        }
9727
9728        fn children(&self) -> Vec<WidgetId> {
9729            self.children.clone()
9730        }
9731    }
9732}
9733
9734#[cfg(test)]
9735mod overlay_release_dismissal_tests {
9736    //! Outside-press overlay dismissal, driven through the real ingress door.
9737    //!
9738    //! The defect: `handle_click_outside` ran on the `PointerDown` and then
9739    //! *fell through*, so one press both closed a menu and actuated whatever
9740    //! the menu was covering. With a cursor that is defensible — the user aimed
9741    //! at a pixel they could see the whole time. With a finger it is not: the
9742    //! menu is the only thing they were looking at, and the control underneath
9743    //! is one they never saw.
9744
9745    use std::cell::Cell;
9746    use std::rc::Rc;
9747
9748    use teksilo_canvas::{Point, Rect, Size, SizeProposal};
9749
9750    use crate::WidgetId;
9751    use crate::event::{Modifiers, PointerButton, WidgetEvent};
9752    use crate::overlay::{DismissBehavior, OverlayPlacement, OverlayRequest};
9753    use crate::pointer::{
9754        BackendDeviceKey, EventTime, PointerId, PointerIdAllocator, PointerInfo, PointerPhase,
9755        PointerSample,
9756    };
9757    use crate::test_widgets::FillWidget;
9758    use crate::widget::{LayoutContext, LayoutResponse, Widget};
9759    use crate::widget_builder::WidgetBuilder;
9760    use crate::widget_tree::WidgetTree;
9761
9762    // -----------------------------------------------------------------
9763    // Fixtures
9764    // -----------------------------------------------------------------
9765
9766    /// A leaf with an intrinsic size, so an overlay hung off it gets real
9767    /// bounds out of `position_overlays` instead of a zero rect.
9768    #[derive(Debug)]
9769    struct Panel(Size);
9770
9771    impl Widget for Panel {
9772        fn layout_response(&self, _proposal: SizeProposal, _ctx: &LayoutContext) -> LayoutResponse {
9773            self.0.into()
9774        }
9775    }
9776
9777    /// A root that puts its first child over the whole window and its second in
9778    /// a 10 dp corner.
9779    ///
9780    /// Two bare roots would both be laid out at the window's full size — the
9781    /// trigger would then contain every press point, and the pre-existing
9782    /// "a press on a click-opened overlay's own anchor is consumed" rule would
9783    /// swallow the very presses these tests are about.
9784    #[derive(Debug)]
9785    struct PageAndTrigger {
9786        children: Vec<WidgetId>,
9787    }
9788
9789    impl Widget for PageAndTrigger {
9790        fn layout_response(&self, proposal: SizeProposal, _ctx: &LayoutContext) -> LayoutResponse {
9791            proposal.resolve(0.0, 0.0).into()
9792        }
9793
9794        fn place_children(
9795            &self,
9796            bounds: Rect,
9797            _proposal: SizeProposal,
9798            children: &mut [crate::widget::WidgetPlacement],
9799            _ctx: &LayoutContext,
9800        ) {
9801            if let Some(page) = children.get_mut(0) {
9802                page.origin = bounds.origin();
9803                page.size = bounds.size();
9804            }
9805            if let Some(trigger) = children.get_mut(1) {
9806                trigger.origin = bounds.origin();
9807                trigger.size = Size::new(10.0, 10.0);
9808            }
9809        }
9810
9811        fn children(&self) -> Vec<WidgetId> {
9812            self.children.clone()
9813        }
9814    }
9815
9816    fn contact_id(n: u64) -> PointerId {
9817        PointerIdAllocator::global().begin(BackendDeviceKey::new(0x0FA2), n)
9818    }
9819
9820    fn touch(id: PointerId, phase: PointerPhase, at: Point) -> PointerSample {
9821        PointerSample {
9822            pointer: PointerInfo::touch(id, EventTime::ZERO),
9823            phase,
9824            position: at,
9825            button: None,
9826            modifiers: Modifiers::NONE,
9827            coalesced: Vec::new(),
9828        }
9829    }
9830
9831    /// The scene every test below shares: a tappable page filling the window,
9832    /// and a menu overlay floating over part of it at (100, 100, 200, 200).
9833    ///
9834    /// The menu's content is a separate root, so a press outside it lands on
9835    /// the page and a press inside it lands on the menu — which is exactly the
9836    /// arrangement the dismissal rule is about.
9837    fn page_with_a_menu() -> (WidgetTree, WidgetId, Rc<Cell<u32>>) {
9838        let mut tree = WidgetTree::new();
9839        let taps = Rc::new(Cell::new(0u32));
9840        let counter = taps.clone();
9841        let page = tree.add(
9842            FillWidget::new()
9843                .focusable()
9844                .on_tap(move |_e, _c| counter.set(counter.get() + 1)),
9845        );
9846        // A small trigger in the corner, well clear of both press points — see
9847        // `PageAndTrigger` for why it cannot simply be a second root.
9848        let trigger = tree.add(Panel(Size::new(10.0, 10.0)));
9849        let _root = tree.add(PageAndTrigger {
9850            children: vec![page, trigger],
9851        });
9852        let menu = tree.add(Panel(Size::new(200.0, 200.0)));
9853        tree.show_overlay(OverlayRequest::new(
9854            menu,
9855            trigger,
9856            OverlayPlacement::AtPointer(Point::new(100.0, 100.0)),
9857            DismissBehavior::ClickOutside,
9858        ));
9859        tree.layout(SizeProposal::exact(800.0, 600.0));
9860        assert_eq!(tree.active_overlays().len(), 1, "the menu is open");
9861        (tree, page, taps)
9862    }
9863
9864    fn outside() -> Point {
9865        Point::new(600.0, 500.0)
9866    }
9867
9868    fn inside_menu() -> Point {
9869        Point::new(150.0, 150.0)
9870    }
9871
9872    // -----------------------------------------------------------------
9873    // The direct-pointer contract
9874    // -----------------------------------------------------------------
9875
9876    /// The arming press reaches nothing: no press record, no capture, and the
9877    /// menu is still up because the decision belongs to the release.
9878    #[test]
9879    fn the_suppressed_down_leaves_nothing_pressed_or_captured_beneath() {
9880        let (mut tree, page, taps) = page_with_a_menu();
9881        let finger = contact_id(1);
9882        tree.dispatch_pointer(touch(finger, PointerPhase::Down, outside()));
9883
9884        assert_eq!(
9885            tree.active_overlays().len(),
9886            1,
9887            "the press does not close the menu; the release does"
9888        );
9889        assert_eq!(tree.pressed_by(page), None, "nothing beneath is pressed");
9890        let entry = tree.pointers.get(finger).expect("the contact is live");
9891        assert_eq!(entry.captured_by, None, "nothing beneath captured it");
9892        assert!(entry.sequence.is_none(), "no arbitration was opened");
9893        assert_eq!(taps.get(), 0);
9894    }
9895
9896    /// …and the release closes the menu without actuating what it covered.
9897    #[test]
9898    fn a_touch_tap_outside_a_menu_closes_it_and_actuates_nothing() {
9899        let (mut tree, page, taps) = page_with_a_menu();
9900        let finger = contact_id(2);
9901        tree.dispatch_pointer(touch(finger, PointerPhase::Down, outside()));
9902        tree.dispatch_pointer(touch(finger, PointerPhase::Up, outside()));
9903
9904        assert!(tree.active_overlays().is_empty(), "the menu closed");
9905        assert_eq!(taps.get(), 0, "the page beneath was never tapped");
9906        assert_eq!(tree.pressed_by(page), None);
9907        tree.assert_no_leaked_pointer_state();
9908    }
9909
9910    /// A press that never completes delivers nothing at all — neither the
9911    /// dismissal it armed nor the press it withheld.
9912    #[test]
9913    fn a_cancelled_press_aborts_the_arm() {
9914        let (mut tree, page, taps) = page_with_a_menu();
9915        let finger = contact_id(3);
9916        tree.dispatch_pointer(touch(finger, PointerPhase::Down, outside()));
9917        tree.dispatch_pointer(touch(finger, PointerPhase::Cancel, outside()));
9918
9919        assert_eq!(tree.active_overlays().len(), 1, "the menu survives");
9920        assert_eq!(taps.get(), 0);
9921        assert_eq!(tree.pressed_by(page), None);
9922        tree.assert_no_leaked_pointer_state();
9923    }
9924
9925    /// Land beside the menu, drag onto it, lift there. The finger changed its
9926    /// mind: the menu stays, and the page under the arming press was never
9927    /// touched either.
9928    #[test]
9929    fn a_press_slid_onto_the_menu_dismisses_nothing() {
9930        let (mut tree, _page, taps) = page_with_a_menu();
9931        let finger = contact_id(4);
9932        tree.dispatch_pointer(touch(finger, PointerPhase::Down, outside()));
9933        tree.dispatch_pointer(touch(finger, PointerPhase::Move, inside_menu()));
9934        tree.dispatch_pointer(touch(finger, PointerPhase::Up, inside_menu()));
9935
9936        assert_eq!(tree.active_overlays().len(), 1, "the menu survives");
9937        assert_eq!(taps.get(), 0);
9938        tree.assert_no_leaked_pointer_state();
9939    }
9940
9941    /// A finger working *inside* the menu is an interaction, and a second one
9942    /// landing on the page is not a reason to take it away mid-flight.
9943    #[test]
9944    fn a_second_contact_cannot_dismiss_what_the_first_is_manipulating() {
9945        let (mut tree, _page, _taps) = page_with_a_menu();
9946        let first = contact_id(5);
9947        let second = contact_id(6);
9948
9949        tree.dispatch_pointer(touch(first, PointerPhase::Down, inside_menu()));
9950        assert!(
9951            tree.pointers
9952                .get(first)
9953                .is_some_and(|e| e.sequence.is_some()),
9954            "the first contact holds a live press inside the menu"
9955        );
9956
9957        tree.dispatch_pointer(touch(second, PointerPhase::Down, outside()));
9958        tree.dispatch_pointer(touch(second, PointerPhase::Up, outside()));
9959        assert_eq!(
9960            tree.active_overlays().len(),
9961            1,
9962            "the menu the first finger is holding must not close under it"
9963        );
9964
9965        // Once the first contact's press is over there is nothing left to
9966        // revoke, so it protects nothing and the same tap closes the menu.
9967        tree.dispatch_pointer(touch(first, PointerPhase::Up, inside_menu()));
9968        let third = contact_id(7);
9969        tree.dispatch_pointer(touch(third, PointerPhase::Down, outside()));
9970        tree.dispatch_pointer(touch(third, PointerPhase::Up, outside()));
9971        assert!(tree.active_overlays().is_empty());
9972        tree.assert_no_leaked_pointer_state();
9973    }
9974
9975    /// A contact that is merely *holding an arm* has no sequence and no
9976    /// capture, so `press_is_revocable` says it has no press — and it must not
9977    /// block a second contact's dismissal the way a real press does.
9978    #[test]
9979    fn an_arm_is_not_itself_a_press_that_blocks_another_contact() {
9980        let (mut tree, _page, _taps) = page_with_a_menu();
9981        let first = contact_id(8);
9982        let second = contact_id(9);
9983
9984        tree.dispatch_pointer(touch(first, PointerPhase::Down, outside()));
9985        assert!(
9986            tree.overlay_manager().has_armed_dismiss(first),
9987            "the first contact armed"
9988        );
9989        // The first contact is live but holds nothing revocable.
9990        assert!(tree.busy_press_points(second).is_empty());
9991
9992        tree.dispatch_pointer(touch(second, PointerPhase::Down, outside()));
9993        assert!(tree.overlay_manager().has_armed_dismiss(second));
9994        tree.dispatch_pointer(touch(second, PointerPhase::Up, outside()));
9995        assert!(tree.active_overlays().is_empty());
9996
9997        // The first contact's arm now names an overlay that is gone; its own
9998        // release must be a quiet no-op rather than a panic.
9999        tree.dispatch_pointer(touch(first, PointerPhase::Up, outside()));
10000        tree.assert_no_leaked_pointer_state();
10001    }
10002
10003    /// A tap *inside* the menu is not an outside press, so nothing is armed and
10004    /// the menu's own content handles the press exactly as before.
10005    #[test]
10006    fn a_touch_inside_the_menu_arms_nothing() {
10007        let (mut tree, _page, _taps) = page_with_a_menu();
10008        let finger = contact_id(10);
10009        tree.dispatch_pointer(touch(finger, PointerPhase::Down, inside_menu()));
10010        assert!(!tree.overlay_manager().has_armed_dismiss(finger));
10011        tree.dispatch_pointer(touch(finger, PointerPhase::Up, inside_menu()));
10012        assert_eq!(tree.active_overlays().len(), 1);
10013        tree.assert_no_leaked_pointer_state();
10014    }
10015
10016    /// A contact whose press was never opened — it hit nothing, or its `Down`
10017    /// was suppressed by an arm — still ceases to exist when the platform
10018    /// revokes it.
10019    ///
10020    /// The cancel funnel returns early for a pointer with nothing revocable and
10021    /// so never reaches the step that drops the table entry. Before the release
10022    /// dismissal that shape was rare (a press on bare background); the arm makes
10023    /// it the ordinary case, so the ingress door applies the same
10024    /// contact-ceases-to-exist rule it applies to an `Up`.
10025    #[test]
10026    fn a_contact_with_no_press_still_ends_when_the_platform_revokes_it() {
10027        let mut tree = WidgetTree::new();
10028        tree.layout(SizeProposal::exact(800.0, 600.0));
10029        let finger = contact_id(99);
10030        tree.dispatch_pointer(touch(finger, PointerPhase::Down, outside()));
10031        tree.dispatch_pointer(touch(finger, PointerPhase::Cancel, outside()));
10032        tree.assert_no_leaked_pointer_state();
10033    }
10034
10035    // -----------------------------------------------------------------
10036    // The mouse, unchanged
10037    // -----------------------------------------------------------------
10038
10039    /// The press dismisses and falls through, exactly as before: one click both
10040    /// closes the menu and actuates the control beneath.
10041    #[test]
10042    fn a_mouse_click_outside_a_menu_dismisses_on_the_press_and_falls_through() {
10043        let (mut tree, _page, taps) = page_with_a_menu();
10044        tree.dispatch_event(WidgetEvent::pointer_down(
10045            outside(),
10046            PointerButton::Primary,
10047            Modifiers::NONE,
10048        ));
10049        assert!(
10050            tree.active_overlays().is_empty(),
10051            "the mouse still dismisses on the press"
10052        );
10053        assert!(
10054            tree.pointers
10055                .get(PointerId::MOUSE)
10056                .is_some_and(|e| e.sequence.is_some()),
10057            "and the press still reaches the page beneath"
10058        );
10059        tree.dispatch_event(WidgetEvent::pointer_up(
10060            outside(),
10061            PointerButton::Primary,
10062            Modifiers::NONE,
10063        ));
10064        assert_eq!(taps.get(), 1, "the control beneath activated");
10065        assert!(
10066            !tree.overlay_manager().has_armed_dismiss(PointerId::MOUSE),
10067            "a mouse never arms"
10068        );
10069        tree.assert_no_leaked_pointer_state();
10070    }
10071
10072    // -----------------------------------------------------------------
10073    // Contact avoidance
10074    // -----------------------------------------------------------------
10075
10076    /// A context menu raised by a finger keeps clear of the contact patch; the
10077    /// same menu raised by a mouse lands on the pixel, as it always has.
10078    #[test]
10079    fn a_context_menu_avoids_the_contact_that_opened_it() {
10080        fn menu_bounds(pointer: PointerInfo, at: Point) -> Rect {
10081            let mut tree = WidgetTree::new();
10082            let page = tree.add(
10083                FillWidget::new()
10084                    .focusable()
10085                    .context_menu(|_p, _ctx| Some(Box::new(Panel(Size::new(200.0, 160.0))))),
10086            );
10087            let _ = page;
10088            tree.layout(SizeProposal::exact(800.0, 600.0));
10089            tree.dispatch_pointer(PointerSample {
10090                pointer,
10091                phase: PointerPhase::Down,
10092                position: at,
10093                button: Some(PointerButton::Secondary),
10094                modifiers: Modifiers::NONE,
10095                coalesced: Vec::new(),
10096            });
10097            tree.layout(SizeProposal::exact(800.0, 600.0));
10098            let id = *tree
10099                .active_overlays()
10100                .first()
10101                .expect("the context menu opened");
10102            tree.overlay_manager().bounds_for(id).expect("bounds")
10103        }
10104
10105        let at = Point::new(400.0, 300.0);
10106        let finger = menu_bounds(PointerInfo::touch(contact_id(11), EventTime::ZERO), at);
10107        let contact = crate::overlay::rect_centred_on(at, crate::overlay::ASSUMED_CONTACT_PATCH);
10108        assert!(
10109            finger.x < contact.x && finger.right() <= contact.x,
10110            "a touch menu clears the contact patch: {finger:?} vs {contact:?}"
10111        );
10112
10113        let mouse = menu_bounds(PointerInfo::mouse(EventTime::ZERO), at);
10114        assert_eq!(
10115            (mouse.x, mouse.y),
10116            (at.x, at.y),
10117            "a mouse menu still opens with its corner on the pointer"
10118        );
10119    }
10120}
10121
10122/// An overlay is chosen by its **bounds**, and what happens when its content
10123/// then claims nothing at the point.
10124///
10125/// Two answers, and the flag on the content root is what picks between them.
10126/// An ordinary overlay ends the search inside itself — that is what keeps the
10127/// miss-only slop pass confined to the one layer the exact pass entered, so a
10128/// near-miss on a menu row can never be re-attributed to a control on the page
10129/// behind the menu. An overlay whose content root declares `event_pass_through`
10130/// is the exception: the flag already means "what I did not claim belongs to
10131/// whatever is behind me", and an overlay root is not an exception to it.
10132///
10133/// This is not a hypothetical. The touch text affordances were specified as a
10134/// viewport-sized pass-through layer, and under the first answer applied to
10135/// both, mounting one made the editor beneath stop taking presses entirely —
10136/// measured, as `hit_test` returning `None` at a point inside the field.
10137#[cfg(test)]
10138mod pass_through_overlay_tests {
10139    use teksilo_canvas::{Point, Rect, SizeProposal};
10140
10141    use crate::WidgetId;
10142    use crate::overlay::{DismissBehavior, OverlayPlacement, OverlayRequest};
10143    use crate::test_widgets::FillWidget;
10144    use crate::widget::{LayoutContext, LayoutResponse, Widget};
10145    use crate::widget_builder::WidgetBuilder;
10146    use crate::widget_tree::WidgetTree;
10147
10148    /// The affordance layer's shape: fills whatever it is given, and puts its
10149    /// one child — a selection handle — on a fixed rectangle inside it.
10150    #[derive(Debug)]
10151    struct HandleLayer {
10152        handle: WidgetId,
10153        at: Rect,
10154    }
10155
10156    impl Widget for HandleLayer {
10157        fn layout_response(&self, proposal: SizeProposal, _ctx: &LayoutContext) -> LayoutResponse {
10158            proposal.resolve(0.0, 0.0).into()
10159        }
10160
10161        fn place_children(
10162            &self,
10163            _bounds: Rect,
10164            _proposal: SizeProposal,
10165            children: &mut [crate::widget::WidgetPlacement],
10166            _ctx: &LayoutContext,
10167        ) {
10168            if let Some(child) = children.get_mut(0) {
10169                child.origin = self.at.origin();
10170                child.size = self.at.size();
10171            }
10172        }
10173
10174        fn children(&self) -> Vec<WidgetId> {
10175            vec![self.handle]
10176        }
10177    }
10178
10179    const HANDLE: Rect = Rect {
10180        x: 10.0,
10181        y: 10.0,
10182        width: 20.0,
10183        height: 20.0,
10184    };
10185
10186    /// Which flag the overlay's content root carries.
10187    #[derive(Clone, Copy, PartialEq)]
10188    enum RootFlag {
10189        /// The affordance layer's: not a target itself, children are.
10190        PassThrough,
10191        /// Neither the root nor its children are targets. Stronger, and
10192        /// deliberately **not** what the fall-through is gated on.
10193        HitTransparent,
10194    }
10195
10196    /// A field under a viewport-sized overlay carrying one handle.
10197    ///
10198    /// Both flags make the subtree answer `None` for a point no handle covers,
10199    /// which is the state the fall-through decides — so the two arms differ in
10200    /// nothing but the flag the router reads.
10201    fn field_under_a_layer(flag: RootFlag) -> (WidgetTree, WidgetId, WidgetId) {
10202        let mut tree = WidgetTree::new();
10203        let field = tree.add(FillWidget::new());
10204        let handle = tree.add(FillWidget::new());
10205        let layer = HandleLayer { handle, at: HANDLE };
10206        let layer = match flag {
10207            RootFlag::PassThrough => tree.add(layer.event_pass_through(true)),
10208            RootFlag::HitTransparent => tree.add(layer.hit_transparent(true)),
10209        };
10210        tree.show_overlay(OverlayRequest::new(
10211            layer,
10212            field,
10213            OverlayPlacement::FullViewport,
10214            DismissBehavior::Manual,
10215        ));
10216        tree.layout(SizeProposal::exact(400.0, 200.0));
10217        assert_eq!(tree.active_overlays().len(), 1, "the layer is up");
10218        (tree, field, handle)
10219    }
10220
10221    /// The door: the surface under a pass-through layer goes on taking presses.
10222    #[test]
10223    fn a_pass_through_layer_hands_back_what_it_did_not_claim() {
10224        let (tree, field, handle) = field_under_a_layer(RootFlag::PassThrough);
10225
10226        assert_eq!(
10227            tree.hit_test(Point::new(15.0, 15.0)),
10228            Some(handle),
10229            "the layer must still win the point its own child covers"
10230        );
10231        assert_eq!(
10232            tree.hit_test(Point::new(200.0, 100.0)),
10233            Some(field),
10234            "a press the layer did not claim must reach the surface beneath it"
10235        );
10236    }
10237
10238    /// `event_pass_through` removes a node from **hit-testing**, not from the
10239    /// **bubble path** of a descendant that was hit.
10240    ///
10241    /// The distinction is what lets a host mount its affordances at the full
10242    /// viewport and still answer the one press neither the layer nor the surface
10243    /// beneath can: the pass-through root is skipped when a point belongs to
10244    /// nobody in its subtree, and is still told about a press that landed on one
10245    /// of its children. The single-line text stack's `AffordanceHost` is exactly
10246    /// this — a cursor's click on a selection handle, which the handle refuses and
10247    /// the editor never sees.
10248    #[test]
10249    fn a_pass_through_root_still_hears_a_press_that_landed_on_its_child() {
10250        use std::cell::Cell;
10251        use std::rc::Rc;
10252
10253        let seen = Rc::new(Cell::new(0u32));
10254        let counter = seen.clone();
10255        let mut tree = WidgetTree::new();
10256        let field = tree.add(FillWidget::new());
10257        let handle = tree.add(FillWidget::new().on_tap(|_e, _c| {}));
10258        let layer = tree.add(
10259            HandleLayer { handle, at: HANDLE }
10260                .event_pass_through(true)
10261                .on_pointer_event(move |_event, _ctx| {
10262                    counter.set(counter.get() + 1);
10263                    crate::event::EventResponse::Ignored
10264                }),
10265        );
10266        tree.show_overlay(OverlayRequest::new(
10267            layer,
10268            field,
10269            OverlayPlacement::FullViewport,
10270            DismissBehavior::Manual,
10271        ));
10272        tree.layout(SizeProposal::exact(400.0, 200.0));
10273
10274        tree.pointer_down_button(Point::new(15.0, 15.0), crate::event::PointerButton::Primary);
10275        assert!(
10276            seen.get() > 0,
10277            "a pass-through root heard nothing about a press on its own child"
10278        );
10279
10280        let after_child = seen.get();
10281        tree.pointer_up_button(Point::new(15.0, 15.0), crate::event::PointerButton::Primary);
10282        // …and a press it did not contain a target for never arrives, because it
10283        // was never the hit.
10284        tree.pointer_down_button(
10285            Point::new(200.0, 100.0),
10286            crate::event::PointerButton::Primary,
10287        );
10288        assert_eq!(
10289            seen.get(),
10290            after_child + 1,
10291            "the press-and-lift on the child accounts for the count, and the \
10292             press on the surface beneath added nothing"
10293        );
10294    }
10295
10296    /// …and the widening stops at that one flag.
10297    ///
10298    /// `hit_transparent` is the discriminating case, and the only one available:
10299    /// it is the other way for an overlay's content to claim nothing at a point,
10300    /// so it is the fixture in which the gate — rather than the subtree's own
10301    /// answer — is what decides. A gate that read "the subtree claimed nothing"
10302    /// alone would fall through here too, and with it past every overlay whose
10303    /// content happens to miss, which is what confines the miss-only slop pass to
10304    /// the layer the exact pass entered.
10305    ///
10306    /// The exclusion is deliberate rather than an oversight: the one overlay that
10307    /// must be seen past regardless is the drag preview, and the hit-test already
10308    /// takes an explicit `exclude_overlay` for it.
10309    #[test]
10310    fn a_hit_transparent_root_does_not_get_the_fall_through() {
10311        let (tree, field, _handle) = field_under_a_layer(RootFlag::HitTransparent);
10312
10313        // Nothing in the overlay is a target, not even the handle.
10314        assert_eq!(
10315            tree.hit_test(Point::new(15.0, 15.0)),
10316            None,
10317            "hit_transparent must exclude the subtree, or this fixture is not \
10318             testing the gate"
10319        );
10320        assert_eq!(
10321            tree.hit_test(Point::new(200.0, 100.0)),
10322            None,
10323            "the fall-through reached past an overlay that did not ask for it"
10324        );
10325        let _ = field;
10326    }
10327}
10328
10329/// Say once per owner, in a debug build, that its menu refused a section a
10330/// node added to it (its widget does not implement
10331/// `Widget::append_context_menu_section`), so the section was left out.
10332fn note_refused_section(owner: WidgetId) {
10333    #[cfg(debug_assertions)]
10334    {
10335        thread_local! {
10336            static NOTED: std::cell::RefCell<std::collections::HashSet<WidgetId>> =
10337                std::cell::RefCell::new(std::collections::HashSet::new());
10338        }
10339        if NOTED.with(|noted| noted.borrow_mut().insert(owner)) {
10340            eprintln!(
10341                "teksilo: the context menu of {owner:?} takes no section \
10342                 (Widget::append_context_menu_section), so a contribution was left out"
10343            );
10344        }
10345    }
10346    #[cfg(not(debug_assertions))]
10347    let _ = owner;
10348}
10349
10350/// A key's identity for pairing a release with its press when the window
10351/// manager noted no physical key (tests, automation): the key itself, a
10352/// character folded to lower case so a Shift released first does not split
10353/// one key into two.
10354fn logical_key_identity(key: Key) -> u64 {
10355    use std::hash::{Hash, Hasher};
10356    let key = match key {
10357        Key::Character(c) => Key::Character(c.to_ascii_lowercase()),
10358        other => other,
10359    };
10360    let mut hasher = std::collections::hash_map::DefaultHasher::new();
10361    key.hash(&mut hasher);
10362    hasher.finish()
10363}