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