Skip to main content

teksilo_core/widget/
event_context.rs

1// SPDX-License-Identifier: MPL-2.0
2// SPDX-FileCopyrightText: 2026 FernTech
3
4use crate::pointer::touch_action::TouchAction;
5use crate::widget_id::WidgetId;
6
7use super::CursorIcon;
8
9/// Selects which overlay-dismissal pathway runs after a handler
10/// returns. Last-write-wins: each `dismiss_*_overlays()` setter
11/// overwrites the previous choice. `None` (the default) falls
12/// through to draining individual ids from `overlay_dismissals`.
13#[derive(Debug, Clone, Copy, PartialEq, Eq)]
14pub(crate) enum DismissScope {
15    /// Dismiss every overlay in the stack, including hosts.
16    All,
17    /// Dismiss every overlay whose content is *not* a host surface
18    /// (`Tooltip`, `Dialog`, `AlertDialog`). Used by popover triggers
19    /// and pre-show cleanup.
20    AllExceptHosts,
21    /// Walk up from the source widget's containing overlay,
22    /// dismissing menu-like overlays and stopping at the first host
23    /// surface. Used by menu / dropdown item activation.
24    SelfChain,
25    /// Dismiss the topmost overlay only.
26    Top,
27}
28
29/// One queued "reveal this rectangle" request, drained after the handler
30/// returns and turned into a [`WidgetEvent::ScrollIntoView`] per clipping
31/// ancestor.
32///
33/// A struct rather than a tuple because the three modifiers (margin, alignment,
34/// motion) are independent and positional tuples of that width stop being
35/// readable at the call site.
36///
37/// [`WidgetEvent::ScrollIntoView`]: crate::event::WidgetEvent::ScrollIntoView
38#[derive(Debug, Clone, Copy, PartialEq)]
39pub(crate) struct ScrollRevealRequest {
40    /// The target, in absolute tree (window) coordinates.
41    pub(crate) rect: teksilo_canvas::Rect,
42    /// Breathing room to keep around the target, in logical pixels.
43    pub(crate) margin: f32,
44    /// Where the target should come to rest vertically.
45    pub(crate) align: crate::event::ScrollAlign,
46    /// Whether to jump or glide.
47    pub(crate) motion: crate::event::ScrollMotion,
48    /// **Whose** ancestors to walk, when that is not the widget whose handler
49    /// queued this.
50    ///
51    /// `None` means the source widget, which is right whenever a widget reveals
52    /// something inside itself. It is wrong — silently — whenever the rect belongs
53    /// to a *different* widget: a find banner's Next button asking for a match in
54    /// the prose, a toolbar revealing a row in the list below it. Those walk the
55    /// button's ancestors, which do not include the scroll container the rect lives
56    /// in, so nothing scrolls and the reveal is a no-op no error reports.
57    pub(crate) from: Option<crate::widget_id::WidgetId>,
58}
59
60/// What a handler said about the cursor during one dispatch.
61///
62/// A handler either names a cursor or withdraws, and the two are distinct
63/// answers: withdrawing is not "show `Default`", it is "the node's own
64/// declaration applies again". One slot, so the last call in a dispatch wins,
65/// the way it did when this was a bare `Option<CursorIcon>`.
66#[derive(Clone, Copy, Debug, PartialEq, Eq)]
67pub(crate) enum CursorRequest {
68    /// Override the cursor with this icon.
69    Set(CursorIcon),
70    /// Give the cursor back to whatever the hovered node declared.
71    Release,
72}
73
74/// Context available during event handling.
75pub struct EventContext<'ops> {
76    /// A handler's word on the cursor for this dispatch, if it said one.
77    pub(crate) cursor_request: Option<CursorRequest>,
78    /// The cursor the **node** declared, written only by the router's
79    /// `PointerEnter` / `PointerLeave` arms. Kept apart from
80    /// [`cursor_request`](Self::cursor_request) so that a handler which also
81    /// speaks during the same dispatch overrides the declared cursor without
82    /// erasing the tree's memory of what it was — which is the value
83    /// [`release_cursor`](Self::release_cursor) hands back to.
84    pub(crate) declared_cursor_request: Option<CursorIcon>,
85    pub(crate) tree_mutations: Vec<TreeMutation>,
86    pub(crate) idle_callbacks: Vec<crate::idle::IdleCallback>,
87    pub(crate) modal_requests: Vec<crate::modal::ModalRequest>,
88    pub(crate) dismiss_modal: bool,
89    pub(crate) overlay_requests: Vec<crate::overlay::OverlayRequest>,
90    pub(crate) overlay_dismissals: Vec<crate::overlay::OverlayId>,
91    /// Content widget ids whose currently-shown overlay (if any) should
92    /// be dismissed. Resolved to an `OverlayId` via
93    /// `OverlayManager::find_by_content` at drain time. Lets a handler
94    /// dismiss an overlay it can only identify by content (e.g. a single
95    /// reusable tooltip surface) — the symmetric companion to
96    /// [`cancel_delayed_overlay`](EventContext::cancel_delayed_overlay).
97    pub(crate) overlay_content_dismissals: Vec<crate::widget_id::WidgetId>,
98    /// Overlay requests that name a z-band other than the default. Kept apart
99    /// from [`overlay_requests`](Self::overlay_requests) rather than carried on
100    /// `OverlayRequest` itself: the band is a property of the *show*, not of
101    /// the request, and every existing construction site of the struct would
102    /// otherwise have to name it.
103    pub(crate) overlay_band_requests:
104        Vec<(crate::overlay::OverlayRequest, crate::overlay::OverlayBand)>,
105    /// New placements for overlays named by their content root. A
106    /// caret-anchored overlay has to be re-placed as the caret moves, and
107    /// `position_overlays` re-reads the placement it was shown with — so
108    /// without this an affordance follows nothing.
109    pub(crate) overlay_placement_updates:
110        Vec<(crate::widget_id::WidgetId, crate::overlay::OverlayPlacement)>,
111    /// Overlay ids whose `auto_dismiss_after` timer should be paused
112    /// or resumed after the handler returns (`true` = pause, `false`
113    /// = resume). Drained by `WidgetTree::collect_from_ctx` against
114    /// `OverlayManager::pause_auto_dismiss` / `resume_auto_dismiss`,
115    /// after the dismissals in the same drain: a pause aimed at an
116    /// overlay the same handler dismissed is silently dropped. Used
117    /// by `ToastHost` for hover-pause.
118    pub(crate) overlay_pause_requests: Vec<(crate::overlay::OverlayId, bool)>,
119    /// The dismissal scope chosen by the handler, if any. Set by
120    /// `dismiss_all_overlays()` / `dismiss_all_except_hosts()` /
121    /// `dismiss_self_overlay_chain()` / `dismiss_top_overlay()` —
122    /// last setter wins. `None` falls through to draining the
123    /// per-id `overlay_dismissals` vec instead.
124    pub(crate) dismiss_scope: Option<DismissScope>,
125    /// Request to capture (`true`) or release (`false`) a pointer, and which
126    /// one. `None` for the pointer means the one whose sample this handler is
127    /// serving — the default, and what every pre-multi-touch call site means.
128    pub(crate) pointer_capture: Option<(Option<crate::pointer::PointerId>, bool)>,
129    /// The widget currently holding the capture of the pointer being
130    /// dispatched, as the tree knew it when this context was made. Read by
131    /// [`owns_pointer`](EventContext::owns_pointer).
132    pub(crate) pointer_captor: Option<WidgetId>,
133    /// Whether the capture request above came from a **widget handler** rather
134    /// than from framework plumbing.
135    ///
136    /// The distinction is the whole of A4's "explicit capture is an
137    /// arbitration act": the gesture arena and the drag pipeline both capture
138    /// the pointer for their own bookkeeping, and neither is a widget staking
139    /// a claim. Only a `capture_pointer()` written in a handler enrols its
140    /// caller as a [`MemberRole::RawDrag`](crate::gesture::MemberRole::RawDrag)
141    /// competitor.
142    pub(crate) explicit_capture: bool,
143    /// A recognizer on this node produced a gesture that **owns the rest of
144    /// the press** — a drag or a swipe, as opposed to a tap, which completes
145    /// the press rather than claiming it. Set by `dispatch_recognized_gesture`
146    /// and read by `collect_from_ctx`, which decides the pointer's sequence in
147    /// the recognizer's favour.
148    pub(crate) recognized_owning_gesture: bool,
149    /// A press-time [`DragActivation`](teksilo_tokens::DragActivation) chosen
150    /// for this node by its own press handler, overriding its build-time
151    /// declaration for this press alone. Applied by `collect_from_ctx` onto the
152    /// pointer's sequence, which the enrolment walk reads immediately
153    /// afterwards. See [`EventContext::set_drag_activation`].
154    pub(crate) drag_activation_override: Option<teksilo_tokens::DragActivation>,
155    /// Arbitration acts the handler performed on the sequence owning the
156    /// pointer it is serving, in the order it performed them. Applied by
157    /// `WidgetTree::collect_from_ctx` against that sequence.
158    pub(crate) gesture_acts: Vec<GestureAct>,
159    /// The handler asked for its pointer's whole interaction to be revoked.
160    /// Queued by `WidgetTree::collect_from_ctx` onto the cancel funnel, so it
161    /// runs after this dispatch rather than under it. Last reason wins.
162    pub(crate) cancel_pointer_request: Option<crate::pointer::CancelReason>,
163    /// The node whose handler is running, when the dispatcher knows it.
164    /// `None` for a context made outside per-node dispatch (a gesture timer, a
165    /// key-capture callback, an async completion).
166    pub(crate) dispatch_node: Option<WidgetId>,
167    /// The node the router resolved as this dispatch's **target** — the
168    /// innermost node the arena's hit walk accepted. Read by
169    /// [`dispatch_target`](EventContext::dispatch_target).
170    pub(crate) dispatch_target: Option<WidgetId>,
171    /// Delayed overlay requests (request, delay, optional focus target,
172    /// whether to dismiss sibling overlays when it finally shows).
173    pub(crate) delayed_overlay_requests: Vec<(
174        crate::overlay::OverlayRequest,
175        std::time::Duration,
176        Option<crate::widget_id::WidgetId>,
177        bool,
178    )>,
179    /// Timed overlay requests (request, auto-dismiss delay).
180    pub(crate) timed_overlay_requests: Vec<(crate::overlay::OverlayRequest, std::time::Duration)>,
181    /// Reveal overlay requests (request, caller-owned animated progress
182    /// signal, tween duration). The framework shows the overlay, then
183    /// drives `progress` 0 → 1 on show and 1 → 0 on dismiss, deferring
184    /// the actual stack removal until the roll-back tween completes —
185    /// the same deferral the fade path uses, minus the opacity scope.
186    /// The caller applies `progress` however it wants (e.g. an `Unroll`
187    /// width). See [`show_overlay_with_reveal`](EventContext::show_overlay_with_reveal).
188    pub(crate) reveal_overlay_requests: Vec<(
189        crate::overlay::OverlayRequest,
190        crate::signal::Signal<f32>,
191        std::time::Duration,
192    )>,
193    /// Dismiss descendant overlays of the source widget's containing overlay.
194    /// Optionally preserve the subtree rooted at a specific content widget ID.
195    pub(crate) dismiss_descendant_overlays: Vec<Option<crate::widget_id::WidgetId>>,
196    /// Cancel pending delayed overlays by content widget ID.
197    pub(crate) cancel_delayed_overlays: Vec<crate::widget_id::WidgetId>,
198    /// Overlays whose safe triangle should be armed at the current
199    /// pointer position once this handler returns. See
200    /// [`EventContext::arm_overlay_safe_region`].
201    pub(crate) safe_region_arm_requests: Vec<crate::widget_id::WidgetId>,
202    /// Widget IDs that need repainting (cross-widget signal propagation).
203    pub(crate) repaint_requests: Vec<crate::widget_id::WidgetId>,
204    /// Synthetic clicks to dispatch on target widgets after event processing.
205    pub(crate) synthetic_clicks: Vec<crate::widget_id::WidgetId>,
206    /// Focus requests — transfer focus to a specific widget (e.g., overlay content on open).
207    pub(crate) focus_requests: Vec<crate::widget_id::WidgetId>,
208    /// Focus-into requests — move focus to the *first focusable descendant* of
209    /// the given widget, with no fallback to the widget itself when the subtree
210    /// has none. The "dive into this region's content" intent (Enter on a tab
211    /// header → into the tab panel), distinct from `focus_requests` which
212    /// focuses the container itself as a last resort.
213    pub(crate) focus_into_requests: Vec<crate::widget_id::WidgetId>,
214    /// Rect-based "scroll this into view" requests, stated in the **queuing
215    /// widget's own bounds space** — window coordinates everywhere except
216    /// inside a content transform (a `SceneView`'s scene coordinates), which
217    /// the ancestor walk carries outward one space at a time.
218    /// Queued by [`ensure_visible`](EventContext::ensure_visible)
219    /// / [`ensure_visible_with_margin`](EventContext::ensure_visible_with_margin).
220    /// Drained in `collect_from_ctx`, which walks the ancestors of the widget
221    /// whose handler queued the request and dispatches
222    /// [`WidgetEvent::ScrollIntoView`](crate::event::WidgetEvent::ScrollIntoView)
223    /// to every `clips_children` scroll container that doesn't already fully
224    /// contain the rect — the same ancestor-walk the focus path uses, but
225    /// with a caller-supplied rectangle instead of a widget's own bounds
226    /// (so a caret, a virtualized row, or a scrolled-off tab header can be
227    /// revealed even though it is not itself a distinct focused node).
228    pub(crate) scroll_into_view_requests: Vec<ScrollRevealRequest>,
229    /// Widget-id-based "scroll this into view" requests, queued by
230    /// [`ensure_widget_visible`](EventContext::ensure_widget_visible) /
231    /// [`ensure_widget_visible_with_margin`](EventContext::ensure_widget_visible_with_margin).
232    /// Drained in `collect_from_ctx`, which resolves each id to its current
233    /// absolute arena bounds and walks *that widget's* ancestors (the target
234    /// widget itself excluded) dispatching
235    /// [`WidgetEvent::ScrollIntoView`](crate::event::WidgetEvent::ScrollIntoView).
236    /// The convenience form of the rect API for a target that is a real
237    /// mounted, non-virtualized child (a radio tile, a tab header) whose bounds
238    /// the framework already knows — the caller need not compute the rect.
239    pub(crate) scroll_widget_into_view_requests: Vec<(crate::widget_id::WidgetId, f32)>,
240    /// Keyboard-highlight tooltip requests: surface the tooltip of the given
241    /// (menu) item immediately and dismiss the previously-highlighted one.
242    /// Drained after the handler (see `pointer_router::collect_from_ctx`).
243    /// Only the last entry per handler is honoured — a handler sets one
244    /// highlight per key.
245    pub(crate) highlight_tooltip_requests: Vec<crate::widget_id::WidgetId>,
246    /// Drag start request: (source_widget_id, payload, optional_preview_widget).
247    pub(crate) drag_start_request: Option<(
248        crate::widget_id::WidgetId,
249        crate::drag_payload::DragPayload,
250        Option<Box<dyn crate::widget::Widget>>,
251    )>,
252    /// Cancel any active drag session.
253    pub(crate) cancel_drag: bool,
254    /// Whether the drag session active while this context is live was
255    /// started by an external (OS) drag. Read via `drag_is_external()`.
256    /// `false` for hand-constructed contexts and when no drag is active.
257    pub(crate) drag_is_external: bool,
258    /// Replace the tree-level theme. Drained after dispatch; triggers a
259    /// composite-widget rebuild and full repaint.
260    pub(crate) theme_request: Option<crate::styles::Theme>,
261    /// Request that the app follow the OS theme (native / system mode).
262    /// Drained after dispatch; the app switches to `ThemeMode::Native` and
263    /// recomputes the theme from the current OS colours. Parameterless so
264    /// `teksilo-widgets` never needs the app-layer `ThemeMode` enum.
265    pub(crate) follow_system_request: bool,
266    /// Replace the tree-level locale identifier. Drained after dispatch;
267    /// triggers a composite-widget rebuild and full repaint.
268    pub(crate) locale_request: Option<String>,
269    /// Set the user-controlled text-scale factor. Drained after dispatch and
270    /// fanned out to every window; grows all text without a rebuild.
271    pub(crate) text_scale_request: Option<f32>,
272    /// Set by `request_frame()`; consumed by the event dispatcher which
273    /// forwards it to `WidgetTree::request_frame()` so the next layout
274    /// pass advances the per-frame tick signal.
275    pub(crate) frame_requested: bool,
276    /// Optional reference to the tree's app-state registry, so handlers
277    /// can look up application-scoped values via `app_state::<T>()`.
278    /// Populated by the dispatcher before running each handler; `None`
279    /// for hand-constructed contexts in tests.
280    pub(crate) app_context: Option<std::rc::Rc<crate::event_source::TreeAppContext>>,
281    /// App-level window-ops sink. Injected by the dispatcher so
282    /// handlers can reach the multi-window API (`open_window`,
283    /// `focus_window`, …) synchronously. For `EventContext`
284    /// instances constructed outside a dispatch (standalone trees,
285    /// tests) this is `None` and the multi-window methods no-op /
286    /// return `None`.
287    pub(crate) window_ops: Option<&'ops mut dyn crate::window::WindowOps>,
288    /// [`WindowState`](crate::window::WindowState) for the window
289    /// this tree belongs to. Cloned from the tree at construction.
290    /// `None` for standalone trees.
291    pub(crate) current_window: Option<crate::window::WindowState>,
292    /// Snapshot of the tree's occlusion-aware window-active state
293    /// (`focused AND not occluded`) at construction time. Distinct from
294    /// `current_window.focused()` (raw OS focus, no occlusion). Read by
295    /// [`window_active`](Self::window_active). Defaults `true` (matches the
296    /// tree's initial value) for standalone / test contexts.
297    pub(crate) tree_window_active: bool,
298    /// Last `PointerMove` position observed by the tree. Snapshotted
299    /// at handler-invocation time so widgets that don't see the live
300    /// pointer event (e.g. an `on_hover` callback that fires on the
301    /// boundary edge) can still query "where is the cursor right
302    /// now". Read by the safe-triangle submenu hover gate.
303    pub(crate) tree_pointer_position: Option<teksilo_canvas::Point>,
304    /// True when the in-flight pointer press's hit target is a strict
305    /// descendant of the widget whose handler is currently running and that
306    /// descendant carries its own tap gesture (a chevron, checkbox, inline
307    /// button). Set per-node by the dispatcher for `PointerDown`/`PointerUp`.
308    /// Read via [`press_claimed_by_interactive_child`](Self::press_claimed_by_interactive_child).
309    pub(crate) press_claimed_by_interactive_child: bool,
310    /// Per-content-widget overlay bounds — and armed safe-triangle apex,
311    /// when the overlay has one — snapshotted at handler invocation. A
312    /// flat vec is fine: open overlays are typically 0–3 per tree. Read
313    /// by [`EventContext::overlay_bounds_for_content`] and
314    /// [`EventContext::overlay_safe_region_armed`].
315    pub(crate) overlay_bounds_snapshot: Vec<(
316        WidgetId,
317        teksilo_canvas::Rect,
318        Option<teksilo_canvas::Point>,
319    )>,
320    /// The widget holding focus when this batch began. Part of the same
321    /// per-dispatch snapshot as the two above, and read by
322    /// [`focused`](EventContext::focused).
323    pub(crate) focused_widget: Option<WidgetId>,
324    /// Intents queued by handlers via `send_intent`. Drained by the
325    /// tree after event dispatch and routed source-widget → root.
326    pub(crate) pending_intents: Vec<crate::intent::Intent>,
327    /// The dispatcher sets this to the appropriate
328    /// [`IntentSource`](crate::telemetry::IntentSource) before
329    /// invoking a typed handler (menu select → `Menu`, AccessKit
330    /// action → `Accessibility`, on_tap / button activation →
331    /// `Handler`, …). `send_intent` reads it and stamps the intent
332    /// before queuing. `None` outside a managed handler — bare
333    /// programmatic sends keep their `Intent::source` value
334    /// (default `Programmatic`).
335    pub(crate) current_source: Option<crate::telemetry::IntentSource>,
336    /// Key-capture callback armed via `ctx.begin_key_capture(...)`.
337    /// The callback + its shared slot are installed on the tree by
338    /// `collect_from_ctx`. Only one per ctx; the last caller wins.
339    pub(crate) pending_key_capture: Option<crate::shortcut::KeyCaptureSlot>,
340    /// Set to request cancellation of any armed key capture.
341    pub(crate) cancel_key_capture: bool,
342    /// Deferred mutations to the tree's [`ShortcutRegistry`](crate::shortcut::ShortcutRegistry),
343    /// typically issued by settings-UI buttons to rebind or clear
344    /// overrides. Applied in `collect_from_ctx` after the handler
345    /// returns.
346    pub(crate) pending_shortcut_mutations: Vec<ShortcutMutation>,
347    /// Requests that the app-level event loop close the window this
348    /// tree belongs to. Drained after dispatch via
349    /// `WidgetTree::take_close_window_request`. Routed through the
350    /// window's close guard (if any) — see
351    /// [`WindowConfig::on_close_requested`](crate::window::WindowConfig::on_close_requested).
352    pub(crate) close_window_requested: bool,
353    /// Like [`close_window_requested`](Self::close_window_requested), but
354    /// **bypasses** the window's close guard. Set by
355    /// [`close_window_forced`](Self::close_window_forced). Drained after
356    /// dispatch via `WidgetTree::take_force_close_request`. The escape
357    /// hatch a confirmation dialog uses once the user confirms.
358    pub(crate) force_close_requested: bool,
359    /// Set by [`request_accessibility_update`](EventContext::request_accessibility_update);
360    /// drained in `collect_from_ctx` to set `WidgetTree::a11y_dirty`, forcing the
361    /// next `sync_accessibility` to re-walk the AccessKit tree. The general lever for a
362    /// composing widget that restructured its subtree in a way that changes the AT tree
363    /// (relayout alone no longer re-walks AT).
364    pub(crate) request_a11y_update: bool,
365    /// Set by [`request_soft_keyboard`](EventContext::request_soft_keyboard);
366    /// drained in `collect_from_ctx` onto the tree, from where the app layer
367    /// takes it once per dispatch — after the IME-allowance reconcile, which
368    /// is the only place that knows whether re-asserting would cancel a live
369    /// composition.
370    pub(crate) soft_keyboard_request: Option<bool>,
371    /// Messages queued by [`announce`](EventContext::announce) /
372    /// [`announce_with`](EventContext::announce_with), drained into the tree's
373    /// own live regions by `collect_from_ctx`. See [`crate::announcer`].
374    pub(crate) announcements: Vec<(String, crate::announcer::Politeness)>,
375    /// Layout direction (LTR/RTL) of the hosting tree, snapshotted at
376    /// handler-invocation time by `make_event_context`. Read via
377    /// [`is_rtl`](EventContext::is_rtl) so pointer / keyboard / drag
378    /// handlers can mirror their x-axis logic live — a runtime locale
379    /// switch dirties the tree but does **not** rebuild, so direction
380    /// must be read here rather than captured at `build()` time.
381    /// Defaults to `LeftToRight` for hand-constructed (test) contexts.
382    pub(crate) layout_direction: crate::environment::LayoutDirection,
383    /// What the tree knows about the sample being dispatched: which pointer
384    /// produced it, where it was, and — for a scroll — its phase and source.
385    /// Snapshotted by `make_event_context` from the tree's in-flight sample.
386    /// Holds its default (a mouse at the epoch) for hand-constructed contexts
387    /// and for handlers run outside a pointer dispatch (a timer, an
388    /// accessibility action).
389    pub(crate) input: crate::pointer::InputSnapshot,
390    /// The frozen [`TouchAction`] for the gesture being handled. Populated by
391    /// `make_event_context` from the pressed pointer's sequence; defaults to
392    /// [`TouchAction::AUTO`] for a hand-constructed context and for a handler
393    /// running outside a press — see
394    /// [`touch_action`](EventContext::touch_action) and
395    /// `crate::pointer::touch_action`.
396    pub(crate) touch_action: TouchAction,
397    /// The framework press held by the pointer being dispatched, as the router
398    /// tracks it: `(inside, pending)`. `None` when that pointer holds no press
399    /// — every handler outside a press, and every hand-constructed context.
400    /// Read by [`is_pressed`](EventContext::is_pressed) and its two siblings.
401    pub(crate) press: Option<(bool, bool)>,
402    /// Debug-only WCAG 3.2.1 guard: `Some(flag)` where `flag` is set while a
403    /// focus-change dispatch is running. `open_window` / `focus_window` warn if
404    /// invoked while it reads `true` (a focus handler changing context). `None`
405    /// for hand-constructed (test) contexts.
406    pub(crate) in_focus_dispatch: Option<std::rc::Rc<std::cell::Cell<bool>>>,
407}
408
409/// One arbitration act a handler performed on its pointer's sequence.
410///
411/// Queued on the context and applied in order by
412/// `WidgetTree::collect_from_ctx`, so a handler that claims and then rejects
413/// leaves the sequence in the state its last word describes.
414#[derive(Debug, Clone, Copy, PartialEq, Eq)]
415pub(crate) enum GestureAct {
416    /// [`EventContext::claim_gesture`].
417    Claim,
418    /// [`EventContext::reject_gesture`].
419    Reject,
420    /// [`EventContext::hold_gesture`].
421    Hold,
422    /// [`EventContext::release_gesture`].
423    Release,
424}
425
426/// Deferred edit to the tree's shortcut registry, queued on an
427/// `EventContext` and applied in `collect_from_ctx`.
428#[derive(Debug, Clone)]
429pub(crate) enum ShortcutMutation {
430    RebindPrimary {
431        id: String,
432        keystroke: Option<crate::shortcut::KeyStroke>,
433    },
434    RebindSecondary {
435        id: String,
436        keystroke: Option<crate::shortcut::KeyStroke>,
437    },
438    ClearOverride {
439        id: String,
440    },
441}
442
443/// A structural change to the widget tree, deferred until after event dispatch.
444pub(crate) enum TreeMutation {
445    SetDormant(WidgetId),
446    Activate(WidgetId),
447    Destroy(WidgetId),
448    /// Typed mutable access to a mounted widget, applied in
449    /// `apply_tree_mutations` where `&mut arena` is live. The boxed closure
450    /// downcasts the node's `as_any_mut()` to the requested concrete type;
451    /// `dirty` selects the post-mutation re-render level.
452    WithWidgetMut {
453        id: WidgetId,
454        dirty: crate::binding::BindingLevel,
455        apply: Box<dyn FnOnce(&mut dyn std::any::Any)>,
456    },
457    /// Re-run one widget's `build()` **now**, inside `apply_tree_mutations`,
458    /// rather than marking it for the next layout pass. See
459    /// [`EventContext::materialize_now`].
460    MaterializeNow(WidgetId),
461    /// `Space` on a data view's focused row: run the keyboard-toggle action
462    /// published inside `row`, or `fallback` when the row publishes none.
463    ///
464    /// Deferred rather than resolved in the handler because finding the action
465    /// means walking the row's subtree, and `EventContext` is a command buffer
466    /// with no view of the arena. Carrying the fallback keeps the decision in
467    /// one place: whether a row has a checkbox is a fact about the tree, not
468    /// something the key handler can know.
469    RowSpaceActivate {
470        row: WidgetId,
471        fallback: std::rc::Rc<dyn Fn(&mut EventContext)>,
472    },
473}
474
475// Manual `Debug`: the `WithWidgetMut` closure is not `Debug`.
476impl std::fmt::Debug for TreeMutation {
477    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
478        match self {
479            Self::SetDormant(id) => f.debug_tuple("SetDormant").field(id).finish(),
480            Self::Activate(id) => f.debug_tuple("Activate").field(id).finish(),
481            Self::MaterializeNow(id) => f.debug_tuple("MaterializeNow").field(id).finish(),
482            Self::Destroy(id) => f.debug_tuple("Destroy").field(id).finish(),
483            Self::WithWidgetMut { id, dirty, .. } => f
484                .debug_struct("WithWidgetMut")
485                .field("id", id)
486                .field("dirty", dirty)
487                .finish_non_exhaustive(),
488            Self::RowSpaceActivate { row, .. } => f
489                .debug_struct("RowSpaceActivate")
490                .field("row", row)
491                .finish_non_exhaustive(),
492        }
493    }
494}
495
496impl<'ops> EventContext<'ops> {
497    pub(crate) fn new() -> Self {
498        Self {
499            cursor_request: None,
500            declared_cursor_request: None,
501            tree_mutations: Vec::new(),
502            idle_callbacks: Vec::new(),
503            modal_requests: Vec::new(),
504            dismiss_modal: false,
505            overlay_requests: Vec::new(),
506            overlay_dismissals: Vec::new(),
507            overlay_content_dismissals: Vec::new(),
508            overlay_band_requests: Vec::new(),
509            overlay_placement_updates: Vec::new(),
510            overlay_pause_requests: Vec::new(),
511            dismiss_scope: None,
512            pointer_capture: None,
513            pointer_captor: None,
514            dispatch_node: None,
515            dispatch_target: None,
516            delayed_overlay_requests: Vec::new(),
517            timed_overlay_requests: Vec::new(),
518            reveal_overlay_requests: Vec::new(),
519            dismiss_descendant_overlays: Vec::new(),
520            cancel_delayed_overlays: Vec::new(),
521            safe_region_arm_requests: Vec::new(),
522            repaint_requests: Vec::new(),
523            synthetic_clicks: Vec::new(),
524            focus_requests: Vec::new(),
525            focus_into_requests: Vec::new(),
526            scroll_into_view_requests: Vec::new(),
527            scroll_widget_into_view_requests: Vec::new(),
528            highlight_tooltip_requests: Vec::new(),
529            drag_start_request: None,
530            cancel_drag: false,
531            drag_is_external: false,
532            theme_request: None,
533            follow_system_request: false,
534            locale_request: None,
535            text_scale_request: None,
536            frame_requested: false,
537            app_context: None,
538            pending_intents: Vec::new(),
539            current_source: None,
540            pending_key_capture: None,
541            cancel_key_capture: false,
542            pending_shortcut_mutations: Vec::new(),
543            close_window_requested: false,
544            force_close_requested: false,
545            request_a11y_update: false,
546            soft_keyboard_request: None,
547            announcements: Vec::new(),
548            window_ops: None,
549            current_window: None,
550            tree_window_active: true,
551            tree_pointer_position: None,
552            press_claimed_by_interactive_child: false,
553            overlay_bounds_snapshot: Vec::new(),
554            focused_widget: None,
555            layout_direction: crate::environment::LayoutDirection::LeftToRight,
556            input: crate::pointer::InputSnapshot::default(),
557            touch_action: TouchAction::AUTO,
558            press: None,
559            in_focus_dispatch: None,
560            explicit_capture: false,
561            recognized_owning_gesture: false,
562            drag_activation_override: None,
563            gesture_acts: Vec::new(),
564            cancel_pointer_request: None,
565        }
566    }
567
568    /// Record the [`TouchAction`] frozen at press for the sequence owning the
569    /// pointer being dispatched. Called by `make_event_context`.
570    pub(crate) fn with_touch_action(mut self, action: TouchAction) -> Self {
571        self.touch_action = action;
572        self
573    }
574
575    /// Record the framework press held by the pointer being dispatched, as
576    /// `(inside, pending)`. Called by `make_event_context`.
577    pub(crate) fn with_press(mut self, press: Option<(bool, bool)>) -> Self {
578        self.press = press;
579        self
580    }
581
582    /// Whether the pointer being dispatched holds a press whose visual is
583    /// showing — inside its tap boundary and past any press-feedback delay.
584    ///
585    /// The framework already drives the pressed node's own
586    /// [`pressed_signal`](crate::BuildContext::pressed_signal) from the same
587    /// state; this is for a handler that has to *branch* on the press rather
588    /// than paint it. `false` outside a press.
589    pub fn is_pressed(&self) -> bool {
590        matches!(self.press, Some((true, false)))
591    }
592
593    /// Whether the pointer being dispatched holds a press that has not left
594    /// its tap boundary. Unlike [`is_pressed`](Self::is_pressed) this is still
595    /// true during the press-feedback delay: the press is real, only its
596    /// visual is being withheld.
597    pub fn press_is_inside(&self) -> bool {
598        matches!(self.press, Some((true, _)))
599    }
600
601    /// Whether the pointer being dispatched holds a press whose feedback delay
602    /// has not elapsed — the press is inside a pan claimant and the framework
603    /// is waiting to see whether it becomes a scroll.
604    pub fn press_pending(&self) -> bool {
605        matches!(self.press, Some((_, true)))
606    }
607
608    /// Record what the tree knows about the sample being dispatched. Called by
609    /// `make_event_context` once per event batch.
610    pub(crate) fn with_input_snapshot(mut self, input: crate::pointer::InputSnapshot) -> Self {
611        self.input = input;
612        self
613    }
614
615    /// Record who holds the capture of the pointer being dispatched, so
616    /// [`owns_pointer`](Self::owns_pointer) can answer without a tree lookup.
617    pub(crate) fn with_pointer_captor(mut self, captor: Option<WidgetId>) -> Self {
618        self.pointer_captor = captor;
619        self
620    }
621
622    /// Record the node the arena picked for this event — the *target*, which is
623    /// not in general the node whose handler is running (a preview fires on
624    /// every strict ancestor of it).
625    pub(crate) fn with_dispatch_target(mut self, target: WidgetId) -> Self {
626        self.dispatch_target = Some(target);
627        self
628    }
629
630    /// Record which node's handler is about to run.
631    pub(crate) fn with_dispatch_node(mut self, node: WidgetId) -> Self {
632        self.dispatch_node = Some(node);
633        self
634    }
635
636    /// The pointer that produced the event being handled.
637    ///
638    /// Two dispatches have a pointer without having a sample, and both report
639    /// it: a gesture the timer recognised — a hold — reports the **contact that
640    /// held**, and a drag-and-drop handler (`on_drag_hover` / `on_drag_tick` /
641    /// `on_drag_leave` / `on_drop`) reports the pointer **that started the
642    /// drag**, which is what makes it right inside a tick fired from a layout
643    /// pass or an OS drag phase delivered from a platform thread. Outside any
644    /// pointer, scroll, gesture or drag dispatch — an assistive-technology
645    /// action, a hand-constructed test context — this is the mouse at the tree
646    /// epoch, which is the same answer every such handler got before pointers
647    /// were distinguishable.
648    pub fn pointer(&self) -> crate::pointer::PointerInfo {
649        self.input.pointer
650    }
651
652    /// What kind of device is pointing: mouse, finger, stylus.
653    ///
654    /// The one question most handlers actually need — it is what decides
655    /// whether a hover affordance is reachable, whether a target needs slop,
656    /// and which gesture profile governs.
657    pub fn pointer_kind(&self) -> teksilo_tokens::PointerKind {
658        self.input.pointer.kind
659    }
660
661    /// Where the pointer was, in window-logical coordinates, when the event
662    /// being handled was produced.
663    ///
664    /// `None` for an event that carries no position — a keyboard-driven
665    /// scroll, a wheel notch (which routes by hover rather than by position),
666    /// anything dispatched outside a pointer sample. Distinct from
667    /// [`tree_pointer_position`](Self::tree_pointer_position), which reports
668    /// where the pointer is *at this instant* regardless of what is being
669    /// dispatched.
670    pub fn pointer_position(&self) -> Option<teksilo_canvas::Point> {
671        self.input.position
672    }
673
674    /// The positions the OS batched into the packet being dispatched, oldest
675    /// first and **excluding** the packet's own
676    /// ([`pointer_position`](Self::pointer_position), which is the newest).
677    ///
678    /// A backend whose device outruns the window's message rate hands over one
679    /// sample per *message* and puts the intermediate positions here, each with
680    /// the [`PointerAxes`](crate::pointer::PointerAxes) it was sampled at and
681    /// its own [`EventTime`](crate::pointer::EventTime). A surface that must
682    /// see every position a stylus produced — an ink tool is the case this
683    /// exists for — iterates these and *then* handles
684    /// [`pointer_position`](Self::pointer_position), and is correct whether or
685    /// not the backend batches, because a backend that does not returns an
686    /// empty slice.
687    ///
688    /// **Window**-logical coordinates, like
689    /// [`WidgetEvent::Scroll`](crate::event::WidgetEvent::Scroll)'s `window_position` and
690    /// for the same reason: a batch has no single widget to localise against.
691    /// A handler working in its own space converts at the use site.
692    ///
693    /// Empty on every dispatch that is not a pointer sample — a gesture the
694    /// timer recognised, a drag-and-drop tick, an assistive-technology action.
695    /// Those batched nothing, and reporting whichever sample arrived last would
696    /// attribute its positions to a gesture that did not produce them.
697    pub fn coalesced(&self) -> &[crate::pointer::CoalescedSample] {
698        &self.input.coalesced
699    }
700
701    /// Where in a continuous scroll gesture the event being handled sits.
702    ///
703    /// [`ScrollPhase::Discrete`](crate::pointer::ScrollPhase::Discrete) — a
704    /// self-contained wheel notch — for everything that is not a phased
705    /// gesture, which is every scroll Teksilo produced before the touch
706    /// programme.
707    pub fn scroll_phase(&self) -> crate::pointer::ScrollPhase {
708        self.input.scroll_phase
709    }
710
711    /// What produced the scroll being handled: a notched wheel, a precision
712    /// trackpad, a synthesised touch pan, or the app itself.
713    pub fn scroll_source(&self) -> crate::pointer::ScrollSource {
714        self.input.scroll_source
715    }
716
717    /// The [`TouchAction`] governing the gesture being handled.
718    ///
719    /// The value is **frozen at press** for the whole gesture's lifetime: the
720    /// router computes it once, from `WidgetTree::effective_touch_action` of
721    /// the pressed target, and stores it on that pointer's
722    /// [`PointerSequence`](crate::gesture::PointerSequence), so a handler never
723    /// re-reads a subtree that may have rebuilt mid-gesture.
724    ///
725    /// [`TouchAction::AUTO`] — the neutral value — outside a press, and for a
726    /// hand-constructed context. A mouse never consults this at all. See
727    /// `crate::pointer::touch_action`.
728    pub fn touch_action(&self) -> TouchAction {
729        self.touch_action
730    }
731
732    /// Snapshot the hosting tree's layout direction. Called by
733    /// `make_event_context` once per event batch so x-axis handlers
734    /// (resize, drag-reorder, arrow-key navigation) can mirror under
735    /// RTL without a rebuild.
736    pub(crate) fn with_layout_direction(
737        mut self,
738        direction: crate::environment::LayoutDirection,
739    ) -> Self {
740        self.layout_direction = direction;
741        self
742    }
743
744    /// Layout direction of the hosting tree at dispatch time.
745    pub fn layout_direction(&self) -> crate::environment::LayoutDirection {
746        self.layout_direction
747    }
748
749    /// Whether the hosting tree is laid out right-to-left. Mirrors
750    /// [`LayoutContext::is_rtl`](crate::widget::LayoutContext::is_rtl)
751    /// for the event-dispatch side.
752    pub fn is_rtl(&self) -> bool {
753        self.layout_direction == crate::environment::LayoutDirection::RightToLeft
754    }
755
756    /// The widget that held focus when this event batch began.
757    ///
758    /// A snapshot, not a live read: it answers what the tree's focus was at
759    /// dispatch time, so a handler that has already called
760    /// [`request_focus`](EventContext::request_focus) still sees the old
761    /// value. That is the useful reading for a handler deciding *whether* to
762    /// act on the focused widget.
763    ///
764    /// `None` when nothing is focused, and also for an `EventContext` built
765    /// outside `WidgetTree::make_event_context`, which is what a hand-made
766    /// test context is. Treat it as `None`-safe, like the other snapshots.
767    ///
768    /// The reason this exists: a widget-scoped shortcut fires before the
769    /// focused widget sees the key, so a container that binds a key which its
770    /// own children also handle has no other way to yield to them.
771    /// `MessageBox` is the case that asked for it, where Enter is bound to the
772    /// default button and must not answer for the button the user has actually
773    /// tabbed to.
774    pub fn focused(&self) -> Option<WidgetId> {
775        self.focused_widget
776    }
777
778    /// Attach a per-dispatch snapshot of read-only tree query state
779    /// (current pointer position, overlay bounds, focus). Called by
780    /// `WidgetTree::make_event_context` once per event batch. Test
781    /// `EventContext`s that don't go through that path stay with
782    /// empty snapshots — handlers must treat every read as `None`-
783    /// safe.
784    pub(crate) fn with_query_snapshot(
785        mut self,
786        pointer: Option<teksilo_canvas::Point>,
787        overlays: Vec<(
788            WidgetId,
789            teksilo_canvas::Rect,
790            Option<teksilo_canvas::Point>,
791        )>,
792        focused: Option<WidgetId>,
793    ) -> Self {
794        self.tree_pointer_position = pointer;
795        self.overlay_bounds_snapshot = overlays;
796        self.focused_widget = focused;
797        self
798    }
799
800    /// Attach the app-level window-ops sink and the hosting tree's
801    /// [`WindowState`](crate::window::WindowState). Called by the
802    /// dispatcher once per event batch so handlers can reach the
803    /// multi-window API synchronously.
804    pub(crate) fn with_window_context(
805        mut self,
806        ops: &'ops mut dyn crate::window::WindowOps,
807        current_window: Option<crate::window::WindowState>,
808    ) -> Self {
809        self.window_ops = Some(ops);
810        self.current_window = current_window;
811        self
812    }
813
814    /// Snapshot the tree's occlusion-aware window-active state. Called by
815    /// `make_event_context` once per event batch so handlers can read
816    /// [`window_active`](Self::window_active).
817    pub(crate) fn with_window_active(mut self, active: bool) -> Self {
818        self.tree_window_active = active;
819        self
820    }
821
822    /// Attach the tree's shared "inside focus dispatch" flag (WCAG 3.2.1
823    /// debug guard). See [`EventContext::open_window`].
824    pub(crate) fn with_focus_dispatch_flag(
825        mut self,
826        flag: std::rc::Rc<std::cell::Cell<bool>>,
827    ) -> Self {
828        self.in_focus_dispatch = Some(flag);
829        self
830    }
831
832    /// Debug-only: warn (once per call) if a context change is being made from
833    /// inside a focus-change dispatch — a WCAG 3.2.1 (On Focus) anti-pattern.
834    /// Compiled out entirely in release builds.
835    #[inline]
836    fn warn_if_context_change_in_focus_dispatch(&self, what: &str) {
837        #[cfg(debug_assertions)]
838        if self.in_focus_dispatch.as_ref().is_some_and(|f| f.get()) {
839            eprintln!(
840                "[teksilo a11y] WCAG 3.2.1 (On Focus): `{what}` was called from \
841                 inside an on_focus handler. Changing context (opening/focusing a \
842                 window, navigating) merely because a control received focus \
843                 surprises keyboard users tabbing through the UI. Move this to an \
844                 explicit activation handler (on_tap / on_activate / a shortcut)."
845            );
846        }
847        let _ = what;
848    }
849
850    /// Attach the tree's app-state registry so handlers can look up
851    /// application-scoped values (`ClipboardHandle`, `SharedTypesetter`,
852    /// …). Called by the dispatcher once per event batch.
853    pub(crate) fn with_app_context(
854        mut self,
855        ctx: std::rc::Rc<crate::event_source::TreeAppContext>,
856    ) -> Self {
857        self.app_context = Some(ctx);
858        self
859    }
860
861    /// Record whether the drag session active while this context is live
862    /// originated from an external (OS) drag. Set by `make_event_context`.
863    pub(crate) fn with_drag_external(mut self, is_external: bool) -> Self {
864        self.drag_is_external = is_external;
865        self
866    }
867
868    /// Whether a drag is currently in flight that was started by an external
869    /// (OS) drag-and-drop (files / text / URLs from another application),
870    /// rather than by an in-app `start_drag`. Useful in `on_drag_leave` /
871    /// `on_drag_tick` handlers, which don't receive the payload directly;
872    /// in `on_drag_hover` / `on_drop` prefer `payload.is_external()`.
873    pub fn drag_is_external(&self) -> bool {
874        self.drag_is_external
875    }
876
877    /// Look up an application-scoped value by type. Mirrors
878    /// `BuildContext::app_state`. Returns `None` when the handler was
879    /// invoked without a registry (hand-constructed `EventContext` in
880    /// tests, or when no value of that type was registered).
881    pub fn app_state<T: 'static>(&self) -> Option<&T> {
882        self.app_context
883            .as_ref()
884            .and_then(|ctx| ctx.app_state::<T>())
885    }
886
887    /// Borrow the [`AppEventPoster`](crate::AppEventPoster) installed
888    /// by the framework. Used by integrations that need to post
889    /// typed payloads back to the UI loop from a worker thread
890    /// (`teksilo_platform::file_dialog`'s `RfdAsyncBackend`, future
891    /// async-result features). Returns `None` for hand-constructed
892    /// `EventContext`s in tests.
893    pub fn poster(&self) -> Option<&std::sync::Arc<dyn crate::AppEventPoster>> {
894        self.app_context.as_ref().and_then(|ctx| ctx.poster())
895    }
896
897    /// Ask the tree to pump one more frame after this handler returns.
898    /// Use from event handlers that kick off per-frame work (pending
899    /// document events to drain, drag-select auto-scroll, caret blink
900    /// restart on focus). See `WidgetTree::request_frame` for the
901    /// draw-when-needed contract.
902    pub fn request_frame(&mut self) {
903        self.frame_requested = true;
904    }
905
906    /// Dispatch an [`Intent`](crate::intent::Intent) as if the source
907    /// widget pressed its keyboard shortcut. The framework walks
908    /// source-widget → root after the current handler returns,
909    /// invoking any matching [`Action`](crate::action::Action) it
910    /// finds. Unmatched intents are silently dropped.
911    ///
912    /// The intent's `source` is overridden by the dispatcher's
913    /// current handler-source label (`current_source`) when one is
914    /// active. This is how the framework distinguishes
915    /// `IntentSource::Handler` (button taps, generic on_tap) from
916    /// `IntentSource::Menu`, `IntentSource::Accessibility`, etc.
917    /// Programmatic callers outside any handler pass through with
918    /// `IntentSource::Programmatic` (the default).
919    pub fn send_intent(&mut self, intent: impl Into<crate::intent::Intent>) {
920        let mut intent: crate::intent::Intent = intent.into();
921        if let Some(src) = self.current_source {
922            intent.source = src;
923        }
924        self.pending_intents.push(intent);
925    }
926
927    /// Run a closure with the given `IntentSource` active. Any
928    /// `ctx.send_intent(...)` issued from within the closure will
929    /// be tagged with this source instead of the dispatcher's
930    /// default (`Handler` / `Shortcut` / `Accessibility`).
931    ///
932    /// The previous source is restored after the closure returns.
933    /// Panic during the closure unwinds the dispatcher's whole
934    /// frame, so the EventContext is destroyed before the next
935    /// dispatch — no need for a panic-safe drop guard.
936    ///
937    /// Used by framework widgets that want a more specific source
938    /// label than the default — `MenuItem` wraps its activation
939    /// handler to emit `IntentSource::Menu`, etc.
940    pub fn with_intent_source<R>(
941        &mut self,
942        source: crate::telemetry::IntentSource,
943        f: impl FnOnce(&mut Self) -> R,
944    ) -> R {
945        let prev = self.current_source.replace(source);
946        let r = f(self);
947        self.current_source = prev;
948        r
949    }
950
951    /// Arm a one-shot key-capture callback, returning a
952    /// [`CaptureHandle`](crate::shortcut::CaptureHandle) whose `Drop`
953    /// cancels the capture if it hasn't fired yet. The next `KeyDown`
954    /// bypasses shortcut resolution and invokes the callback with:
955    /// - the captured [`KeyStroke`](crate::shortcut::KeyStroke)
956    /// - mutable access to the registry (rebinds in-place)
957    /// - a mutable [`EventContext`] (emit commands, send intents,
958    ///   dismiss overlays, …)
959    ///
960    /// The handle must be stored somewhere with an appropriate
961    /// lifetime (typically in the calling widget's state) or the
962    /// capture will be cancelled immediately when the returned
963    /// handle drops at end of scope.
964    pub fn begin_key_capture(
965        &mut self,
966        callback: impl FnOnce(
967            crate::shortcut::KeyStroke,
968            &mut crate::shortcut::ShortcutRegistry,
969            &mut EventContext,
970        ) + 'static,
971    ) -> crate::shortcut::CaptureHandle {
972        let slot: crate::shortcut::KeyCaptureSlot =
973            std::rc::Rc::new(std::cell::RefCell::new(Some(Box::new(callback))));
974        self.pending_key_capture = Some(slot.clone());
975        self.cancel_key_capture = false;
976        crate::shortcut::CaptureHandle::new(slot)
977    }
978
979    /// Cancel any key capture armed earlier in this handler or via
980    /// `WidgetTree::begin_key_capture` before the handler ran.
981    pub fn cancel_key_capture(&mut self) {
982        self.pending_key_capture = None;
983        self.cancel_key_capture = true;
984    }
985
986    /// Queue a deferred rebind of the primary keystroke for the
987    /// registered shortcut with the given id. Applied by the tree
988    /// after the current handler returns. Use `None` to explicitly
989    /// unbind the slot.
990    pub fn rebind_shortcut_primary(
991        &mut self,
992        id: impl Into<String>,
993        keystroke: Option<crate::shortcut::KeyStroke>,
994    ) {
995        self.pending_shortcut_mutations
996            .push(ShortcutMutation::RebindPrimary {
997                id: id.into(),
998                keystroke,
999            });
1000    }
1001
1002    /// Queue a deferred rebind of the secondary keystroke for the
1003    /// registered shortcut with the given id.
1004    pub fn rebind_shortcut_secondary(
1005        &mut self,
1006        id: impl Into<String>,
1007        keystroke: Option<crate::shortcut::KeyStroke>,
1008    ) {
1009        self.pending_shortcut_mutations
1010            .push(ShortcutMutation::RebindSecondary {
1011                id: id.into(),
1012                keystroke,
1013            });
1014    }
1015
1016    /// Queue a deferred clear of any user override for the given
1017    /// shortcut id, restoring its declared defaults.
1018    pub fn clear_shortcut_override(&mut self, id: impl Into<String>) {
1019        self.pending_shortcut_mutations
1020            .push(ShortcutMutation::ClearOverride { id: id.into() });
1021    }
1022
1023    /// Request that the application close the window this tree
1024    /// belongs to. Drained by the app event loop after the handler
1025    /// returns. Typical use: title-bar close button handlers.
1026    ///
1027    /// This is a *guarded* close: if the window declared a close guard
1028    /// via
1029    /// [`WindowConfig::on_close_requested`](crate::window::WindowConfig::on_close_requested)
1030    /// or [`can_close`](crate::window::WindowConfig::can_close), that
1031    /// guard runs first and may veto the close. To skip the guard (e.g.
1032    /// from the confirmation dialog the guard itself opened), use
1033    /// [`close_window_forced`](Self::close_window_forced).
1034    pub fn close_window(&mut self) {
1035        self.close_window_requested = true;
1036    }
1037
1038    /// Request that the application close this tree's window
1039    /// **unconditionally**, bypassing any close guard declared via
1040    /// [`WindowConfig::on_close_requested`](crate::window::WindowConfig::on_close_requested)
1041    /// / [`can_close`](crate::window::WindowConfig::can_close).
1042    ///
1043    /// This is the second half of the veto-then-reissue pattern: the
1044    /// guard returns [`CloseResponse::Veto`](crate::window::CloseResponse::Veto)
1045    /// and opens a confirmation dialog; the dialog's "close anyway"
1046    /// button calls `close_window_forced` so the window actually closes
1047    /// without re-triggering the guard.
1048    pub fn close_window_forced(&mut self) {
1049        self.force_close_requested = true;
1050    }
1051
1052    // -------------------- Multi-window API --------------------
1053
1054    /// Cursor position at the moment this handler was invoked. `None`
1055    /// when no `PointerMove` has reached the tree yet, or when the
1056    /// context was constructed without a tree-side snapshot (e.g.
1057    /// hand-built `EventContext`s in tests). Used by the safe-triangle
1058    /// submenu hover gate.
1059    pub fn tree_pointer_position(&self) -> Option<teksilo_canvas::Point> {
1060        self.tree_pointer_position
1061    }
1062
1063    /// True when the in-flight pointer press's hit target is a strict
1064    /// descendant of THIS handler's widget that carries its own tap gesture
1065    /// (chevron, checkbox, inline button). A row/container that selects on
1066    /// press should early-return `EventResponse::Ignored` when this is set, so
1067    /// the press belongs to the inner control, not the row. Only meaningful
1068    /// inside `on_pointer_event` handlers for `PointerDown`/`PointerUp`.
1069    pub fn press_claimed_by_interactive_child(&self) -> bool {
1070        self.press_claimed_by_interactive_child
1071    }
1072
1073    /// The node this dispatch is **addressed to** — the innermost node the
1074    /// arena's hit walk accepted for this pointer sample, with
1075    /// [`hit_transparent`](crate::widget_builder::HandlerSet::hit_transparent),
1076    /// [`Widget::hit_shape`](crate::widget::Widget::hit_shape),
1077    /// [`Widget::accepts_child_hit`](crate::widget::Widget::accepts_child_hit)
1078    /// and `event_pass_through` all already applied.
1079    ///
1080    /// The point of it is the **preview** pass. `on_pointer_event` fires on
1081    /// every strict ancestor of the target during preview and on the target
1082    /// itself during the bubble, so an ancestor handler cannot otherwise tell
1083    /// "a descendant won the walk" from "I am the one that was hit". A widget
1084    /// that owns a second picking system over the same area needs exactly that
1085    /// distinction, to know whether to yield: comparing this against its own id
1086    /// reads the arena's verdict instead of re-deriving it from a rectangle,
1087    /// which is what keeps the two pickers from answering in different orders.
1088    ///
1089    /// `None` for a context made outside pointer dispatch (a gesture timer, a
1090    /// key-capture callback, an async completion). Treat `None` as "no verdict
1091    /// available", not as "not the target".
1092    pub fn dispatch_target(&self) -> Option<WidgetId> {
1093        self.dispatch_target
1094    }
1095
1096    /// Look up the bounds rect of an open overlay by its root content
1097    /// widget id. Returns `None` when no such overlay is currently
1098    /// active. The snapshot is taken once per dispatch; mid-handler
1099    /// `show_overlay` calls will not appear here. Used by the
1100    /// safe-triangle submenu hover gate.
1101    pub fn overlay_bounds_for_content(&self, content_id: WidgetId) -> Option<teksilo_canvas::Rect> {
1102        self.overlay_bounds_snapshot
1103            .iter()
1104            .find(|(cid, _, _)| *cid == content_id)
1105            .map(|(_, r, _)| *r)
1106    }
1107
1108    /// Whether a safe-triangle traversal toward the overlay rooted at
1109    /// `content_id` is still live — i.e. whether the user may still be on
1110    /// their way to that submenu.
1111    ///
1112    /// A widget whose hover would otherwise tear the overlay down (a
1113    /// sibling menu row switching the selection) asks this first and
1114    /// stands aside while it is `true`, leaving the dismissal to the
1115    /// overlay's own pointer-leave grace — which tests the cone on every
1116    /// sample and closes the overlay one `delay` after the pointer stops
1117    /// heading there.
1118    ///
1119    /// **This is deliberately the armed window, not a point-in-cone
1120    /// test.** A sibling row's hover fires exactly once, at the instant
1121    /// the pointer crosses onto it — a pixel or two from the apex, where
1122    /// the cone is a needle — so answering "is this one sample inside the
1123    /// cone" made a single quantized step final, and any departure
1124    /// steeper than the cone (which is most of them, for a wide menu with
1125    /// a short submenu) killed the submenu the moment the pointer left
1126    /// the trigger row. Whether *this* sample is inside the cone is the
1127    /// framework's question, asked continuously; the widget's question is
1128    /// only whether to get out of the way.
1129    ///
1130    /// `false` when no region is armed and when its budget is spent.
1131    ///
1132    /// Arm the region with
1133    /// [`arm_overlay_safe_region`](Self::arm_overlay_safe_region).
1134    pub fn overlay_safe_region_armed(&self, content_id: WidgetId) -> bool {
1135        self.overlay_bounds_snapshot
1136            .iter()
1137            .find(|(cid, _, _)| *cid == content_id)
1138            .is_some_and(|(_, _, apex)| apex.is_some())
1139    }
1140
1141    pub fn window(&self) -> Option<&crate::window::WindowState> {
1142        self.current_window.as_ref()
1143    }
1144
1145    /// Whether the host window is currently active (`focused AND not
1146    /// occluded`) — the occlusion-aware companion to
1147    /// `self.window().map(|w| w.focused())` (raw OS focus). Snapshotted at
1148    /// context construction. Matches [`BuildContext::window_active`].
1149    ///
1150    /// [`BuildContext::window_active`]: crate::build_context::BuildContext::window_active
1151    pub fn window_active(&self) -> bool {
1152        self.tree_window_active
1153    }
1154
1155    /// Open a new window, creating the winit-level surface
1156    /// synchronously. The returned id is immediately valid for
1157    /// [`focus_window`](Self::focus_window),
1158    /// [`window_state`](Self::window_state), and
1159    /// [`find_window`](Self::find_window).
1160    ///
1161    /// Panics when called from a handler on a standalone `WidgetTree`
1162    /// (no app context) — tests should not invoke this method.
1163    pub fn open_window(
1164        &mut self,
1165        config: crate::window::WindowConfig,
1166    ) -> crate::window::TeksiloWindowId {
1167        self.warn_if_context_change_in_focus_dispatch("open_window");
1168        self.window_ops
1169            .as_deref_mut()
1170            .expect("open_window called outside of a dispatch")
1171            .open_window(config)
1172    }
1173
1174    /// Find a window by the string id assigned via
1175    /// [`WindowConfig::id`](crate::window::WindowConfig::id). Returns
1176    /// `None` if no open window carries that id.
1177    pub fn find_window(&self, string_id: &str) -> Option<crate::window::TeksiloWindowId> {
1178        self.window_ops.as_deref()?.find_window(string_id)
1179    }
1180
1181    /// Read the [`WindowState`](crate::window::WindowState) for a
1182    /// specific window.
1183    pub fn window_state(
1184        &self,
1185        id: crate::window::TeksiloWindowId,
1186    ) -> Option<crate::window::WindowState> {
1187        self.window_ops.as_deref()?.window_state(id)
1188    }
1189
1190    /// Snapshot of every live window's state.
1191    pub fn windows(&self) -> Vec<crate::window::WindowState> {
1192        self.window_ops
1193            .as_deref()
1194            .map(|o| o.windows())
1195            .unwrap_or_default()
1196    }
1197
1198    /// Raise a window to the front and give it keyboard focus.
1199    pub fn focus_window(&mut self, id: crate::window::TeksiloWindowId) {
1200        self.warn_if_context_change_in_focus_dispatch("focus_window");
1201        if let Some(ops) = self.window_ops.as_deref_mut() {
1202            ops.focus_window(id);
1203        }
1204    }
1205
1206    /// Request an xdg-activation token for `id` (see
1207    /// [`WindowOps::request_activation_token`](crate::window::WindowOps::request_activation_token)).
1208    /// `cb` fires once with the token string, or `None` where the platform can't
1209    /// provide one — used to hand a token to a child process ("open in new
1210    /// window") or an IPC peer that will raise itself on Wayland.
1211    pub fn request_activation_token(
1212        &mut self,
1213        id: crate::window::TeksiloWindowId,
1214        cb: Box<dyn FnOnce(Option<String>)>,
1215    ) {
1216        if let Some(ops) = self.window_ops.as_deref_mut() {
1217            ops.request_activation_token(id, cb);
1218        } else {
1219            cb(None);
1220        }
1221    }
1222
1223    /// Request an activation token for the **current** window (see
1224    /// [`WindowOps::request_activation_token_self`](crate::window::WindowOps::request_activation_token_self)).
1225    /// Use this from a widget handler to mint a token from *this* focused window
1226    /// to hand to another window or process — it works mid-dispatch, unlike the
1227    /// id-based variant.
1228    pub fn request_activation_token_self(&mut self, cb: Box<dyn FnOnce(Option<String>)>) {
1229        if let Some(ops) = self.window_ops.as_deref_mut() {
1230            ops.request_activation_token_self(cb);
1231        } else {
1232            cb(None);
1233        }
1234    }
1235
1236    /// Close a specific window by id. Equivalent to
1237    /// [`close_window`](Self::close_window) when `id` is the current
1238    /// window's id.
1239    pub fn close_window_by_id(&mut self, id: crate::window::TeksiloWindowId) {
1240        if let Some(ops) = self.window_ops.as_deref_mut() {
1241            ops.close_window_by_id(id);
1242        }
1243    }
1244
1245    /// Report the focused text widget's caret rectangle (window-logical
1246    /// pixels) so the platform can position the OS IME candidate window at
1247    /// the insertion point. Text-editing widgets call this whenever the
1248    /// caret moves. No-op outside a dispatch / on a standalone tree.
1249    pub fn set_ime_cursor_area(&mut self, area: teksilo_canvas::Rect) {
1250        if let Some(ops) = self.window_ops.as_deref_mut() {
1251            ops.set_ime_cursor_area(area);
1252        }
1253    }
1254
1255    /// Resolve the platform parent handle of the window currently
1256    /// dispatching the event. Used by native-dialog integrations
1257    /// (`teksilo_platform::file_dialog`) to parent OS dialogs to the
1258    /// originating Teksilo window.
1259    ///
1260    /// Returns `None` when called from a standalone `WidgetTree` (no
1261    /// app-level `WindowOps` sink), or when the platform refuses to
1262    /// surface a handle (rare; mostly during teardown).
1263    pub fn parent_window_handle(&self) -> Option<crate::raw_handle::ParentHandle> {
1264        self.window_ops.as_deref()?.current_parent_handle()
1265    }
1266
1267    /// Request a cursor icon change.
1268    ///
1269    /// This is an **override**: it outranks the cursor the hovered node
1270    /// declared with [`WidgetBuilder::cursor`], and it outlives the dispatch
1271    /// that set it. The tree's cursor moves only when something writes to it,
1272    /// and the node-declared cursor is written on `PointerEnter` /
1273    /// `PointerLeave` alone — so a handler that sets a cursor while the
1274    /// pointer is inside a node owns the cursor until the pointer leaves that
1275    /// node, or until the handler gives it back with
1276    /// [`release_cursor`](Self::release_cursor).
1277    ///
1278    /// [`WidgetBuilder::cursor`]: crate::widget_builder::WidgetBuilder::cursor
1279    pub fn set_cursor(&mut self, cursor: CursorIcon) {
1280        self.cursor_request = Some(CursorRequest::Set(cursor));
1281    }
1282
1283    /// Withdraw this handler's cursor override, so the cursor the hovered
1284    /// node declared applies again.
1285    ///
1286    /// The cursor counterpart of returning [`EventResponse::Ignored`]: it says
1287    /// "I have nothing to say about the cursor", which is *not* the same as
1288    /// saying [`CursorIcon::Default`] and not the same as staying silent.
1289    ///
1290    /// Silence is only safe for a handler that has never spoken. A handler
1291    /// which re-decides the cursor on every move — a scene arbitrating a
1292    /// lightweight item's cursor against the card underneath it, a chart's
1293    /// overlay marks, a terminal's link layer — reaches points where it has no
1294    /// answer while the pointer is still inside the same node. No hover
1295    /// transition fires there, so nothing re-applies the node's declared
1296    /// cursor, and going quiet leaves the handler's *last* word standing. This
1297    /// is how it takes that word back.
1298    ///
1299    /// Restores exactly what the `PointerEnter` walk resolved for the current
1300    /// hover chain (or [`CursorIcon::Default`] if that chain declared none),
1301    /// so it can never disagree with the declared-cursor mechanism it defers
1302    /// to. Calling it when nothing was overridden is a no-op.
1303    ///
1304    /// [`EventResponse::Ignored`]: crate::event::EventResponse::Ignored
1305    pub fn release_cursor(&mut self) {
1306        self.cursor_request = Some(CursorRequest::Release);
1307    }
1308
1309    /// Set a widget subtree as dormant (preserves state, releases rendering).
1310    pub fn set_dormant(&mut self, id: WidgetId) {
1311        self.tree_mutations.push(TreeMutation::SetDormant(id));
1312    }
1313
1314    /// Activate a dormant widget subtree.
1315    pub fn activate(&mut self, id: WidgetId) {
1316        self.tree_mutations.push(TreeMutation::Activate(id));
1317    }
1318
1319    /// Destroy a widget subtree (removes from arena entirely, state is gone).
1320    pub fn destroy(&mut self, id: WidgetId) {
1321        self.tree_mutations.push(TreeMutation::Destroy(id));
1322    }
1323
1324    /// Imperatively mutate a mounted widget by id, downcasting to the
1325    /// concrete type `W`.
1326    ///
1327    /// The mutation is **deferred**: the closure runs after the handler
1328    /// returns, inside `apply_tree_mutations`, where the framework holds
1329    /// `&mut` arena access (a handler cannot re-borrow the arena to reach
1330    /// another node, so this is the only safe channel — the same model as
1331    /// [`destroy`](Self::destroy)). After the closure runs, the target is
1332    /// dirty-marked at `dirty` so the mutation takes visual effect.
1333    ///
1334    /// The target widget must override `Widget::as_any_mut` to return
1335    /// `Some(self)`. If the id is gone or is not a `W`, the closure is a
1336    /// no-op in release and a `debug_assert` failure in debug — it never
1337    /// silently mutates the wrong widget.
1338    ///
1339    /// Use it for per-view state a handler can't otherwise reach — e.g.
1340    /// `SceneView::ensure_visible(...)` (camera) after the view is mounted:
1341    /// ```ignore
1342    /// ctx.with_widget_mut::<SceneView>(view_id, BindingLevel::Relayout, |v| {
1343    ///     v.ensure_visible(card_rect, 40.0);
1344    /// });
1345    /// ```
1346    /// For scene *content*, prefer the shared `SceneModel` handle (`view.model()`)
1347    /// — its mutators are `&self`, so a handler holding a clone can drive the
1348    /// scene directly and every attached view reconciles, no `with_widget_mut`
1349    /// needed.
1350    pub fn with_widget_mut<W: 'static>(
1351        &mut self,
1352        id: WidgetId,
1353        dirty: crate::binding::BindingLevel,
1354        f: impl FnOnce(&mut W) + 'static,
1355    ) {
1356        self.tree_mutations.push(TreeMutation::WithWidgetMut {
1357            id,
1358            dirty,
1359            apply: Box::new(move |any| match any.downcast_mut::<W>() {
1360                Some(w) => f(w),
1361                None => debug_assert!(
1362                    false,
1363                    "with_widget_mut: widget {id:?} is not the requested type (or does not \
1364                     override Widget::as_any_mut)"
1365                ),
1366            }),
1367        });
1368    }
1369
1370    /// Re-run one widget's `build()` **during this handler's drain**, before
1371    /// overlays are shown and before focus requests are applied — rather than
1372    /// dirty-marking it for the next layout pass, which is what every other
1373    /// rebuild trigger does.
1374    ///
1375    /// It exists for one shape:
1376    /// [`DeferredSubtree`](crate::deferred_subtree::DeferredSubtree) content
1377    /// that a handler is *about to depend on*. Opening a popover activates its
1378    /// content, shows an overlay anchored to it, and moves focus into it — all
1379    /// three inside the same drain (see `collect_from_ctx`). A deferred panel
1380    /// marked for rebuild would not exist yet at any of those points: the
1381    /// overlay would be measured against an empty node and
1382    /// `first_focusable_descendant` would find nothing to focus, so the popover
1383    /// would open in the wrong place and swallow the keyboard. Materializing
1384    /// here closes that window, and makes deferred content behave exactly like
1385    /// the eagerly-built content it replaces.
1386    ///
1387    /// Cheap to call redundantly: a `DeferredSubtree` that is already
1388    /// materialized returns its existing child, so a second open costs one
1389    /// `build()` of the host and nothing below it.
1390    ///
1391    /// Not a general "rebuild this widget now" door — reach for
1392    /// [`with_widget_mut`](Self::with_widget_mut) or a `Rebuild` binding for
1393    /// ordinary reactive updates, which are correctly served by the next
1394    /// layout pass.
1395    /// `Space` on a data view's focused row: activate the row's published
1396    /// keyboard toggle — the checkbox `StandardListItem` embeds, most often —
1397    /// or run `fallback` when the row publishes none.
1398    ///
1399    /// A row's controls are out of the Tab order, so this is the only keyboard
1400    /// route to them; `fallback` is what `Space` means on a row without one,
1401    /// which for the data views is "toggle the selection".
1402    pub fn row_space_activate(
1403        &mut self,
1404        row: WidgetId,
1405        fallback: std::rc::Rc<dyn Fn(&mut EventContext)>,
1406    ) {
1407        self.tree_mutations
1408            .push(TreeMutation::RowSpaceActivate { row, fallback });
1409    }
1410
1411    pub fn materialize_now(&mut self, id: WidgetId) {
1412        self.tree_mutations.push(TreeMutation::MaterializeNow(id));
1413    }
1414
1415    /// Request that the AccessKit tree be re-walked after this handler
1416    /// returns. Use after a mutation that changes the accessibility tree
1417    /// **shape** in a way the framework doesn't already detect (relayout
1418    /// alone no longer re-walks AT; only events that change the AT tree
1419    /// — focus, overlays, locale/shortcut rebinds — set the dirty flag).
1420    /// The companion `BuildContext::request_accessibility_update` covers
1421    /// the build-time path.
1422    pub fn request_accessibility_update(&mut self) {
1423        self.request_a11y_update = true;
1424    }
1425
1426    /// Ask the platform to raise its on-screen keyboard.
1427    ///
1428    /// For the case the desktop convention has no answer for: a *finger*
1429    /// landing in a text field, where there is no physical keyboard and no
1430    /// focus change the accessibility layer would notice on its own.
1431    ///
1432    /// The request is honoured **only where it can do no harm**. Where the
1433    /// platform's keyboard follows the framework's IME-allowance reconcile
1434    /// ([`SoftKeyboardSupport::ViaAccessibility`](crate::window::SoftKeyboardSupport::ViaAccessibility)),
1435    /// the request resolves to nothing — always, not merely while a composition
1436    /// happens to be live. That reconcile *is* the request, and the only thing
1437    /// an explicit ask could add is a re-assertion of IME allowance, which is
1438    /// what cancels a composition mid-word. Nothing on this path calls
1439    /// `set_ime_allowed`, and that is what makes placing a caret with a finger
1440    /// mid-composition safe. Where the framework has no keyboard request to
1441    /// send at all the request is dropped; ask
1442    /// [`soft_keyboard_support`](Self::soft_keyboard_support) first if the
1443    /// widget needs to offer a fallback.
1444    pub fn request_soft_keyboard(&mut self) {
1445        self.soft_keyboard_request = Some(true);
1446    }
1447
1448    /// Ask the platform to dismiss its on-screen keyboard.
1449    ///
1450    /// Only a platform reporting
1451    /// [`SoftKeyboardSupport::Explicit`](crate::window::SoftKeyboardSupport::Explicit)
1452    /// can honour this; elsewhere there is no dismiss request to send, and a
1453    /// keyboard that rose on the IME enable goes away on the matching disable
1454    /// when focus leaves the text surface.
1455    pub fn dismiss_soft_keyboard(&mut self) {
1456        self.soft_keyboard_request = Some(false);
1457    }
1458
1459    /// What the host platform can do about an on-screen keyboard.
1460    ///
1461    /// [`SoftKeyboardSupport::None`](crate::window::SoftKeyboardSupport::None)
1462    /// on a standalone tree and on every platform the framework has no keyboard
1463    /// request to send on — which, on the desktop, is most of them.
1464    pub fn soft_keyboard_support(&self) -> crate::window::SoftKeyboardSupport {
1465        self.window_ops
1466            .as_deref()
1467            .map(|ops| ops.soft_keyboard_support())
1468            .unwrap_or_default()
1469    }
1470
1471    /// Speak `message` to the screen reader, politely.
1472    ///
1473    /// For anything the user needs told that is not the name of a widget: a
1474    /// completed action, a new count, the result of an undo, a row that moved.
1475    /// Sighted users read those off the screen; a screen-reader user is told
1476    /// only what the framework says out loud.
1477    ///
1478    /// ```ignore
1479    /// ctx.announce(tr!(event_added(title = title.clone())));
1480    /// ```
1481    ///
1482    /// Takes `impl Into<String>`, so `tr!(…)` works directly.
1483    /// `LocalizedString` is deliberately not the parameter type: an
1484    /// announcement is an event, not a label, and
1485    /// re-resolving it on a later language switch would re-speak it. See
1486    /// [`crate::announcer`].
1487    ///
1488    /// **Do not pair this with a toast on the same path.** `Toast` is already a
1489    /// correct live region, so doing both says everything twice.
1490    pub fn announce(&mut self, message: impl Into<String>) {
1491        self.announce_with(message, crate::announcer::Politeness::Polite);
1492    }
1493
1494    /// Speak `message` to the screen reader at the given urgency.
1495    ///
1496    /// [`Politeness::Assertive`](crate::announcer::Politeness::Assertive)
1497    /// interrupts whatever is being spoken. Reserve it for something the user
1498    /// must not miss and cannot recover by re-reading the screen — a failure, a
1499    /// refusal, a destructive result. Everything else is
1500    /// [`Polite`](crate::announcer::Politeness::Polite), which is what
1501    /// [`announce`](Self::announce) uses.
1502    pub fn announce_with(
1503        &mut self,
1504        message: impl Into<String>,
1505        politeness: crate::announcer::Politeness,
1506    ) {
1507        self.announcements.push((message.into(), politeness));
1508    }
1509
1510    /// Show an overlay (tooltip, menu, popover).
1511    pub fn show_overlay(&mut self, request: crate::overlay::OverlayRequest) {
1512        self.overlay_requests.push(request);
1513    }
1514
1515    /// Show an overlay in an explicit z-band.
1516    ///
1517    /// [`show_overlay`](Self::show_overlay) is this with
1518    /// [`Standard`](crate::overlay::OverlayBand::Standard). The other band is
1519    /// for the touch text affordances, which must render above the editor's
1520    /// `clips_children` ancestor, below every menu, and outside the
1521    /// outside-press dismissal that every caret-moving tap would otherwise
1522    /// trigger. Their lifetime is the controller's — see
1523    /// [`TouchSelection::dismiss`](crate::text_touch::TouchSelection::dismiss).
1524    ///
1525    /// Showing content that is already up is a no-op, so a host may call this
1526    /// on every raise without tracking whether it has.
1527    pub fn show_overlay_in_band(
1528        &mut self,
1529        request: crate::overlay::OverlayRequest,
1530        band: crate::overlay::OverlayBand,
1531    ) {
1532        self.overlay_band_requests.push((request, band));
1533    }
1534
1535    /// Re-place the currently-shown overlay whose content root is `content_id`.
1536    ///
1537    /// Content-keyed for the same reason
1538    /// [`dismiss_overlay_by_content`](Self::dismiss_overlay_by_content) is:
1539    /// [`show_overlay`](Self::show_overlay) returns nothing, so a handler
1540    /// cannot learn the [`OverlayId`](crate::overlay::OverlayId) it created. A
1541    /// no-op when no overlay is showing that content.
1542    pub fn update_overlay_placement_by_content(
1543        &mut self,
1544        content_id: crate::widget_id::WidgetId,
1545        placement: crate::overlay::OverlayPlacement,
1546    ) {
1547        self.overlay_placement_updates.push((content_id, placement));
1548    }
1549
1550    /// Show an overlay whose reveal/dismiss is animated by a
1551    /// caller-owned progress signal.
1552    ///
1553    /// `progress` must be an animated `Signal<f32>` (created with
1554    /// [`Signal::new_animated`](crate::signal::Signal::new_animated) or
1555    /// [`BuildContext::animated_signal`](crate::build_context::BuildContext::animated_signal)).
1556    /// The framework shows the overlay, tweens `progress` 0 → 1 over
1557    /// `duration`, and on any dismiss path tweens it 1 → 0 while
1558    /// **deferring** the overlay's removal (and its content's dormancy)
1559    /// until the roll-back completes — the same window the fade path
1560    /// uses, but with no opacity applied. The caller binds `progress`
1561    /// to whatever paints the reveal (e.g. an
1562    /// [`Unroll`](https://docs.rs/teksilo) width), and is responsible for
1563    /// resetting it to `0.0` before the show if a prior reveal left it
1564    /// at `1.0`.
1565    ///
1566    /// Under `prefers-reduced-motion`, skip this and use
1567    /// [`show_overlay`](Self::show_overlay) with the progress pinned at
1568    /// `1.0` so there is no tween and dismissal is immediate.
1569    pub fn show_overlay_with_reveal(
1570        &mut self,
1571        request: crate::overlay::OverlayRequest,
1572        progress: crate::signal::Signal<f32>,
1573        duration: std::time::Duration,
1574    ) {
1575        self.reveal_overlay_requests
1576            .push((request, progress, duration));
1577    }
1578
1579    /// Show an overlay that dismisses automatically after `duration`.
1580    pub fn show_overlay_for(
1581        &mut self,
1582        request: crate::overlay::OverlayRequest,
1583        duration: std::time::Duration,
1584    ) {
1585        self.timed_overlay_requests.push((request, duration));
1586    }
1587
1588    /// Dismiss an overlay by ID.
1589    pub fn dismiss_overlay(&mut self, id: crate::overlay::OverlayId) {
1590        self.overlay_dismissals.push(id);
1591    }
1592
1593    /// Dismiss the currently-shown overlay whose content root is
1594    /// `content_id`, if one is active. No-op when no overlay is showing
1595    /// that content. Use this to dismiss an overlay you can only name by
1596    /// its content widget — the symmetric companion to
1597    /// [`cancel_delayed_overlay`](Self::cancel_delayed_overlay), which
1598    /// cancels a *pending* delayed show for the same content. Together
1599    /// they let a caller fully retract a reusable tooltip surface
1600    /// (shown or pending) without tracking the `OverlayId`.
1601    pub fn dismiss_overlay_by_content(&mut self, content_id: crate::widget_id::WidgetId) {
1602        self.overlay_content_dismissals.push(content_id);
1603    }
1604
1605    /// Queue a request to pause an overlay's `auto_dismiss_after`
1606    /// timer. Drained by the framework after this handler returns —
1607    /// equivalent to calling
1608    /// [`OverlayManager::pause_auto_dismiss`](crate::overlay::OverlayManager::pause_auto_dismiss)
1609    /// at the next safe point. Idempotent.
1610    ///
1611    /// Used by `ToastHost` for hover-pause: on pointer-enter the
1612    /// host queues `pause_overlay_auto_dismiss(id)` for every live
1613    /// toast; on pointer-leave it queues `resume_overlay_auto_dismiss`.
1614    pub fn pause_overlay_auto_dismiss(&mut self, id: crate::overlay::OverlayId) {
1615        self.overlay_pause_requests.push((id, true));
1616    }
1617
1618    /// Queue a request to resume an overlay's `auto_dismiss_after`
1619    /// timer paused via
1620    /// [`pause_overlay_auto_dismiss`](Self::pause_overlay_auto_dismiss).
1621    /// Idempotent on un-paused overlays.
1622    pub fn resume_overlay_auto_dismiss(&mut self, id: crate::overlay::OverlayId) {
1623        self.overlay_pause_requests.push((id, false));
1624    }
1625
1626    /// Dismiss all active overlays (e.g., after a menu item is activated).
1627    pub fn dismiss_all_overlays(&mut self) {
1628        self.dismiss_scope = Some(DismissScope::All);
1629    }
1630
1631    /// Dismiss the source widget's containing overlay and any ancestor
1632    /// overlays in the chain that are menu-like (anything that isn't a
1633    /// `Role::Tooltip`, `Role::Dialog`, or `Role::AlertDialog`),
1634    /// preserving an outer composite tooltip or modal hosting the
1635    /// popover. Use for menu / dropdown item activation that wants to
1636    /// close the menu cascade without disturbing the host surface.
1637    pub fn dismiss_self_overlay_chain(&mut self) {
1638        self.dismiss_scope = Some(DismissScope::SelfChain);
1639    }
1640
1641    /// Dismiss every overlay whose content is *not* a host surface
1642    /// (`Role::Tooltip`, `Role::Dialog`, `Role::AlertDialog`),
1643    /// preserving an outer composite tooltip or modal hosting the
1644    /// trigger. Use for popover triggers and pre-show cleanup that
1645    /// want to close stale popovers / menus without taking a hosting
1646    /// surface with them.
1647    pub fn dismiss_all_except_hosts(&mut self) {
1648        self.dismiss_scope = Some(DismissScope::AllExceptHosts);
1649    }
1650
1651    /// Dismiss the topmost overlay only (e.g., closing a submenu while
1652    /// keeping the parent menu open).
1653    pub fn dismiss_top_overlay(&mut self) {
1654        self.dismiss_scope = Some(DismissScope::Top);
1655    }
1656
1657    /// Dismiss descendant overlays of the source widget's containing overlay.
1658    /// Useful for closing sibling submenu branches while keeping the current
1659    /// parent menu open.
1660    pub fn dismiss_child_overlays(&mut self) {
1661        self.dismiss_descendant_overlays.push(None);
1662    }
1663
1664    /// Dismiss descendant overlays of the source widget's containing overlay,
1665    /// preserving the subtree rooted at `content_id` if it is already open.
1666    pub fn dismiss_child_overlays_except(&mut self, content_id: crate::widget_id::WidgetId) {
1667        self.dismiss_descendant_overlays.push(Some(content_id));
1668    }
1669
1670    /// Request an idle callback to be run during the next idle period.
1671    /// Use this for incremental work that takes 5-50ms — too short for a
1672    /// background thread, too long for a single frame.
1673    pub fn request_idle_callback(
1674        &mut self,
1675        callback: impl FnOnce(crate::idle::IdleDeadline) + 'static,
1676    ) {
1677        self.idle_callbacks.push(Box::new(callback));
1678    }
1679
1680    /// Request framework-owned modal presentation.
1681    ///
1682    /// The widget tree records the request together with the originating
1683    /// widget, and the application layer can later resolve `Auto` into a
1684    /// concrete presentation backend.
1685    pub fn present_modal(&mut self, request: crate::modal::ModalRequest) {
1686        self.modal_requests.push(request);
1687    }
1688
1689    /// Synchronously open a modal as a native window — the single
1690    /// unified path for native-window modals. Callers that don't
1691    /// care whether the modal lands in-tree or in a native window
1692    /// use [`present_modal`](Self::present_modal), which routes
1693    /// `ModalPresentation::Auto` through the framework's picker.
1694    ///
1695    /// Returns the new window's id, or `None` when called outside a
1696    /// dispatch context (standalone trees). The window's parent is
1697    /// the current window; focus target and title / size from the
1698    /// request are honored.
1699    ///
1700    /// Only `ModalContent::Deferred` is supported here — an
1701    /// `ExistingWidget` id wouldn't make sense in a fresh tree.
1702    pub fn open_modal(
1703        &mut self,
1704        request: crate::modal::ModalRequest,
1705    ) -> Option<crate::window::TeksiloWindowId> {
1706        let parent = self.current_window.as_ref()?.id();
1707        let crate::modal::ModalContent::Deferred(builder) = request.content else {
1708            return None;
1709        };
1710        let mut config = crate::window::WindowConfig::new().modal(crate::window::ModalConfig {
1711            parent,
1712            focus_target: request.focus_target,
1713        });
1714        if let Some(title) = request.title {
1715            config = config.title(title);
1716        }
1717        if let Some((w, h)) = request.size {
1718            config = config.size(w, h);
1719        }
1720        let config = config.root(move |tree, _state| builder(tree));
1721        Some(self.open_window(config))
1722    }
1723
1724    /// Dismiss the current framework-owned modal presentation.
1725    pub fn dismiss_modal(&mut self) {
1726        self.dismiss_modal = true;
1727    }
1728
1729    /// Show an overlay after a delay. The widget tree checks pending delayed
1730    /// overlays during `layout()` and shows them once the delay elapses.
1731    /// Use this for submenu hover-open delays.
1732    ///
1733    /// The content widget should already be added to the tree (typically
1734    /// dormant). It will be activated automatically when the delay elapses.
1735    pub fn show_overlay_after(
1736        &mut self,
1737        request: crate::overlay::OverlayRequest,
1738        delay: std::time::Duration,
1739    ) {
1740        self.delayed_overlay_requests
1741            .push((request, delay, None, false));
1742    }
1743
1744    /// Show an overlay after a delay and move focus when it opens.
1745    pub fn show_overlay_after_with_focus(
1746        &mut self,
1747        request: crate::overlay::OverlayRequest,
1748        delay: std::time::Duration,
1749        focus_target: crate::widget_id::WidgetId,
1750    ) {
1751        self.delayed_overlay_requests
1752            .push((request, delay, Some(focus_target), false));
1753    }
1754
1755    /// Show an overlay after a delay, move focus when it opens, and
1756    /// dismiss the anchor's sibling overlays **at that moment** rather
1757    /// than when the request was made.
1758    ///
1759    /// This is the hover-switch between two submenu triggers in the same
1760    /// menu. Dismissing eagerly at hover-enter closes the submenu the
1761    /// user is still walking toward as soon as the pointer crosses a
1762    /// neighbouring trigger; deferring the dismissal to the moment the
1763    /// new submenu actually opens means a pointer merely passing through
1764    /// costs nothing, and one that settles gets the swap on the same
1765    /// frame — no window with two submenus on screen.
1766    pub fn show_overlay_after_replacing_siblings(
1767        &mut self,
1768        request: crate::overlay::OverlayRequest,
1769        delay: std::time::Duration,
1770        focus_target: crate::widget_id::WidgetId,
1771    ) {
1772        self.delayed_overlay_requests
1773            .push((request, delay, Some(focus_target), true));
1774    }
1775
1776    /// Request a repaint on a specific widget. Use this when an event handler
1777    /// on one widget changes state that affects a different widget's appearance
1778    /// (e.g., keyboard navigation highlighting items in an overlay).
1779    pub fn request_repaint(&mut self, id: crate::widget_id::WidgetId) {
1780        self.repaint_requests.push(id);
1781    }
1782
1783    /// Programmatically click a widget (synthetic PointerDown + PointerUp at
1784    /// its center). Use this for keyboard activation of a child widget, e.g.,
1785    /// Enter on a keyboard-focused menu item.
1786    pub fn synthetic_click(&mut self, id: crate::widget_id::WidgetId) {
1787        self.synthetic_clicks.push(id);
1788    }
1789
1790    /// Transfer focus to a specific widget. Use this when opening overlay
1791    /// content (menus, dialogs) that should receive keyboard events.
1792    pub fn request_focus(&mut self, id: crate::widget_id::WidgetId) {
1793        self.focus_requests.push(id);
1794    }
1795
1796    /// Move focus **into** the content of `id`: focus its first focusable
1797    /// descendant in tab order. Unlike [`request_focus`](Self::request_focus),
1798    /// this does **not** fall back to focusing `id` itself when the subtree has
1799    /// no focusable descendant — it is a no-op in that case, so an empty region
1800    /// never traps focus on a non-interactive container.
1801    ///
1802    /// Use this for "dive into this region" gestures, e.g. pressing Enter on a
1803    /// focused tab header to move focus into the tab's content panel. A panel
1804    /// with focusable content lands on its first control; a panel that opted
1805    /// into focusability itself (no inner controls) lands on the panel; a bare
1806    /// panel with neither leaves focus where it was.
1807    pub fn request_focus_into(&mut self, id: crate::widget_id::WidgetId) {
1808        self.focus_into_requests.push(id);
1809    }
1810
1811    /// Scroll the given rectangle into view inside every enclosing scroll
1812    /// container, walking outward from the widget whose handler is running.
1813    ///
1814    /// `rect` is in **absolute tree (window) coordinates** — the same space
1815    /// the arena stores widget bounds in. After the handler returns, the
1816    /// framework walks the current widget's ancestors and, for each
1817    /// `clips_children` scroll container whose viewport does not already
1818    /// fully contain `rect`, dispatches
1819    /// [`WidgetEvent::ScrollIntoView`](crate::event::WidgetEvent::ScrollIntoView)
1820    /// so the container adjusts its offset. Nested scroll areas each get a
1821    /// turn (outermost included), exactly like the focus-driven path.
1822    ///
1823    /// Unlike the automatic focus follow — which can only reveal a *focused
1824    /// widget's own bounds* — this lets a widget reveal an arbitrary interior
1825    /// rectangle it computed itself: a text caret, a virtualized list/table
1826    /// row (which is not a distinct focusable node), or a scrolled-off tab
1827    /// header. The widget remains responsible for scrolling its *own* interior
1828    /// viewport; `ensure_visible` handles the enclosing containers. It is a
1829    /// no-op when there is no scroll container above the widget, or when every
1830    /// container already shows the rect.
1831    ///
1832    /// See [`ensure_visible_with_margin`](Self::ensure_visible_with_margin) to
1833    /// keep breathing room around the target.
1834    pub fn ensure_visible(&mut self, rect: teksilo_canvas::Rect) {
1835        self.scroll_into_view_requests.push(ScrollRevealRequest {
1836            rect,
1837            margin: 0.0,
1838            align: crate::event::ScrollAlign::Minimal,
1839            motion: crate::event::ScrollMotion::Instant,
1840            from: None,
1841        });
1842    }
1843
1844    /// [`ensure_visible`](Self::ensure_visible), for a rect that belongs to
1845    /// **another** widget.
1846    ///
1847    /// The framework walks `owner`'s ancestors rather than the handling widget's.
1848    /// That distinction is the whole of it, and getting it wrong fails silently:
1849    /// a find banner's Next button sits *beside* the scrolling page, not inside
1850    /// it, so a reveal walked from the button climbs out through the banner and
1851    /// never meets the scroll container the match is in. The match is selected,
1852    /// the counter moves, and the viewport does not follow.
1853    ///
1854    /// The same reasoning [`ensure_widget_visible`](Self::ensure_widget_visible)
1855    /// already records for the id-based form; this is its rect-based twin, for a
1856    /// target that is an interior span rather than a mounted child.
1857    ///
1858    /// `rect` is in absolute tree (window) coordinates.
1859    pub fn ensure_visible_from(
1860        &mut self,
1861        owner: crate::widget_id::WidgetId,
1862        rect: teksilo_canvas::Rect,
1863    ) {
1864        self.scroll_into_view_requests.push(ScrollRevealRequest {
1865            rect,
1866            margin: 0.0,
1867            align: crate::event::ScrollAlign::Minimal,
1868            motion: crate::event::ScrollMotion::Instant,
1869            from: Some(owner),
1870        });
1871    }
1872
1873    /// Like [`ensure_visible`](Self::ensure_visible), but keeps `margin`
1874    /// logical pixels of breathing room around `rect` on every edge, so the
1875    /// target does not sit flush against the viewport boundary (the caret at
1876    /// the bottom line, the selected row at the fold). `rect` is in absolute
1877    /// tree (window) coordinates.
1878    pub fn ensure_visible_with_margin(&mut self, rect: teksilo_canvas::Rect, margin: f32) {
1879        self.scroll_into_view_requests.push(ScrollRevealRequest {
1880            rect,
1881            margin: margin.max(0.0),
1882            align: crate::event::ScrollAlign::Minimal,
1883            motion: crate::event::ScrollMotion::Instant,
1884            from: None,
1885        });
1886    }
1887
1888    /// **Pin** `rect` at `fraction` of the way down the innermost enclosing
1889    /// scroll container — `0.0` flush with the top, `0.5` centred, `1.0` flush
1890    /// with the bottom — instead of merely revealing it.
1891    ///
1892    /// The difference from [`ensure_visible`](Self::ensure_visible) is that this
1893    /// scrolls **even when the target is already visible**. That is what makes
1894    /// it usable for typewriter scrolling: a caret that only moved the view once
1895    /// it fell off the edge would not be pinned to anything.
1896    ///
1897    /// Only the **innermost** clipping ancestor aligns; any further ancestors
1898    /// out fall back to a minimal reveal, since an outer container's job is to
1899    /// bring the inner viewport on screen, not to align a rectangle it does not
1900    /// own.
1901    ///
1902    /// `fraction` is clamped to `0.0..=1.0`. The container additionally clamps
1903    /// to its own scroll range, so a target near the start or end of the content
1904    /// lands as close to `fraction` as the range permits — see the scroll
1905    /// container's `scroll_past_end` for buying range past the content's end so
1906    /// the last line can still reach the pin.
1907    ///
1908    /// `rect` is in absolute tree (window) coordinates.
1909    pub fn ensure_visible_aligned(
1910        &mut self,
1911        rect: teksilo_canvas::Rect,
1912        fraction: f32,
1913        motion: crate::event::ScrollMotion,
1914    ) {
1915        self.scroll_into_view_requests.push(ScrollRevealRequest {
1916            rect,
1917            margin: 0.0,
1918            align: crate::event::ScrollAlign::Fraction(fraction.clamp(0.0, 1.0)),
1919            motion,
1920            from: None,
1921        });
1922    }
1923
1924    /// [`ensure_visible_aligned`](Self::ensure_visible_aligned), for a rect that
1925    /// belongs to **another** widget — see [`ensure_visible_from`](Self::ensure_visible_from)
1926    /// for why the distinction exists and how it fails when it is missed.
1927    pub fn ensure_visible_aligned_from(
1928        &mut self,
1929        owner: crate::widget_id::WidgetId,
1930        rect: teksilo_canvas::Rect,
1931        fraction: f32,
1932        motion: crate::event::ScrollMotion,
1933    ) {
1934        self.scroll_into_view_requests.push(ScrollRevealRequest {
1935            rect,
1936            margin: 0.0,
1937            align: crate::event::ScrollAlign::Fraction(fraction.clamp(0.0, 1.0)),
1938            motion,
1939            from: Some(owner),
1940        });
1941    }
1942
1943    /// Scroll a specific mounted widget into view inside every enclosing
1944    /// scroll container — the id-based companion to
1945    /// [`ensure_visible`](Self::ensure_visible).
1946    ///
1947    /// The framework resolves `id` to its current absolute bounds after the
1948    /// handler returns and walks *that widget's* ancestors (never `id`
1949    /// itself), dispatching
1950    /// [`WidgetEvent::ScrollIntoView`](crate::event::WidgetEvent::ScrollIntoView)
1951    /// to each `clips_children` container that doesn't already show it.
1952    ///
1953    /// Use this when the target you want revealed is a real, non-virtualized
1954    /// child whose bounds the arena already knows — a selected radio tile, a
1955    /// tab header — so you don't have to compute a rect. For a target that has
1956    /// no distinct node (a text caret) or that may not be realized (a
1957    /// virtualized list/table row), use [`ensure_visible`](Self::ensure_visible)
1958    /// with an analytic rect instead. No-op if `id` is not currently mounted.
1959    pub fn ensure_widget_visible(&mut self, id: crate::widget_id::WidgetId) {
1960        self.scroll_widget_into_view_requests.push((id, 0.0));
1961    }
1962
1963    /// Like [`ensure_widget_visible`](Self::ensure_widget_visible), but keeps
1964    /// `margin` logical pixels of breathing room around the widget.
1965    pub fn ensure_widget_visible_with_margin(
1966        &mut self,
1967        id: crate::widget_id::WidgetId,
1968        margin: f32,
1969    ) {
1970        self.scroll_widget_into_view_requests
1971            .push((id, margin.max(0.0)));
1972    }
1973
1974    /// Surface the tooltip of a keyboard-highlighted item immediately (no
1975    /// dwell), dismissing the previously-highlighted item's tooltip. Used by
1976    /// `MenuList` on arrow-key navigation so a menu item's rich/composite
1977    /// tooltip is reachable by keyboard — real focus stays on the menu panel,
1978    /// so this is keyed on the item id rather than on focus. Pass the item's
1979    /// own widget id; a tooltip-less item simply dismisses the previous one.
1980    pub fn show_highlight_tooltip(&mut self, id: crate::widget_id::WidgetId) {
1981        self.highlight_tooltip_requests.push(id);
1982    }
1983
1984    /// Cancel a pending delayed overlay by its content widget ID.
1985    /// Call this when the hover ends before the delay elapses.
1986    pub fn cancel_delayed_overlay(&mut self, content_id: crate::widget_id::WidgetId) {
1987        self.cancel_delayed_overlays.push(content_id);
1988    }
1989
1990    /// Arm the "safe triangle" of the open overlay rooted at
1991    /// `content_id`, with its apex at the current pointer position.
1992    ///
1993    /// Call this from the anchor's hover-leave handler: the pointer is
1994    /// then exactly at the point the diagonal toward the overlay
1995    /// starts. While the pointer sits inside the triangle spanned by
1996    /// that apex and the overlay's near edge, the overlay's
1997    /// pointer-leave grace is held off; leaving the triangle starts the
1998    /// grace and re-entering it cancels the grace again, so a wobble
1999    /// mid-diagonal costs nothing. Throughout — cone or no cone, until
2000    /// the pointer arrives or the framework's budget runs out —
2001    /// [`overlay_safe_region_armed`](Self::overlay_safe_region_armed)
2002    /// reports `true` so sibling widgets stand aside and let that one
2003    /// re-evaluated grace own the dismissal.
2004    ///
2005    /// No-ops when the overlay is not open (a submenu whose hover-open
2006    /// delay was cancelled before it ever showed) or when no pointer
2007    /// position is known.
2008    pub fn arm_overlay_safe_region(&mut self, content_id: crate::widget_id::WidgetId) {
2009        self.safe_region_arm_requests.push(content_id);
2010    }
2011
2012    /// Choose, **from this press's `PointerDown` handler**, when this node's own
2013    /// drag may begin — overriding its declared
2014    /// [`DragActivation`](teksilo_tokens::DragActivation) for this press alone.
2015    ///
2016    /// `.drag_activation(..)` is a node property, decided at build time. That is
2017    /// the right grain when a node's `on_drag` means one thing. It is the wrong
2018    /// grain when one handler means several: a scene viewport's single `on_drag`
2019    /// is its marquee *and* its item grab *and* its magnet port drag, and which
2020    /// of the three a press is cannot be known until the press has been
2021    /// hit-tested. This is the per-press door — the press handler has already
2022    /// done that hit test, so it can say "this one landed on an item, arm it
2023    /// immediately" while leaving an empty-space press to defer to the pan.
2024    ///
2025    /// Stashed on the pointer's sequence, **not** written back onto the node, so
2026    /// it dies with the press that chose it. That matters here more than
2027    /// hygiene usually does: `on_pointer_event` previews root-first over every
2028    /// strict ancestor of the press target, so a node that answers from it also
2029    /// answers for presses an interactive descendant owns, and a node write
2030    /// would leave the declaration changed for the *next* press.
2031    ///
2032    /// Read by the enrolment walk, which runs immediately after the press
2033    /// dispatch. Called from anything but a press handler it is inert for the
2034    /// press in flight — there is no enrolment left to read it — and applies to
2035    /// nothing else.
2036    ///
2037    /// Last writer wins: answering twice on one press means the second answer.
2038    pub fn set_drag_activation(&mut self, activation: teksilo_tokens::DragActivation) {
2039        self.drag_activation_override = Some(activation);
2040    }
2041
2042    /// Capture **the pointer this handler is serving**: its subsequent
2043    /// `PointerMove` and `PointerUp` are routed to this widget regardless of
2044    /// hit test, until the capture is released.
2045    ///
2046    /// Capture is per pointer. Two fingers pressing two widgets hold two
2047    /// independent captures, and each is released only by its own Up or
2048    /// Cancel — so a second contact lifting can no longer steal the first
2049    /// one's stream. A mouse call site is unaffected: there is one mouse, and
2050    /// this captures it.
2051    /// **Also an arbitration act.** Taking the pointer from an undecided
2052    /// [`PointerSequence`](crate::gesture::PointerSequence) enrols this widget
2053    /// as a [`MemberRole::RawDrag`](crate::gesture::MemberRole::RawDrag)
2054    /// competitor, and for a precise pointer with no eligible pan competitor
2055    /// it decides the sequence outright — which is what makes the splitter
2056    /// handle, the dock resize handle and the table column grip (all of which
2057    /// answer `Ignored` from `on_pointer_event` and work from `PointerMove`
2058    /// with no recognizer at all) first-class competitors rather than widgets
2059    /// the arbitration cannot see.
2060    pub fn capture_pointer(&mut self) {
2061        self.pointer_capture = Some((None, true));
2062        self.explicit_capture = true;
2063    }
2064
2065    /// Capture a *named* pointer, for a handler driving a pointer other than
2066    /// the one whose sample it is serving.
2067    pub fn capture_pointer_id(&mut self, pointer: crate::pointer::PointerId) {
2068        self.pointer_capture = Some((Some(pointer), true));
2069        self.explicit_capture = true;
2070    }
2071
2072    /// Capture the pointer as **framework plumbing**, without staking an
2073    /// arbitration claim.
2074    ///
2075    /// The gesture arena takes the pointer for the Down..Up window so a
2076    /// recognizer keeps seeing moves that leave the widget's bounds, and the
2077    /// drag pipeline takes it for the life of a drag. Neither is a widget
2078    /// saying "this press is mine"; routing them through the public
2079    /// [`capture_pointer`](Self::capture_pointer) would enrol every
2080    /// arena-bearing node as a `RawDrag` member and decide every mouse
2081    /// sequence at press.
2082    pub(crate) fn capture_pointer_implicit(&mut self) {
2083        self.pointer_capture = Some((None, true));
2084    }
2085
2086    /// Claim the pointer sequence for the widget whose handler is running:
2087    /// arbitration ends, every other competitor is cancelled.
2088    ///
2089    /// The explicit form of what a recognizer does when it recognizes. Use it
2090    /// from an application recognizer that decides by its own rules.
2091    pub fn claim_gesture(&mut self) {
2092        self.gesture_acts.push(GestureAct::Claim);
2093    }
2094
2095    /// Withdraw the widget whose handler is running from the sequence. It can
2096    /// no longer win this press; its peers carry on.
2097    pub fn reject_gesture(&mut self) {
2098        self.gesture_acts.push(GestureAct::Reject);
2099    }
2100
2101    /// Defer this widget's own decision without withdrawing: no peer may win
2102    /// while a member is holding.
2103    ///
2104    /// **The framework never holds.** This exists for an application
2105    /// recognizer awaiting an answer it does not have yet (a hit test against
2106    /// an off-thread model, a network round trip). The hold auto-releases at
2107    /// [`GestureProfile::max_hold`](teksilo_tokens::GestureProfile::max_hold)
2108    /// — 250 ms — so a holder that never answers cannot strand the press.
2109    pub fn hold_gesture(&mut self) {
2110        self.gesture_acts.push(GestureAct::Hold);
2111    }
2112
2113    /// End this widget's hold, putting it back in the running.
2114    pub fn release_gesture(&mut self) {
2115        self.gesture_acts.push(GestureAct::Release);
2116    }
2117
2118    /// Revoke the whole interaction of the pointer this handler is serving,
2119    /// for `reason`.
2120    ///
2121    /// The widget's own way into the cancel funnel, for a widget that knows
2122    /// the interaction can no longer mean anything — the document under a text
2123    /// drag was reloaded, the row being reordered was deleted by a peer. Every
2124    /// competitor is cancelled, the capture is given back, and a
2125    /// [`PointerCancel`](crate::event::WidgetEvent::PointerCancel) is
2126    /// delivered, all **after** this handler returns: a cancel taken inline
2127    /// would unwind the very sample the handler is standing on.
2128    ///
2129    /// Distinct from [`reject_gesture`](Self::reject_gesture), which withdraws
2130    /// only *this* widget and lets its peers carry on with a pointer that is
2131    /// still perfectly alive.
2132    pub fn cancel_pointer_sequence(&mut self, reason: crate::pointer::CancelReason) {
2133        self.cancel_pointer_request = Some(reason);
2134    }
2135
2136    /// Release the capture of the pointer this handler is serving. Its events
2137    /// resume normal hit-test dispatch.
2138    pub fn release_pointer(&mut self) {
2139        self.pointer_capture = Some((None, false));
2140    }
2141
2142    /// Whether the widget whose handler is running already holds the capture
2143    /// of the pointer it is serving.
2144    ///
2145    /// `true` also immediately after a [`capture_pointer`](Self::capture_pointer)
2146    /// in the same handler, even though the tree does not apply the request
2147    /// until the handler returns — asking "do I own this pointer?" after
2148    /// claiming it must not answer no.
2149    pub fn owns_pointer(&self) -> bool {
2150        match self.pointer_capture {
2151            Some((None, capture)) => capture,
2152            _ => self.dispatch_node.is_some() && self.dispatch_node == self.pointer_captor,
2153        }
2154    }
2155
2156    /// Start a drag-and-drop operation from the given source widget.
2157    ///
2158    /// The `payload` carries the data being dragged. During the drag:
2159    /// - `PointerMove` events update the drag position and fire `on_drag_hover`
2160    ///   on widgets under the pointer that have drop handlers
2161    /// - `PointerUp` fires `on_drop` on the target widget (if any)
2162    /// - `Escape` cancels the drag
2163    pub fn start_drag(
2164        &mut self,
2165        source_widget: crate::widget_id::WidgetId,
2166        payload: crate::drag_payload::DragPayload,
2167    ) {
2168        self.drag_start_request = Some((source_widget, payload, None));
2169    }
2170
2171    /// Start a drag-and-drop with a preview widget that follows the pointer.
2172    pub fn start_drag_with_preview(
2173        &mut self,
2174        source_widget: crate::widget_id::WidgetId,
2175        payload: crate::drag_payload::DragPayload,
2176        preview: Box<dyn crate::widget::Widget>,
2177    ) {
2178        self.drag_start_request = Some((source_widget, payload, Some(preview)));
2179    }
2180
2181    /// Cancel the active drag-and-drop session (if any).
2182    pub fn cancel_drag(&mut self) {
2183        self.cancel_drag = true;
2184    }
2185
2186    /// Replace the tree-level theme. Composite widgets are rebuilt so any
2187    /// derived values they captured at build time pick up the new tokens,
2188    /// and all widgets are marked dirty for repaint.
2189    ///
2190    /// An explicit theme also turns **off** OS-following: the app's theme
2191    /// mode is reset to manual, so a later OS light/dark change won't
2192    /// override the chosen theme.
2193    pub fn set_theme(&mut self, theme: crate::styles::Theme) {
2194        self.theme_request = Some(theme);
2195    }
2196
2197    /// Switch the application to follow the OS theme (native / system mode):
2198    /// the app adopts the OS's colours and tracks OS light/dark changes at
2199    /// runtime. On platforms without OS-colour support it falls back to
2200    /// following the built-in light/dark presets.
2201    ///
2202    /// This is the counterpart to [`set_theme`](Self::set_theme): calling
2203    /// `set_theme` pins a fixed theme (manual mode), while this resumes
2204    /// OS-following. Parameterless by design, so widgets need not reference
2205    /// the app-layer theme-mode enum.
2206    pub fn follow_system_theme(&mut self) {
2207        self.follow_system_request = true;
2208    }
2209
2210    /// Replace the tree-level locale identifier. Composite widgets are
2211    /// rebuilt so any tr! lookups picked up at build time are re-evaluated
2212    /// against the new locale.
2213    pub fn set_locale(&mut self, locale: impl Into<String>) {
2214        self.locale_request = Some(locale.into());
2215    }
2216
2217    /// Set the user-controlled global text-scale factor (`1.0` = 100 %).
2218    ///
2219    /// The change is applied app-wide (every window) after the handler returns,
2220    /// mirroring [`set_theme`](Self::set_theme) / [`set_locale`](Self::set_locale).
2221    /// All text grows uniformly without a rebuild. Persist the value through
2222    /// `ctx.settings()` (e.g. `teksilo_settings::TEXT_SCALE_KEY`) so it survives
2223    /// a restart — the `TextScaleControl` widget does both for you.
2224    pub fn set_text_scale(&mut self, factor: f32) {
2225        self.text_scale_request = Some(factor);
2226    }
2227}
2228
2229#[cfg(test)]
2230mod multi_window_tests {
2231    use super::*;
2232    use crate::window::state::WindowStateInit;
2233    use crate::window::{
2234        NoopWindowOps, TeksiloWindowId, WindowConfig, WindowOps, WindowPlacement, WindowState,
2235    };
2236    use std::cell::RefCell;
2237    use std::rc::Rc;
2238
2239    /// Recording implementation of `WindowOps` so tests can assert
2240    /// that `EventContext` routes each method through the trait.
2241    #[derive(Default)]
2242    struct RecordingOps {
2243        open_calls: RefCell<Vec<WindowConfig>>,
2244        focus_calls: RefCell<Vec<TeksiloWindowId>>,
2245        close_calls: RefCell<Vec<TeksiloWindowId>>,
2246        next_id: RefCell<u64>,
2247        // A fake registry so `find_window` / `window_state` / `windows`
2248        // can return values.
2249        states: RefCell<Vec<WindowState>>,
2250    }
2251
2252    impl RecordingOps {
2253        fn alloc_id(&self) -> TeksiloWindowId {
2254            let mut n = self.next_id.borrow_mut();
2255            *n += 1;
2256            TeksiloWindowId::new(*n)
2257        }
2258    }
2259
2260    impl WindowOps for RecordingOps {
2261        fn open_window(&mut self, config: WindowConfig) -> TeksiloWindowId {
2262            let id = self.alloc_id();
2263            let state = WindowState::new(WindowStateInit {
2264                id,
2265                string_id: config.string_id.clone(),
2266                placement: config.initial_placement,
2267                title: config.title.clone(),
2268                size: config.size,
2269                position: config.position.unwrap_or((0, 0)),
2270                focused: true,
2271                resizable: config.resizable,
2272                always_on_top: config.always_on_top,
2273            });
2274            self.states.borrow_mut().push(state);
2275            self.open_calls.borrow_mut().push(config);
2276            id
2277        }
2278
2279        fn find_window(&self, string_id: &str) -> Option<TeksiloWindowId> {
2280            self.states
2281                .borrow()
2282                .iter()
2283                .find(|s| s.string_id() == Some(string_id))
2284                .map(|s| s.id())
2285        }
2286
2287        fn window_state(&self, id: TeksiloWindowId) -> Option<WindowState> {
2288            self.states.borrow().iter().find(|s| s.id() == id).cloned()
2289        }
2290
2291        fn windows(&self) -> Vec<WindowState> {
2292            self.states.borrow().clone()
2293        }
2294
2295        fn focus_window(&mut self, id: TeksiloWindowId) {
2296            self.focus_calls.borrow_mut().push(id);
2297        }
2298
2299        fn close_window_by_id(&mut self, id: TeksiloWindowId) {
2300            self.close_calls.borrow_mut().push(id);
2301        }
2302    }
2303
2304    fn make_state(id: u64, string_id: Option<&str>) -> WindowState {
2305        WindowState::new(WindowStateInit {
2306            id: TeksiloWindowId::new(id),
2307            string_id: string_id.map(String::from),
2308            placement: WindowPlacement::Floating,
2309            title: "Test".into(),
2310            size: (800, 600),
2311            position: (0, 0),
2312            focused: true,
2313            resizable: true,
2314            always_on_top: false,
2315        })
2316    }
2317
2318    #[test]
2319    fn window_returns_current_window_state() {
2320        let state = make_state(1, Some("main"));
2321        let mut noop = NoopWindowOps;
2322        let ctx = EventContext::new().with_window_context(&mut noop, Some(state.clone()));
2323        assert_eq!(ctx.window().unwrap().id(), TeksiloWindowId::new(1));
2324        assert_eq!(ctx.window().unwrap().string_id(), Some("main"));
2325    }
2326
2327    #[test]
2328    fn window_is_none_without_context() {
2329        let ctx = EventContext::new();
2330        assert!(ctx.window().is_none());
2331    }
2332
2333    #[test]
2334    fn open_window_routes_through_ops() {
2335        let mut ops = RecordingOps::default();
2336        let main_state = make_state(1, Some("main"));
2337        let returned_id = {
2338            let mut ctx = EventContext::new().with_window_context(&mut ops, Some(main_state));
2339            ctx.open_window(WindowConfig::new().id("help").title("Help"))
2340        };
2341        assert_eq!(ops.open_calls.borrow().len(), 1);
2342        assert_eq!(
2343            ops.open_calls.borrow()[0].string_id.as_deref(),
2344            Some("help")
2345        );
2346        // Recording ops allocates ids 2+; 1 was reserved for `main`
2347        // only in this test — Recording's counter starts from 0, so the
2348        // first alloc yields 1.
2349        assert_eq!(returned_id, TeksiloWindowId::new(1));
2350    }
2351
2352    #[test]
2353    fn find_window_routes_through_ops() {
2354        let mut ops = RecordingOps::default();
2355        ops.states.borrow_mut().push(make_state(7, Some("foo")));
2356        let main_state = make_state(1, Some("main"));
2357        let ctx = EventContext::new().with_window_context(&mut ops, Some(main_state));
2358        assert_eq!(ctx.find_window("foo"), Some(TeksiloWindowId::new(7)));
2359        assert!(ctx.find_window("missing").is_none());
2360    }
2361
2362    #[test]
2363    fn focus_window_records_via_ops() {
2364        let mut ops = RecordingOps::default();
2365        let main_state = make_state(1, None);
2366        {
2367            let mut ctx = EventContext::new().with_window_context(&mut ops, Some(main_state));
2368            ctx.focus_window(TeksiloWindowId::new(42));
2369        }
2370        assert_eq!(
2371            ops.focus_calls.borrow().as_slice(),
2372            &[TeksiloWindowId::new(42)]
2373        );
2374    }
2375
2376    #[test]
2377    fn close_window_by_id_records_via_ops() {
2378        let mut ops = RecordingOps::default();
2379        let main_state = make_state(1, None);
2380        {
2381            let mut ctx = EventContext::new().with_window_context(&mut ops, Some(main_state));
2382            ctx.close_window_by_id(TeksiloWindowId::new(9));
2383        }
2384        assert_eq!(
2385            ops.close_calls.borrow().as_slice(),
2386            &[TeksiloWindowId::new(9)]
2387        );
2388    }
2389
2390    #[test]
2391    fn close_window_sets_guarded_flag_only() {
2392        let mut ctx = EventContext::new();
2393        ctx.close_window();
2394        assert!(
2395            ctx.close_window_requested,
2396            "close_window must raise the guarded-close flag"
2397        );
2398        assert!(
2399            !ctx.force_close_requested,
2400            "close_window must NOT raise the forced-close flag"
2401        );
2402    }
2403
2404    #[test]
2405    fn close_window_forced_sets_force_flag_only() {
2406        let mut ctx = EventContext::new();
2407        ctx.close_window_forced();
2408        assert!(
2409            ctx.force_close_requested,
2410            "close_window_forced must raise the forced-close flag"
2411        );
2412        assert!(
2413            !ctx.close_window_requested,
2414            "close_window_forced must NOT raise the guarded-close flag"
2415        );
2416    }
2417
2418    /// End-to-end: a handler calling `close_window_forced` during
2419    /// dispatch must transfer the flag onto the `WidgetTree` (the
2420    /// `collect_from_ctx` teardown), where the app loop drains it via
2421    /// `take_force_close_request` — separately from the guarded
2422    /// `take_close_window_request` flag.
2423    #[test]
2424    fn forced_close_flag_propagates_to_tree_and_drains_independently() {
2425        use crate::test_widgets::FillWidget;
2426        use crate::widget_tree::WidgetTree;
2427
2428        // `run_with_event_context` only runs the `collect_from_ctx`
2429        // teardown (which transfers ctx flags onto the tree) when the
2430        // tree has a root to anchor on, so give it one.
2431        let mut tree = WidgetTree::new();
2432        tree.add(FillWidget::new());
2433        tree.run_with_event_context(&mut NoopWindowOps, |ctx| ctx.close_window_forced());
2434        assert!(
2435            tree.take_force_close_request(),
2436            "forced-close flag must reach the tree"
2437        );
2438        assert!(
2439            !tree.take_close_window_request(),
2440            "a forced close must not also raise the guarded flag"
2441        );
2442
2443        // And the guarded path stays on its own channel.
2444        let mut tree = WidgetTree::new();
2445        tree.add(FillWidget::new());
2446        tree.run_with_event_context(&mut NoopWindowOps, |ctx| ctx.close_window());
2447        assert!(tree.take_close_window_request());
2448        assert!(!tree.take_force_close_request());
2449    }
2450
2451    #[test]
2452    fn windows_enumerates_via_ops() {
2453        let mut ops = RecordingOps::default();
2454        ops.states.borrow_mut().push(make_state(1, Some("a")));
2455        ops.states.borrow_mut().push(make_state(2, Some("b")));
2456        let main_state = make_state(1, Some("a"));
2457        let ctx = EventContext::new().with_window_context(&mut ops, Some(main_state));
2458        let ids: Vec<_> = ctx.windows().iter().map(|s| s.id()).collect();
2459        assert_eq!(ids, vec![TeksiloWindowId::new(1), TeksiloWindowId::new(2)]);
2460    }
2461
2462    #[test]
2463    fn standalone_context_returns_empty_windows_and_none_lookups() {
2464        let ctx = EventContext::new();
2465        assert!(ctx.find_window("anything").is_none());
2466        assert!(ctx.window_state(TeksiloWindowId::new(1)).is_none());
2467        assert!(ctx.windows().is_empty());
2468    }
2469
2470    #[test]
2471    #[should_panic(expected = "open_window called outside of a dispatch")]
2472    fn open_window_on_standalone_context_panics() {
2473        let mut ctx = EventContext::new();
2474        let _ = ctx.open_window(WindowConfig::new());
2475    }
2476
2477    #[test]
2478    fn open_modal_builds_window_config_from_request() {
2479        use crate::modal::{ModalContent, ModalRequest};
2480        let mut ops = RecordingOps::default();
2481        let main_state = make_state(1, Some("main"));
2482        let built_widget = Rc::new(RefCell::new(false));
2483        let built_widget_flag = built_widget.clone();
2484        let request = ModalRequest {
2485            content: ModalContent::Deferred(Box::new(move |_tree| {
2486                *built_widget_flag.borrow_mut() = true;
2487                // Return a dummy WidgetId — not used in this test since
2488                // the RecordingOps doesn't actually build the tree.
2489                crate::widget_id::WidgetId::default()
2490            })),
2491            presentation: crate::modal::ModalPresentation::NativeWindow,
2492            close_behavior: crate::modal::ModalCloseBehavior::default(),
2493            title: Some("Confirm".to_string()),
2494            size: Some((420, 180)),
2495            focus_target: None,
2496            on_dismiss: None,
2497        };
2498        {
2499            let mut ctx = EventContext::new().with_window_context(&mut ops, Some(main_state));
2500            let id = ctx.open_modal(request);
2501            assert!(id.is_some());
2502        }
2503        // open_modal is a thin wrapper over open_window — the config
2504        // it built must reach RecordingOps::open_window.
2505        let calls = ops.open_calls.borrow();
2506        assert_eq!(calls.len(), 1);
2507        let cfg = &calls[0];
2508        assert_eq!(cfg.title, "Confirm");
2509        assert_eq!(cfg.size, (420, 180));
2510        assert!(cfg.is_modal());
2511        assert_eq!(cfg.modal_parent(), Some(TeksiloWindowId::new(1)));
2512        // Cell is just to let us observe something reachable via cfg.root_builder;
2513        // the builder hasn't been called yet (RecordingOps records the config
2514        // but doesn't build the tree).
2515        let _ = built_widget;
2516    }
2517
2518    #[test]
2519    fn open_modal_requires_current_window() {
2520        use crate::modal::{ModalContent, ModalRequest};
2521        let mut ops = RecordingOps::default();
2522        let mut ctx = EventContext::new().with_window_context(&mut ops, None);
2523        let request = ModalRequest {
2524            content: ModalContent::Deferred(Box::new(|_tree| {
2525                crate::widget_id::WidgetId::default()
2526            })),
2527            presentation: crate::modal::ModalPresentation::NativeWindow,
2528            close_behavior: crate::modal::ModalCloseBehavior::default(),
2529            title: None,
2530            size: None,
2531            focus_target: None,
2532            on_dismiss: None,
2533        };
2534        assert!(ctx.open_modal(request).is_none());
2535    }
2536}