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