Skip to main content

teksilo_core/widget/
event_context.rs

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