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::widget_id::WidgetId;
5
6use super::CursorIcon;
7
8/// Selects which overlay-dismissal pathway runs after a handler
9/// returns. Last-write-wins: each `dismiss_*_overlays()` setter
10/// overwrites the previous choice. `None` (the default) falls
11/// through to draining individual ids from `overlay_dismissals`.
12#[derive(Debug, Clone, Copy, PartialEq, Eq)]
13pub(crate) enum DismissScope {
14    /// Dismiss every overlay in the stack, including hosts.
15    All,
16    /// Dismiss every overlay whose content is *not* a host surface
17    /// (`Tooltip`, `Dialog`, `AlertDialog`). Used by popover triggers
18    /// and pre-show cleanup.
19    AllExceptHosts,
20    /// Walk up from the source widget's containing overlay,
21    /// dismissing menu-like overlays and stopping at the first host
22    /// surface. Used by menu / dropdown item activation.
23    SelfChain,
24    /// Dismiss the topmost overlay only.
25    Top,
26}
27
28/// One queued "reveal this rectangle" request, drained after the handler
29/// returns and turned into a [`WidgetEvent::ScrollIntoView`] per clipping
30/// ancestor.
31///
32/// A struct rather than a tuple because the three modifiers (margin, alignment,
33/// motion) are independent and positional tuples of that width stop being
34/// readable at the call site.
35///
36/// [`WidgetEvent::ScrollIntoView`]: crate::event::WidgetEvent::ScrollIntoView
37#[derive(Debug, Clone, Copy, PartialEq)]
38pub(crate) struct ScrollRevealRequest {
39    /// The target, in absolute tree (window) coordinates.
40    pub(crate) rect: teksilo_canvas::Rect,
41    /// Breathing room to keep around the target, in logical pixels.
42    pub(crate) margin: f32,
43    /// Where the target should come to rest vertically.
44    pub(crate) align: crate::event::ScrollAlign,
45    /// Whether to jump or glide.
46    pub(crate) motion: crate::event::ScrollMotion,
47    /// **Whose** ancestors to walk, when that is not the widget whose handler
48    /// queued this.
49    ///
50    /// `None` means the source widget, which is right whenever a widget reveals
51    /// something inside itself. It is wrong — silently — whenever the rect belongs
52    /// to a *different* widget: a find banner's Next button asking for a match in
53    /// the prose, a toolbar revealing a row in the list below it. Those walk the
54    /// button's ancestors, which do not include the scroll container the rect lives
55    /// in, so nothing scrolls and the reveal is a no-op no error reports.
56    pub(crate) from: Option<crate::widget_id::WidgetId>,
57}
58
59/// Context available during event handling.
60pub struct EventContext<'ops> {
61    pub(crate) cursor_request: Option<CursorIcon>,
62    pub(crate) tree_mutations: Vec<TreeMutation>,
63    pub(crate) idle_callbacks: Vec<crate::idle::IdleCallback>,
64    pub(crate) modal_requests: Vec<crate::modal::ModalRequest>,
65    pub(crate) dismiss_modal: bool,
66    pub(crate) overlay_requests: Vec<crate::overlay::OverlayRequest>,
67    pub(crate) overlay_dismissals: Vec<crate::overlay::OverlayId>,
68    /// Content widget ids whose currently-shown overlay (if any) should
69    /// be dismissed. Resolved to an `OverlayId` via
70    /// `OverlayManager::find_by_content` at drain time. Lets a handler
71    /// dismiss an overlay it can only identify by content (e.g. a single
72    /// reusable tooltip surface) — the symmetric companion to
73    /// [`cancel_delayed_overlay`](EventContext::cancel_delayed_overlay).
74    pub(crate) overlay_content_dismissals: Vec<crate::widget_id::WidgetId>,
75    /// Overlay ids whose `auto_dismiss_after` timer should be paused
76    /// or resumed after the handler returns (`true` = pause, `false`
77    /// = resume). Drained by `WidgetTree::collect_from_ctx` against
78    /// `OverlayManager::pause_auto_dismiss` / `resume_auto_dismiss`,
79    /// after the dismissals in the same drain: a pause aimed at an
80    /// overlay the same handler dismissed is silently dropped. Used
81    /// by `ToastHost` for hover-pause.
82    pub(crate) overlay_pause_requests: Vec<(crate::overlay::OverlayId, bool)>,
83    /// The dismissal scope chosen by the handler, if any. Set by
84    /// `dismiss_all_overlays()` / `dismiss_all_except_hosts()` /
85    /// `dismiss_self_overlay_chain()` / `dismiss_top_overlay()` —
86    /// last setter wins. `None` falls through to draining the
87    /// per-id `overlay_dismissals` vec instead.
88    pub(crate) dismiss_scope: Option<DismissScope>,
89    /// Request to capture or release the pointer.
90    pub(crate) pointer_capture: Option<bool>,
91    /// Delayed overlay requests (request, delay, optional focus target).
92    pub(crate) delayed_overlay_requests: Vec<(
93        crate::overlay::OverlayRequest,
94        std::time::Duration,
95        Option<crate::widget_id::WidgetId>,
96    )>,
97    /// Timed overlay requests (request, auto-dismiss delay).
98    pub(crate) timed_overlay_requests: Vec<(crate::overlay::OverlayRequest, std::time::Duration)>,
99    /// Reveal overlay requests (request, caller-owned animated progress
100    /// signal, tween duration). The framework shows the overlay, then
101    /// drives `progress` 0 → 1 on show and 1 → 0 on dismiss, deferring
102    /// the actual stack removal until the roll-back tween completes —
103    /// the same deferral the fade path uses, minus the opacity scope.
104    /// The caller applies `progress` however it wants (e.g. an `Unroll`
105    /// width). See [`show_overlay_with_reveal`](EventContext::show_overlay_with_reveal).
106    pub(crate) reveal_overlay_requests: Vec<(
107        crate::overlay::OverlayRequest,
108        crate::signal::Signal<f32>,
109        std::time::Duration,
110    )>,
111    /// Dismiss descendant overlays of the source widget's containing overlay.
112    /// Optionally preserve the subtree rooted at a specific content widget ID.
113    pub(crate) dismiss_descendant_overlays: Vec<Option<crate::widget_id::WidgetId>>,
114    /// Cancel pending delayed overlays by content widget ID.
115    pub(crate) cancel_delayed_overlays: Vec<crate::widget_id::WidgetId>,
116    /// Widget IDs that need repainting (cross-widget signal propagation).
117    pub(crate) repaint_requests: Vec<crate::widget_id::WidgetId>,
118    /// Synthetic clicks to dispatch on target widgets after event processing.
119    pub(crate) synthetic_clicks: Vec<crate::widget_id::WidgetId>,
120    /// Focus requests — transfer focus to a specific widget (e.g., overlay content on open).
121    pub(crate) focus_requests: Vec<crate::widget_id::WidgetId>,
122    /// Focus-into requests — move focus to the *first focusable descendant* of
123    /// the given widget, with no fallback to the widget itself when the subtree
124    /// has none. The "dive into this region's content" intent (Enter on a tab
125    /// header → into the tab panel), distinct from `focus_requests` which
126    /// focuses the container itself as a last resort.
127    pub(crate) focus_into_requests: Vec<crate::widget_id::WidgetId>,
128    /// Rect-based "scroll this into view" requests, in **absolute tree
129    /// (window) coordinates**. Queued by [`ensure_visible`](EventContext::ensure_visible)
130    /// / [`ensure_visible_with_margin`](EventContext::ensure_visible_with_margin).
131    /// Drained in `collect_from_ctx`, which walks the ancestors of the widget
132    /// whose handler queued the request and dispatches
133    /// [`WidgetEvent::ScrollIntoView`](crate::event::WidgetEvent::ScrollIntoView)
134    /// to every `clips_children` scroll container that doesn't already fully
135    /// contain the rect — the same ancestor-walk the focus path uses, but
136    /// with a caller-supplied rectangle instead of a widget's own bounds
137    /// (so a caret, a virtualized row, or a scrolled-off tab header can be
138    /// revealed even though it is not itself a distinct focused node).
139    pub(crate) scroll_into_view_requests: Vec<ScrollRevealRequest>,
140    /// Widget-id-based "scroll this into view" requests, queued by
141    /// [`ensure_widget_visible`](EventContext::ensure_widget_visible) /
142    /// [`ensure_widget_visible_with_margin`](EventContext::ensure_widget_visible_with_margin).
143    /// Drained in `collect_from_ctx`, which resolves each id to its current
144    /// absolute arena bounds and walks *that widget's* ancestors (the target
145    /// widget itself excluded) dispatching
146    /// [`WidgetEvent::ScrollIntoView`](crate::event::WidgetEvent::ScrollIntoView).
147    /// The convenience form of the rect API for a target that is a real
148    /// mounted, non-virtualized child (a radio tile, a tab header) whose bounds
149    /// the framework already knows — the caller need not compute the rect.
150    pub(crate) scroll_widget_into_view_requests: Vec<(crate::widget_id::WidgetId, f32)>,
151    /// Keyboard-highlight tooltip requests: surface the tooltip of the given
152    /// (menu) item immediately and dismiss the previously-highlighted one.
153    /// Drained after the handler (see `event_dispatch_impl`). Only the last
154    /// entry per handler is honoured — a handler sets one highlight per key.
155    pub(crate) highlight_tooltip_requests: Vec<crate::widget_id::WidgetId>,
156    /// Drag start request: (source_widget_id, payload, optional_preview_widget).
157    pub(crate) drag_start_request: Option<(
158        crate::widget_id::WidgetId,
159        crate::drag_payload::DragPayload,
160        Option<Box<dyn crate::widget::Widget>>,
161    )>,
162    /// Cancel any active drag session.
163    pub(crate) cancel_drag: bool,
164    /// Whether the drag session active while this context is live was
165    /// started by an external (OS) drag. Read via `drag_is_external()`.
166    /// `false` for hand-constructed contexts and when no drag is active.
167    pub(crate) drag_is_external: bool,
168    /// Replace the tree-level theme. Drained after dispatch; triggers a
169    /// composite-widget rebuild and full repaint.
170    pub(crate) theme_request: Option<crate::styles::Theme>,
171    /// Request that the app follow the OS theme (native / system mode).
172    /// Drained after dispatch; the app switches to `ThemeMode::Native` and
173    /// recomputes the theme from the current OS colours. Parameterless so
174    /// `teksilo-widgets` never needs the app-layer `ThemeMode` enum.
175    pub(crate) follow_system_request: bool,
176    /// Replace the tree-level locale identifier. Drained after dispatch;
177    /// triggers a composite-widget rebuild and full repaint.
178    pub(crate) locale_request: Option<String>,
179    /// Set the user-controlled text-scale factor. Drained after dispatch and
180    /// fanned out to every window; grows all text without a rebuild.
181    pub(crate) text_scale_request: Option<f32>,
182    /// Set by `request_frame()`; consumed by the event dispatcher which
183    /// forwards it to `WidgetTree::request_frame()` so the next layout
184    /// pass advances the per-frame tick signal.
185    pub(crate) frame_requested: bool,
186    /// Optional reference to the tree's app-state registry, so handlers
187    /// can look up application-scoped values via `app_state::<T>()`.
188    /// Populated by the dispatcher before running each handler; `None`
189    /// for hand-constructed contexts in tests.
190    pub(crate) app_context: Option<std::rc::Rc<crate::event_source::TreeAppContext>>,
191    /// App-level window-ops sink. Injected by the dispatcher so
192    /// handlers can reach the multi-window API (`open_window`,
193    /// `focus_window`, …) synchronously. For `EventContext`
194    /// instances constructed outside a dispatch (standalone trees,
195    /// tests) this is `None` and the multi-window methods no-op /
196    /// return `None`.
197    pub(crate) window_ops: Option<&'ops mut dyn crate::window::WindowOps>,
198    /// [`WindowState`](crate::window::WindowState) for the window
199    /// this tree belongs to. Cloned from the tree at construction.
200    /// `None` for standalone trees.
201    pub(crate) current_window: Option<crate::window::WindowState>,
202    /// Snapshot of the tree's occlusion-aware window-active state
203    /// (`focused AND not occluded`) at construction time. Distinct from
204    /// `current_window.focused()` (raw OS focus, no occlusion). Read by
205    /// [`window_active`](Self::window_active). Defaults `true` (matches the
206    /// tree's initial value) for standalone / test contexts.
207    pub(crate) tree_window_active: bool,
208    /// Last `PointerMove` position observed by the tree. Snapshotted
209    /// at handler-invocation time so widgets that don't see the live
210    /// pointer event (e.g. an `on_hover` callback that fires on the
211    /// boundary edge) can still query "where is the cursor right
212    /// now". Read by the safe-triangle submenu hover gate.
213    pub(crate) tree_pointer_position: Option<teksilo_canvas::Point>,
214    /// True when the in-flight pointer press's hit target is a strict
215    /// descendant of the widget whose handler is currently running and that
216    /// descendant carries its own tap gesture (a chevron, checkbox, inline
217    /// button). Set per-node by the dispatcher for `PointerDown`/`PointerUp`.
218    /// Read via [`press_claimed_by_interactive_child`](Self::press_claimed_by_interactive_child).
219    pub(crate) press_claimed_by_interactive_child: bool,
220    /// Per-content-widget overlay bounds snapshotted at handler
221    /// invocation. A flat vec is fine — open overlays are typically
222    /// 0–3 per tree. Read by the safe-triangle submenu hover gate
223    /// via [`EventContext::overlay_bounds_for_content`].
224    pub(crate) overlay_bounds_snapshot: Vec<(WidgetId, teksilo_canvas::Rect)>,
225    /// Intents queued by handlers via `send_intent`. Drained by the
226    /// tree after event dispatch and routed source-widget → root.
227    pub(crate) pending_intents: Vec<crate::intent::Intent>,
228    /// The dispatcher sets this to the appropriate
229    /// [`IntentSource`](crate::telemetry::IntentSource) before
230    /// invoking a typed handler (menu select → `Menu`, AccessKit
231    /// action → `Accessibility`, on_tap / button activation →
232    /// `Handler`, …). `send_intent` reads it and stamps the intent
233    /// before queuing. `None` outside a managed handler — bare
234    /// programmatic sends keep their `Intent::source` value
235    /// (default `Programmatic`).
236    pub(crate) current_source: Option<crate::telemetry::IntentSource>,
237    /// Key-capture callback armed via `ctx.begin_key_capture(...)`.
238    /// The callback + its shared slot are installed on the tree by
239    /// `collect_from_ctx`. Only one per ctx; the last caller wins.
240    pub(crate) pending_key_capture: Option<crate::shortcut::KeyCaptureSlot>,
241    /// Set to request cancellation of any armed key capture.
242    pub(crate) cancel_key_capture: bool,
243    /// Deferred mutations to the tree's [`ShortcutRegistry`](crate::shortcut::ShortcutRegistry),
244    /// typically issued by settings-UI buttons to rebind or clear
245    /// overrides. Applied in `collect_from_ctx` after the handler
246    /// returns.
247    pub(crate) pending_shortcut_mutations: Vec<ShortcutMutation>,
248    /// Requests that the app-level event loop close the window this
249    /// tree belongs to. Drained after dispatch via
250    /// `WidgetTree::take_close_window_request`. Routed through the
251    /// window's close guard (if any) — see
252    /// [`WindowConfig::on_close_requested`](crate::window::WindowConfig::on_close_requested).
253    pub(crate) close_window_requested: bool,
254    /// Like [`close_window_requested`](Self::close_window_requested), but
255    /// **bypasses** the window's close guard. Set by
256    /// [`close_window_forced`](Self::close_window_forced). Drained after
257    /// dispatch via `WidgetTree::take_force_close_request`. The escape
258    /// hatch a confirmation dialog uses once the user confirms.
259    pub(crate) force_close_requested: bool,
260    /// Set by [`request_accessibility_update`](EventContext::request_accessibility_update);
261    /// drained in `collect_from_ctx` to set `WidgetTree::a11y_dirty`, forcing the
262    /// next `sync_accessibility` to re-walk the AccessKit tree. The general lever for a
263    /// composing widget that restructured its subtree in a way that changes the AT tree
264    /// (relayout alone no longer re-walks AT).
265    pub(crate) request_a11y_update: bool,
266    /// Messages queued by [`announce`](EventContext::announce) /
267    /// [`announce_with`](EventContext::announce_with), drained into the tree's
268    /// own live regions by `collect_from_ctx`. See [`crate::announcer`].
269    pub(crate) announcements: Vec<(String, crate::announcer::Politeness)>,
270    /// Layout direction (LTR/RTL) of the hosting tree, snapshotted at
271    /// handler-invocation time by `make_event_context`. Read via
272    /// [`is_rtl`](EventContext::is_rtl) so pointer / keyboard / drag
273    /// handlers can mirror their x-axis logic live — a runtime locale
274    /// switch dirties the tree but does **not** rebuild, so direction
275    /// must be read here rather than captured at `build()` time.
276    /// Defaults to `LeftToRight` for hand-constructed (test) contexts.
277    pub(crate) layout_direction: crate::environment::LayoutDirection,
278    /// Debug-only WCAG 3.2.1 guard: `Some(flag)` where `flag` is set while a
279    /// focus-change dispatch is running. `open_window` / `focus_window` warn if
280    /// invoked while it reads `true` (a focus handler changing context). `None`
281    /// for hand-constructed (test) contexts.
282    pub(crate) in_focus_dispatch: Option<std::rc::Rc<std::cell::Cell<bool>>>,
283}
284
285/// Deferred edit to the tree's shortcut registry, queued on an
286/// `EventContext` and applied in `collect_from_ctx`.
287#[derive(Debug, Clone)]
288pub(crate) enum ShortcutMutation {
289    RebindPrimary {
290        id: String,
291        keystroke: Option<crate::shortcut::KeyStroke>,
292    },
293    RebindSecondary {
294        id: String,
295        keystroke: Option<crate::shortcut::KeyStroke>,
296    },
297    ClearOverride {
298        id: String,
299    },
300}
301
302/// A structural change to the widget tree, deferred until after event dispatch.
303pub(crate) enum TreeMutation {
304    SetDormant(WidgetId),
305    Activate(WidgetId),
306    Destroy(WidgetId),
307    /// Typed mutable access to a mounted widget, applied in
308    /// `apply_tree_mutations` where `&mut arena` is live. The boxed closure
309    /// downcasts the node's `as_any_mut()` to the requested concrete type;
310    /// `dirty` selects the post-mutation re-render level.
311    WithWidgetMut {
312        id: WidgetId,
313        dirty: crate::binding::BindingLevel,
314        apply: Box<dyn FnOnce(&mut dyn std::any::Any)>,
315    },
316    /// Re-run one widget's `build()` **now**, inside `apply_tree_mutations`,
317    /// rather than marking it for the next layout pass. See
318    /// [`EventContext::materialize_now`].
319    MaterializeNow(WidgetId),
320}
321
322// Manual `Debug`: the `WithWidgetMut` closure is not `Debug`.
323impl std::fmt::Debug for TreeMutation {
324    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
325        match self {
326            Self::SetDormant(id) => f.debug_tuple("SetDormant").field(id).finish(),
327            Self::Activate(id) => f.debug_tuple("Activate").field(id).finish(),
328            Self::MaterializeNow(id) => f.debug_tuple("MaterializeNow").field(id).finish(),
329            Self::Destroy(id) => f.debug_tuple("Destroy").field(id).finish(),
330            Self::WithWidgetMut { id, dirty, .. } => f
331                .debug_struct("WithWidgetMut")
332                .field("id", id)
333                .field("dirty", dirty)
334                .finish_non_exhaustive(),
335        }
336    }
337}
338
339impl<'ops> EventContext<'ops> {
340    pub(crate) fn new() -> Self {
341        Self {
342            cursor_request: None,
343            tree_mutations: Vec::new(),
344            idle_callbacks: Vec::new(),
345            modal_requests: Vec::new(),
346            dismiss_modal: false,
347            overlay_requests: Vec::new(),
348            overlay_dismissals: Vec::new(),
349            overlay_content_dismissals: Vec::new(),
350            overlay_pause_requests: Vec::new(),
351            dismiss_scope: None,
352            pointer_capture: None,
353            delayed_overlay_requests: Vec::new(),
354            timed_overlay_requests: Vec::new(),
355            reveal_overlay_requests: Vec::new(),
356            dismiss_descendant_overlays: Vec::new(),
357            cancel_delayed_overlays: Vec::new(),
358            repaint_requests: Vec::new(),
359            synthetic_clicks: Vec::new(),
360            focus_requests: Vec::new(),
361            focus_into_requests: Vec::new(),
362            scroll_into_view_requests: Vec::new(),
363            scroll_widget_into_view_requests: Vec::new(),
364            highlight_tooltip_requests: Vec::new(),
365            drag_start_request: None,
366            cancel_drag: false,
367            drag_is_external: false,
368            theme_request: None,
369            follow_system_request: false,
370            locale_request: None,
371            text_scale_request: None,
372            frame_requested: false,
373            app_context: None,
374            pending_intents: Vec::new(),
375            current_source: None,
376            pending_key_capture: None,
377            cancel_key_capture: false,
378            pending_shortcut_mutations: Vec::new(),
379            close_window_requested: false,
380            force_close_requested: false,
381            request_a11y_update: false,
382            announcements: Vec::new(),
383            window_ops: None,
384            current_window: None,
385            tree_window_active: true,
386            tree_pointer_position: None,
387            press_claimed_by_interactive_child: false,
388            overlay_bounds_snapshot: Vec::new(),
389            layout_direction: crate::environment::LayoutDirection::LeftToRight,
390            in_focus_dispatch: None,
391        }
392    }
393
394    /// Snapshot the hosting tree's layout direction. Called by
395    /// `make_event_context` once per event batch so x-axis handlers
396    /// (resize, drag-reorder, arrow-key navigation) can mirror under
397    /// RTL without a rebuild.
398    pub(crate) fn with_layout_direction(
399        mut self,
400        direction: crate::environment::LayoutDirection,
401    ) -> Self {
402        self.layout_direction = direction;
403        self
404    }
405
406    /// Layout direction of the hosting tree at dispatch time.
407    pub fn layout_direction(&self) -> crate::environment::LayoutDirection {
408        self.layout_direction
409    }
410
411    /// Whether the hosting tree is laid out right-to-left. Mirrors
412    /// [`LayoutContext::is_rtl`](crate::widget::LayoutContext::is_rtl)
413    /// for the event-dispatch side.
414    pub fn is_rtl(&self) -> bool {
415        self.layout_direction == crate::environment::LayoutDirection::RightToLeft
416    }
417
418    /// Attach a per-dispatch snapshot of read-only tree query state
419    /// (current pointer position, overlay bounds). Called by
420    /// `WidgetTree::make_event_context` once per event batch. Test
421    /// `EventContext`s that don't go through that path stay with
422    /// empty snapshots — handlers must treat both reads as `None`-
423    /// safe.
424    pub(crate) fn with_query_snapshot(
425        mut self,
426        pointer: Option<teksilo_canvas::Point>,
427        overlays: Vec<(WidgetId, teksilo_canvas::Rect)>,
428    ) -> Self {
429        self.tree_pointer_position = pointer;
430        self.overlay_bounds_snapshot = overlays;
431        self
432    }
433
434    /// Attach the app-level window-ops sink and the hosting tree's
435    /// [`WindowState`](crate::window::WindowState). Called by the
436    /// dispatcher once per event batch so handlers can reach the
437    /// multi-window API synchronously.
438    pub(crate) fn with_window_context(
439        mut self,
440        ops: &'ops mut dyn crate::window::WindowOps,
441        current_window: Option<crate::window::WindowState>,
442    ) -> Self {
443        self.window_ops = Some(ops);
444        self.current_window = current_window;
445        self
446    }
447
448    /// Snapshot the tree's occlusion-aware window-active state. Called by
449    /// `make_event_context` once per event batch so handlers can read
450    /// [`window_active`](Self::window_active).
451    pub(crate) fn with_window_active(mut self, active: bool) -> Self {
452        self.tree_window_active = active;
453        self
454    }
455
456    /// Attach the tree's shared "inside focus dispatch" flag (WCAG 3.2.1
457    /// debug guard). See [`EventContext::open_window`].
458    pub(crate) fn with_focus_dispatch_flag(
459        mut self,
460        flag: std::rc::Rc<std::cell::Cell<bool>>,
461    ) -> Self {
462        self.in_focus_dispatch = Some(flag);
463        self
464    }
465
466    /// Debug-only: warn (once per call) if a context change is being made from
467    /// inside a focus-change dispatch — a WCAG 3.2.1 (On Focus) anti-pattern.
468    /// Compiled out entirely in release builds.
469    #[inline]
470    fn warn_if_context_change_in_focus_dispatch(&self, what: &str) {
471        #[cfg(debug_assertions)]
472        if self.in_focus_dispatch.as_ref().is_some_and(|f| f.get()) {
473            eprintln!(
474                "[teksilo a11y] WCAG 3.2.1 (On Focus): `{what}` was called from \
475                 inside an on_focus handler. Changing context (opening/focusing a \
476                 window, navigating) merely because a control received focus \
477                 surprises keyboard users tabbing through the UI. Move this to an \
478                 explicit activation handler (on_tap / on_activate / a shortcut)."
479            );
480        }
481        let _ = what;
482    }
483
484    /// Attach the tree's app-state registry so handlers can look up
485    /// application-scoped values (`ClipboardHandle`, `SharedTypesetter`,
486    /// …). Called by the dispatcher once per event batch.
487    pub(crate) fn with_app_context(
488        mut self,
489        ctx: std::rc::Rc<crate::event_source::TreeAppContext>,
490    ) -> Self {
491        self.app_context = Some(ctx);
492        self
493    }
494
495    /// Record whether the drag session active while this context is live
496    /// originated from an external (OS) drag. Set by `make_event_context`.
497    pub(crate) fn with_drag_external(mut self, is_external: bool) -> Self {
498        self.drag_is_external = is_external;
499        self
500    }
501
502    /// Whether a drag is currently in flight that was started by an external
503    /// (OS) drag-and-drop (files / text / URLs from another application),
504    /// rather than by an in-app `start_drag`. Useful in `on_drag_leave` /
505    /// `on_drag_tick` handlers, which don't receive the payload directly;
506    /// in `on_drag_hover` / `on_drop` prefer `payload.is_external()`.
507    pub fn drag_is_external(&self) -> bool {
508        self.drag_is_external
509    }
510
511    /// Look up an application-scoped value by type. Mirrors
512    /// `BuildContext::app_state`. Returns `None` when the handler was
513    /// invoked without a registry (hand-constructed `EventContext` in
514    /// tests, or when no value of that type was registered).
515    pub fn app_state<T: 'static>(&self) -> Option<&T> {
516        self.app_context
517            .as_ref()
518            .and_then(|ctx| ctx.app_state::<T>())
519    }
520
521    /// Borrow the [`AppEventPoster`](crate::AppEventPoster) installed
522    /// by the framework. Used by integrations that need to post
523    /// typed payloads back to the UI loop from a worker thread
524    /// (`teksilo_platform::file_dialog`'s `RfdAsyncBackend`, future
525    /// async-result features). Returns `None` for hand-constructed
526    /// `EventContext`s in tests.
527    pub fn poster(&self) -> Option<&std::sync::Arc<dyn crate::AppEventPoster>> {
528        self.app_context.as_ref().and_then(|ctx| ctx.poster())
529    }
530
531    /// Ask the tree to pump one more frame after this handler returns.
532    /// Use from event handlers that kick off per-frame work (pending
533    /// document events to drain, drag-select auto-scroll, caret blink
534    /// restart on focus). See `WidgetTree::request_frame` for the
535    /// draw-when-needed contract.
536    pub fn request_frame(&mut self) {
537        self.frame_requested = true;
538    }
539
540    /// Dispatch an [`Intent`](crate::intent::Intent) as if the source
541    /// widget pressed its keyboard shortcut. The framework walks
542    /// source-widget → root after the current handler returns,
543    /// invoking any matching [`Action`](crate::action::Action) it
544    /// finds. Unmatched intents are silently dropped.
545    ///
546    /// The intent's `source` is overridden by the dispatcher's
547    /// current handler-source label (`current_source`) when one is
548    /// active. This is how the framework distinguishes
549    /// `IntentSource::Handler` (button taps, generic on_tap) from
550    /// `IntentSource::Menu`, `IntentSource::Accessibility`, etc.
551    /// Programmatic callers outside any handler pass through with
552    /// `IntentSource::Programmatic` (the default).
553    pub fn send_intent(&mut self, intent: impl Into<crate::intent::Intent>) {
554        let mut intent: crate::intent::Intent = intent.into();
555        if let Some(src) = self.current_source {
556            intent.source = src;
557        }
558        self.pending_intents.push(intent);
559    }
560
561    /// Run a closure with the given `IntentSource` active. Any
562    /// `ctx.send_intent(...)` issued from within the closure will
563    /// be tagged with this source instead of the dispatcher's
564    /// default (`Handler` / `Shortcut` / `Accessibility`).
565    ///
566    /// The previous source is restored after the closure returns.
567    /// Panic during the closure unwinds the dispatcher's whole
568    /// frame, so the EventContext is destroyed before the next
569    /// dispatch — no need for a panic-safe drop guard.
570    ///
571    /// Used by framework widgets that want a more specific source
572    /// label than the default — `MenuItem` wraps its activation
573    /// handler to emit `IntentSource::Menu`, etc.
574    pub fn with_intent_source<R>(
575        &mut self,
576        source: crate::telemetry::IntentSource,
577        f: impl FnOnce(&mut Self) -> R,
578    ) -> R {
579        let prev = self.current_source.replace(source);
580        let r = f(self);
581        self.current_source = prev;
582        r
583    }
584
585    /// Arm a one-shot key-capture callback, returning a
586    /// [`CaptureHandle`](crate::shortcut::CaptureHandle) whose `Drop`
587    /// cancels the capture if it hasn't fired yet. The next `KeyDown`
588    /// bypasses shortcut resolution and invokes the callback with:
589    /// - the captured [`KeyStroke`](crate::shortcut::KeyStroke)
590    /// - mutable access to the registry (rebinds in-place)
591    /// - a mutable [`EventContext`] (emit commands, send intents,
592    ///   dismiss overlays, …)
593    ///
594    /// The handle must be stored somewhere with an appropriate
595    /// lifetime (typically in the calling widget's state) or the
596    /// capture will be cancelled immediately when the returned
597    /// handle drops at end of scope.
598    pub fn begin_key_capture(
599        &mut self,
600        callback: impl FnOnce(
601            crate::shortcut::KeyStroke,
602            &mut crate::shortcut::ShortcutRegistry,
603            &mut EventContext,
604        ) + 'static,
605    ) -> crate::shortcut::CaptureHandle {
606        let slot: crate::shortcut::KeyCaptureSlot =
607            std::rc::Rc::new(std::cell::RefCell::new(Some(Box::new(callback))));
608        self.pending_key_capture = Some(slot.clone());
609        self.cancel_key_capture = false;
610        crate::shortcut::CaptureHandle::new(slot)
611    }
612
613    /// Cancel any key capture armed earlier in this handler or via
614    /// `WidgetTree::begin_key_capture` before the handler ran.
615    pub fn cancel_key_capture(&mut self) {
616        self.pending_key_capture = None;
617        self.cancel_key_capture = true;
618    }
619
620    /// Queue a deferred rebind of the primary keystroke for the
621    /// registered shortcut with the given id. Applied by the tree
622    /// after the current handler returns. Use `None` to explicitly
623    /// unbind the slot.
624    pub fn rebind_shortcut_primary(
625        &mut self,
626        id: impl Into<String>,
627        keystroke: Option<crate::shortcut::KeyStroke>,
628    ) {
629        self.pending_shortcut_mutations
630            .push(ShortcutMutation::RebindPrimary {
631                id: id.into(),
632                keystroke,
633            });
634    }
635
636    /// Queue a deferred rebind of the secondary keystroke for the
637    /// registered shortcut with the given id.
638    pub fn rebind_shortcut_secondary(
639        &mut self,
640        id: impl Into<String>,
641        keystroke: Option<crate::shortcut::KeyStroke>,
642    ) {
643        self.pending_shortcut_mutations
644            .push(ShortcutMutation::RebindSecondary {
645                id: id.into(),
646                keystroke,
647            });
648    }
649
650    /// Queue a deferred clear of any user override for the given
651    /// shortcut id, restoring its declared defaults.
652    pub fn clear_shortcut_override(&mut self, id: impl Into<String>) {
653        self.pending_shortcut_mutations
654            .push(ShortcutMutation::ClearOverride { id: id.into() });
655    }
656
657    /// Request that the application close the window this tree
658    /// belongs to. Drained by the app event loop after the handler
659    /// returns. Typical use: title-bar close button handlers.
660    ///
661    /// This is a *guarded* close: if the window declared a close guard
662    /// via
663    /// [`WindowConfig::on_close_requested`](crate::window::WindowConfig::on_close_requested)
664    /// or [`can_close`](crate::window::WindowConfig::can_close), that
665    /// guard runs first and may veto the close. To skip the guard (e.g.
666    /// from the confirmation dialog the guard itself opened), use
667    /// [`close_window_forced`](Self::close_window_forced).
668    pub fn close_window(&mut self) {
669        self.close_window_requested = true;
670    }
671
672    /// Request that the application close this tree's window
673    /// **unconditionally**, bypassing any close guard declared via
674    /// [`WindowConfig::on_close_requested`](crate::window::WindowConfig::on_close_requested)
675    /// / [`can_close`](crate::window::WindowConfig::can_close).
676    ///
677    /// This is the second half of the veto-then-reissue pattern: the
678    /// guard returns [`CloseResponse::Veto`](crate::window::CloseResponse::Veto)
679    /// and opens a confirmation dialog; the dialog's "close anyway"
680    /// button calls `close_window_forced` so the window actually closes
681    /// without re-triggering the guard.
682    pub fn close_window_forced(&mut self) {
683        self.force_close_requested = true;
684    }
685
686    // -------------------- Multi-window API --------------------
687
688    /// The [`WindowState`](crate::window::WindowState) for the window
689    /// hosting this handler. `None` only for handlers run outside
690    /// of an app (hand-constructed `EventContext` in tests).
691    /// Cursor position at the moment this handler was invoked. `None`
692    /// when no `PointerMove` has reached the tree yet, or when the
693    /// context was constructed without a tree-side snapshot (e.g.
694    /// hand-built `EventContext`s in tests). Used by the safe-triangle
695    /// submenu hover gate.
696    pub fn tree_pointer_position(&self) -> Option<teksilo_canvas::Point> {
697        self.tree_pointer_position
698    }
699
700    /// True when the in-flight pointer press's hit target is a strict
701    /// descendant of THIS handler's widget that carries its own tap gesture
702    /// (chevron, checkbox, inline button). A row/container that selects on
703    /// press should early-return `EventResponse::Ignored` when this is set, so
704    /// the press belongs to the inner control, not the row. Only meaningful
705    /// inside `on_pointer_event` handlers for `PointerDown`/`PointerUp`.
706    pub fn press_claimed_by_interactive_child(&self) -> bool {
707        self.press_claimed_by_interactive_child
708    }
709
710    /// Look up the bounds rect of an open overlay by its root content
711    /// widget id. Returns `None` when no such overlay is currently
712    /// active. The snapshot is taken once per dispatch; mid-handler
713    /// `show_overlay` calls will not appear here. Used by the
714    /// safe-triangle submenu hover gate.
715    pub fn overlay_bounds_for_content(&self, content_id: WidgetId) -> Option<teksilo_canvas::Rect> {
716        self.overlay_bounds_snapshot
717            .iter()
718            .find(|(cid, _)| *cid == content_id)
719            .map(|(_, r)| *r)
720    }
721
722    pub fn window(&self) -> Option<&crate::window::WindowState> {
723        self.current_window.as_ref()
724    }
725
726    /// Whether the host window is currently active (`focused AND not
727    /// occluded`) — the occlusion-aware companion to
728    /// `self.window().map(|w| w.focused())` (raw OS focus). Snapshotted at
729    /// context construction. Matches [`BuildContext::window_active`].
730    ///
731    /// [`BuildContext::window_active`]: crate::build_context::BuildContext::window_active
732    pub fn window_active(&self) -> bool {
733        self.tree_window_active
734    }
735
736    /// Open a new window, creating the winit-level surface
737    /// synchronously. The returned id is immediately valid for
738    /// [`focus_window`](Self::focus_window),
739    /// [`window_state`](Self::window_state), and
740    /// [`find_window`](Self::find_window).
741    ///
742    /// Panics when called from a handler on a standalone `WidgetTree`
743    /// (no app context) — tests should not invoke this method.
744    pub fn open_window(
745        &mut self,
746        config: crate::window::WindowConfig,
747    ) -> crate::window::TeksiloWindowId {
748        self.warn_if_context_change_in_focus_dispatch("open_window");
749        self.window_ops
750            .as_deref_mut()
751            .expect("open_window called outside of a dispatch")
752            .open_window(config)
753    }
754
755    /// Find a window by the string id assigned via
756    /// [`WindowConfig::id`](crate::window::WindowConfig::id). Returns
757    /// `None` if no open window carries that id.
758    pub fn find_window(&self, string_id: &str) -> Option<crate::window::TeksiloWindowId> {
759        self.window_ops.as_deref()?.find_window(string_id)
760    }
761
762    /// Read the [`WindowState`](crate::window::WindowState) for a
763    /// specific window.
764    pub fn window_state(
765        &self,
766        id: crate::window::TeksiloWindowId,
767    ) -> Option<crate::window::WindowState> {
768        self.window_ops.as_deref()?.window_state(id)
769    }
770
771    /// Snapshot of every live window's state.
772    pub fn windows(&self) -> Vec<crate::window::WindowState> {
773        self.window_ops
774            .as_deref()
775            .map(|o| o.windows())
776            .unwrap_or_default()
777    }
778
779    /// Raise a window to the front and give it keyboard focus.
780    pub fn focus_window(&mut self, id: crate::window::TeksiloWindowId) {
781        self.warn_if_context_change_in_focus_dispatch("focus_window");
782        if let Some(ops) = self.window_ops.as_deref_mut() {
783            ops.focus_window(id);
784        }
785    }
786
787    /// Request an xdg-activation token for `id` (see
788    /// [`WindowOps::request_activation_token`](crate::window::WindowOps::request_activation_token)).
789    /// `cb` fires once with the token string, or `None` where the platform can't
790    /// provide one — used to hand a token to a child process ("open in new
791    /// window") or an IPC peer that will raise itself on Wayland.
792    pub fn request_activation_token(
793        &mut self,
794        id: crate::window::TeksiloWindowId,
795        cb: Box<dyn FnOnce(Option<String>)>,
796    ) {
797        if let Some(ops) = self.window_ops.as_deref_mut() {
798            ops.request_activation_token(id, cb);
799        } else {
800            cb(None);
801        }
802    }
803
804    /// Request an activation token for the **current** window (see
805    /// [`WindowOps::request_activation_token_self`](crate::window::WindowOps::request_activation_token_self)).
806    /// Use this from a widget handler to mint a token from *this* focused window
807    /// to hand to another window or process — it works mid-dispatch, unlike the
808    /// id-based variant.
809    pub fn request_activation_token_self(&mut self, cb: Box<dyn FnOnce(Option<String>)>) {
810        if let Some(ops) = self.window_ops.as_deref_mut() {
811            ops.request_activation_token_self(cb);
812        } else {
813            cb(None);
814        }
815    }
816
817    /// Close a specific window by id. Equivalent to
818    /// [`close_window`](Self::close_window) when `id` is the current
819    /// window's id.
820    pub fn close_window_by_id(&mut self, id: crate::window::TeksiloWindowId) {
821        if let Some(ops) = self.window_ops.as_deref_mut() {
822            ops.close_window_by_id(id);
823        }
824    }
825
826    /// Report the focused text widget's caret rectangle (window-logical
827    /// pixels) so the platform can position the OS IME candidate window at
828    /// the insertion point. Text-editing widgets call this whenever the
829    /// caret moves. No-op outside a dispatch / on a standalone tree.
830    pub fn set_ime_cursor_area(&mut self, area: teksilo_canvas::Rect) {
831        if let Some(ops) = self.window_ops.as_deref_mut() {
832            ops.set_ime_cursor_area(area);
833        }
834    }
835
836    /// Resolve the platform parent handle of the window currently
837    /// dispatching the event. Used by native-dialog integrations
838    /// (`teksilo_platform::file_dialog`) to parent OS dialogs to the
839    /// originating Teksilo window.
840    ///
841    /// Returns `None` when called from a standalone `WidgetTree` (no
842    /// app-level `WindowOps` sink), or when the platform refuses to
843    /// surface a handle (rare; mostly during teardown).
844    pub fn parent_window_handle(&self) -> Option<crate::raw_handle::ParentHandle> {
845        self.window_ops.as_deref()?.current_parent_handle()
846    }
847
848    /// Request a cursor icon change.
849    pub fn set_cursor(&mut self, cursor: CursorIcon) {
850        self.cursor_request = Some(cursor);
851    }
852
853    /// Set a widget subtree as dormant (preserves state, releases rendering).
854    pub fn set_dormant(&mut self, id: WidgetId) {
855        self.tree_mutations.push(TreeMutation::SetDormant(id));
856    }
857
858    /// Activate a dormant widget subtree.
859    pub fn activate(&mut self, id: WidgetId) {
860        self.tree_mutations.push(TreeMutation::Activate(id));
861    }
862
863    /// Destroy a widget subtree (removes from arena entirely, state is gone).
864    pub fn destroy(&mut self, id: WidgetId) {
865        self.tree_mutations.push(TreeMutation::Destroy(id));
866    }
867
868    /// Imperatively mutate a mounted widget by id, downcasting to the
869    /// concrete type `W`.
870    ///
871    /// The mutation is **deferred**: the closure runs after the handler
872    /// returns, inside `apply_tree_mutations`, where the framework holds
873    /// `&mut` arena access (a handler cannot re-borrow the arena to reach
874    /// another node, so this is the only safe channel — the same model as
875    /// [`destroy`](Self::destroy)). After the closure runs, the target is
876    /// dirty-marked at `dirty` so the mutation takes visual effect.
877    ///
878    /// The target widget must override `Widget::as_any_mut` to return
879    /// `Some(self)`. If the id is gone or is not a `W`, the closure is a
880    /// no-op in release and a `debug_assert` failure in debug — it never
881    /// silently mutates the wrong widget.
882    ///
883    /// Use it for per-view state a handler can't otherwise reach — e.g.
884    /// `SceneView::ensure_visible(...)` (camera) after the view is mounted:
885    /// ```ignore
886    /// ctx.with_widget_mut::<SceneView>(view_id, BindingLevel::Relayout, |v| {
887    ///     v.ensure_visible(card_rect, 40.0);
888    /// });
889    /// ```
890    /// For scene *content*, prefer the shared `SceneModel` handle (`view.model()`)
891    /// — its mutators are `&self`, so a handler holding a clone can drive the
892    /// scene directly and every attached view reconciles, no `with_widget_mut`
893    /// needed.
894    pub fn with_widget_mut<W: 'static>(
895        &mut self,
896        id: WidgetId,
897        dirty: crate::binding::BindingLevel,
898        f: impl FnOnce(&mut W) + 'static,
899    ) {
900        self.tree_mutations.push(TreeMutation::WithWidgetMut {
901            id,
902            dirty,
903            apply: Box::new(move |any| match any.downcast_mut::<W>() {
904                Some(w) => f(w),
905                None => debug_assert!(
906                    false,
907                    "with_widget_mut: widget {id:?} is not the requested type (or does not \
908                     override Widget::as_any_mut)"
909                ),
910            }),
911        });
912    }
913
914    /// Re-run one widget's `build()` **during this handler's drain**, before
915    /// overlays are shown and before focus requests are applied — rather than
916    /// dirty-marking it for the next layout pass, which is what every other
917    /// rebuild trigger does.
918    ///
919    /// It exists for one shape:
920    /// [`DeferredSubtree`](crate::deferred_subtree::DeferredSubtree) content
921    /// that a handler is *about to depend on*. Opening a popover activates its
922    /// content, shows an overlay anchored to it, and moves focus into it — all
923    /// three inside the same drain (see `collect_from_ctx`). A deferred panel
924    /// marked for rebuild would not exist yet at any of those points: the
925    /// overlay would be measured against an empty node and
926    /// `first_focusable_descendant` would find nothing to focus, so the popover
927    /// would open in the wrong place and swallow the keyboard. Materializing
928    /// here closes that window, and makes deferred content behave exactly like
929    /// the eagerly-built content it replaces.
930    ///
931    /// Cheap to call redundantly: a `DeferredSubtree` that is already
932    /// materialized returns its existing child, so a second open costs one
933    /// `build()` of the host and nothing below it.
934    ///
935    /// Not a general "rebuild this widget now" door — reach for
936    /// [`with_widget_mut`](Self::with_widget_mut) or a `Rebuild` binding for
937    /// ordinary reactive updates, which are correctly served by the next
938    /// layout pass.
939    pub fn materialize_now(&mut self, id: WidgetId) {
940        self.tree_mutations.push(TreeMutation::MaterializeNow(id));
941    }
942
943    /// Request that the AccessKit tree be re-walked after this handler
944    /// returns. Use after a mutation that changes the accessibility tree
945    /// **shape** in a way the framework doesn't already detect (relayout
946    /// alone no longer re-walks AT; only events that change the AT tree
947    /// — focus, overlays, locale/shortcut rebinds — set the dirty flag).
948    /// The companion `BuildContext::request_accessibility_update` covers
949    /// the build-time path.
950    pub fn request_accessibility_update(&mut self) {
951        self.request_a11y_update = true;
952    }
953
954    /// Speak `message` to the screen reader, politely.
955    ///
956    /// For anything the user needs told that is not the name of a widget: a
957    /// completed action, a new count, the result of an undo, a row that moved.
958    /// Sighted users read those off the screen; a screen-reader user is told
959    /// only what the framework says out loud.
960    ///
961    /// ```ignore
962    /// ctx.announce(tr!(event_added(title = title.clone())));
963    /// ```
964    ///
965    /// Takes `impl Into<String>`, so `tr!(…)` works directly.
966    /// `LocalizedString` is deliberately not the parameter type: an
967    /// announcement is an event, not a label, and
968    /// re-resolving it on a later language switch would re-speak it. See
969    /// [`crate::announcer`].
970    ///
971    /// **Do not pair this with a toast on the same path.** `Toast` is already a
972    /// correct live region, so doing both says everything twice.
973    pub fn announce(&mut self, message: impl Into<String>) {
974        self.announce_with(message, crate::announcer::Politeness::Polite);
975    }
976
977    /// Speak `message` to the screen reader at the given urgency.
978    ///
979    /// [`Politeness::Assertive`](crate::announcer::Politeness::Assertive)
980    /// interrupts whatever is being spoken. Reserve it for something the user
981    /// must not miss and cannot recover by re-reading the screen — a failure, a
982    /// refusal, a destructive result. Everything else is
983    /// [`Polite`](crate::announcer::Politeness::Polite), which is what
984    /// [`announce`](Self::announce) uses.
985    pub fn announce_with(
986        &mut self,
987        message: impl Into<String>,
988        politeness: crate::announcer::Politeness,
989    ) {
990        self.announcements.push((message.into(), politeness));
991    }
992
993    /// Show an overlay (tooltip, menu, popover).
994    pub fn show_overlay(&mut self, request: crate::overlay::OverlayRequest) {
995        self.overlay_requests.push(request);
996    }
997
998    /// Show an overlay whose reveal/dismiss is animated by a
999    /// caller-owned progress signal.
1000    ///
1001    /// `progress` must be an animated `Signal<f32>` (created with
1002    /// [`Signal::new_animated`](crate::signal::Signal::new_animated) or
1003    /// [`BuildContext::animated_signal`](crate::build_context::BuildContext::animated_signal)).
1004    /// The framework shows the overlay, tweens `progress` 0 → 1 over
1005    /// `duration`, and on any dismiss path tweens it 1 → 0 while
1006    /// **deferring** the overlay's removal (and its content's dormancy)
1007    /// until the roll-back completes — the same window the fade path
1008    /// uses, but with no opacity applied. The caller binds `progress`
1009    /// to whatever paints the reveal (e.g. an
1010    /// [`Unroll`](https://docs.rs/teksilo) width), and is responsible for
1011    /// resetting it to `0.0` before the show if a prior reveal left it
1012    /// at `1.0`.
1013    ///
1014    /// Under `prefers-reduced-motion`, skip this and use
1015    /// [`show_overlay`](Self::show_overlay) with the progress pinned at
1016    /// `1.0` so there is no tween and dismissal is immediate.
1017    pub fn show_overlay_with_reveal(
1018        &mut self,
1019        request: crate::overlay::OverlayRequest,
1020        progress: crate::signal::Signal<f32>,
1021        duration: std::time::Duration,
1022    ) {
1023        self.reveal_overlay_requests
1024            .push((request, progress, duration));
1025    }
1026
1027    /// Show an overlay that dismisses automatically after `duration`.
1028    pub fn show_overlay_for(
1029        &mut self,
1030        request: crate::overlay::OverlayRequest,
1031        duration: std::time::Duration,
1032    ) {
1033        self.timed_overlay_requests.push((request, duration));
1034    }
1035
1036    /// Dismiss an overlay by ID.
1037    pub fn dismiss_overlay(&mut self, id: crate::overlay::OverlayId) {
1038        self.overlay_dismissals.push(id);
1039    }
1040
1041    /// Dismiss the currently-shown overlay whose content root is
1042    /// `content_id`, if one is active. No-op when no overlay is showing
1043    /// that content. Use this to dismiss an overlay you can only name by
1044    /// its content widget — the symmetric companion to
1045    /// [`cancel_delayed_overlay`](Self::cancel_delayed_overlay), which
1046    /// cancels a *pending* delayed show for the same content. Together
1047    /// they let a caller fully retract a reusable tooltip surface
1048    /// (shown or pending) without tracking the `OverlayId`.
1049    pub fn dismiss_overlay_by_content(&mut self, content_id: crate::widget_id::WidgetId) {
1050        self.overlay_content_dismissals.push(content_id);
1051    }
1052
1053    /// Queue a request to pause an overlay's `auto_dismiss_after`
1054    /// timer. Drained by the framework after this handler returns —
1055    /// equivalent to calling
1056    /// [`OverlayManager::pause_auto_dismiss`](crate::overlay::OverlayManager::pause_auto_dismiss)
1057    /// at the next safe point. Idempotent.
1058    ///
1059    /// Used by `ToastHost` for hover-pause: on pointer-enter the
1060    /// host queues `pause_overlay_auto_dismiss(id)` for every live
1061    /// toast; on pointer-leave it queues `resume_overlay_auto_dismiss`.
1062    pub fn pause_overlay_auto_dismiss(&mut self, id: crate::overlay::OverlayId) {
1063        self.overlay_pause_requests.push((id, true));
1064    }
1065
1066    /// Queue a request to resume an overlay's `auto_dismiss_after`
1067    /// timer paused via
1068    /// [`pause_overlay_auto_dismiss`](Self::pause_overlay_auto_dismiss).
1069    /// Idempotent on un-paused overlays.
1070    pub fn resume_overlay_auto_dismiss(&mut self, id: crate::overlay::OverlayId) {
1071        self.overlay_pause_requests.push((id, false));
1072    }
1073
1074    /// Dismiss all active overlays (e.g., after a menu item is activated).
1075    pub fn dismiss_all_overlays(&mut self) {
1076        self.dismiss_scope = Some(DismissScope::All);
1077    }
1078
1079    /// Dismiss the source widget's containing overlay and any ancestor
1080    /// overlays in the chain that are menu-like (anything that isn't a
1081    /// `Role::Tooltip`, `Role::Dialog`, or `Role::AlertDialog`),
1082    /// preserving an outer composite tooltip or modal hosting the
1083    /// popover. Use for menu / dropdown item activation that wants to
1084    /// close the menu cascade without disturbing the host surface.
1085    pub fn dismiss_self_overlay_chain(&mut self) {
1086        self.dismiss_scope = Some(DismissScope::SelfChain);
1087    }
1088
1089    /// Dismiss every overlay whose content is *not* a host surface
1090    /// (`Role::Tooltip`, `Role::Dialog`, `Role::AlertDialog`),
1091    /// preserving an outer composite tooltip or modal hosting the
1092    /// trigger. Use for popover triggers and pre-show cleanup that
1093    /// want to close stale popovers / menus without taking a hosting
1094    /// surface with them.
1095    pub fn dismiss_all_except_hosts(&mut self) {
1096        self.dismiss_scope = Some(DismissScope::AllExceptHosts);
1097    }
1098
1099    /// Dismiss the topmost overlay only (e.g., closing a submenu while
1100    /// keeping the parent menu open).
1101    pub fn dismiss_top_overlay(&mut self) {
1102        self.dismiss_scope = Some(DismissScope::Top);
1103    }
1104
1105    /// Dismiss descendant overlays of the source widget's containing overlay.
1106    /// Useful for closing sibling submenu branches while keeping the current
1107    /// parent menu open.
1108    pub fn dismiss_child_overlays(&mut self) {
1109        self.dismiss_descendant_overlays.push(None);
1110    }
1111
1112    /// Dismiss descendant overlays of the source widget's containing overlay,
1113    /// preserving the subtree rooted at `content_id` if it is already open.
1114    pub fn dismiss_child_overlays_except(&mut self, content_id: crate::widget_id::WidgetId) {
1115        self.dismiss_descendant_overlays.push(Some(content_id));
1116    }
1117
1118    /// Request an idle callback to be run during the next idle period.
1119    /// Use this for incremental work that takes 5-50ms — too short for a
1120    /// background thread, too long for a single frame.
1121    pub fn request_idle_callback(
1122        &mut self,
1123        callback: impl FnOnce(crate::idle::IdleDeadline) + 'static,
1124    ) {
1125        self.idle_callbacks.push(Box::new(callback));
1126    }
1127
1128    /// Request framework-owned modal presentation.
1129    ///
1130    /// The widget tree records the request together with the originating
1131    /// widget, and the application layer can later resolve `Auto` into a
1132    /// concrete presentation backend.
1133    pub fn present_modal(&mut self, request: crate::modal::ModalRequest) {
1134        self.modal_requests.push(request);
1135    }
1136
1137    /// Synchronously open a modal as a native window — the single
1138    /// unified path for native-window modals. Callers that don't
1139    /// care whether the modal lands in-tree or in a native window
1140    /// use [`present_modal`](Self::present_modal), which routes
1141    /// `ModalPresentation::Auto` through the framework's picker.
1142    ///
1143    /// Returns the new window's id, or `None` when called outside a
1144    /// dispatch context (standalone trees). The window's parent is
1145    /// the current window; focus target and title / size from the
1146    /// request are honored.
1147    ///
1148    /// Only `ModalContent::Deferred` is supported here — an
1149    /// `ExistingWidget` id wouldn't make sense in a fresh tree.
1150    pub fn open_modal(
1151        &mut self,
1152        request: crate::modal::ModalRequest,
1153    ) -> Option<crate::window::TeksiloWindowId> {
1154        let parent = self.current_window.as_ref()?.id();
1155        let crate::modal::ModalContent::Deferred(builder) = request.content else {
1156            return None;
1157        };
1158        let mut config = crate::window::WindowConfig::new().modal(crate::window::ModalConfig {
1159            parent,
1160            focus_target: request.focus_target,
1161        });
1162        if let Some(title) = request.title {
1163            config = config.title(title);
1164        }
1165        if let Some((w, h)) = request.size {
1166            config = config.size(w, h);
1167        }
1168        let config = config.root(move |tree, _state| builder(tree));
1169        Some(self.open_window(config))
1170    }
1171
1172    /// Dismiss the current framework-owned modal presentation.
1173    pub fn dismiss_modal(&mut self) {
1174        self.dismiss_modal = true;
1175    }
1176
1177    /// Show an overlay after a delay. The widget tree checks pending delayed
1178    /// overlays during `layout()` and shows them once the delay elapses.
1179    /// Use this for submenu hover-open delays.
1180    ///
1181    /// The content widget should already be added to the tree (typically
1182    /// dormant). It will be activated automatically when the delay elapses.
1183    pub fn show_overlay_after(
1184        &mut self,
1185        request: crate::overlay::OverlayRequest,
1186        delay: std::time::Duration,
1187    ) {
1188        self.delayed_overlay_requests.push((request, delay, None));
1189    }
1190
1191    /// Show an overlay after a delay and move focus when it opens.
1192    pub fn show_overlay_after_with_focus(
1193        &mut self,
1194        request: crate::overlay::OverlayRequest,
1195        delay: std::time::Duration,
1196        focus_target: crate::widget_id::WidgetId,
1197    ) {
1198        self.delayed_overlay_requests
1199            .push((request, delay, Some(focus_target)));
1200    }
1201
1202    /// Request a repaint on a specific widget. Use this when an event handler
1203    /// on one widget changes state that affects a different widget's appearance
1204    /// (e.g., keyboard navigation highlighting items in an overlay).
1205    pub fn request_repaint(&mut self, id: crate::widget_id::WidgetId) {
1206        self.repaint_requests.push(id);
1207    }
1208
1209    /// Programmatically click a widget (synthetic PointerDown + PointerUp at
1210    /// its center). Use this for keyboard activation of a child widget, e.g.,
1211    /// Enter on a keyboard-focused menu item.
1212    pub fn synthetic_click(&mut self, id: crate::widget_id::WidgetId) {
1213        self.synthetic_clicks.push(id);
1214    }
1215
1216    /// Transfer focus to a specific widget. Use this when opening overlay
1217    /// content (menus, dialogs) that should receive keyboard events.
1218    pub fn request_focus(&mut self, id: crate::widget_id::WidgetId) {
1219        self.focus_requests.push(id);
1220    }
1221
1222    /// Move focus **into** the content of `id`: focus its first focusable
1223    /// descendant in tab order. Unlike [`request_focus`](Self::request_focus),
1224    /// this does **not** fall back to focusing `id` itself when the subtree has
1225    /// no focusable descendant — it is a no-op in that case, so an empty region
1226    /// never traps focus on a non-interactive container.
1227    ///
1228    /// Use this for "dive into this region" gestures, e.g. pressing Enter on a
1229    /// focused tab header to move focus into the tab's content panel. A panel
1230    /// with focusable content lands on its first control; a panel that opted
1231    /// into focusability itself (no inner controls) lands on the panel; a bare
1232    /// panel with neither leaves focus where it was.
1233    pub fn request_focus_into(&mut self, id: crate::widget_id::WidgetId) {
1234        self.focus_into_requests.push(id);
1235    }
1236
1237    /// Scroll the given rectangle into view inside every enclosing scroll
1238    /// container, walking outward from the widget whose handler is running.
1239    ///
1240    /// `rect` is in **absolute tree (window) coordinates** — the same space
1241    /// the arena stores widget bounds in. After the handler returns, the
1242    /// framework walks the current widget's ancestors and, for each
1243    /// `clips_children` scroll container whose viewport does not already
1244    /// fully contain `rect`, dispatches
1245    /// [`WidgetEvent::ScrollIntoView`](crate::event::WidgetEvent::ScrollIntoView)
1246    /// so the container adjusts its offset. Nested scroll areas each get a
1247    /// turn (outermost included), exactly like the focus-driven path.
1248    ///
1249    /// Unlike the automatic focus follow — which can only reveal a *focused
1250    /// widget's own bounds* — this lets a widget reveal an arbitrary interior
1251    /// rectangle it computed itself: a text caret, a virtualized list/table
1252    /// row (which is not a distinct focusable node), or a scrolled-off tab
1253    /// header. The widget remains responsible for scrolling its *own* interior
1254    /// viewport; `ensure_visible` handles the enclosing containers. It is a
1255    /// no-op when there is no scroll container above the widget, or when every
1256    /// container already shows the rect.
1257    ///
1258    /// See [`ensure_visible_with_margin`](Self::ensure_visible_with_margin) to
1259    /// keep breathing room around the target.
1260    pub fn ensure_visible(&mut self, rect: teksilo_canvas::Rect) {
1261        self.scroll_into_view_requests.push(ScrollRevealRequest {
1262            rect,
1263            margin: 0.0,
1264            align: crate::event::ScrollAlign::Minimal,
1265            motion: crate::event::ScrollMotion::Instant,
1266            from: None,
1267        });
1268    }
1269
1270    /// [`ensure_visible`](Self::ensure_visible), for a rect that belongs to
1271    /// **another** widget.
1272    ///
1273    /// The framework walks `owner`'s ancestors rather than the handling widget's.
1274    /// That distinction is the whole of it, and getting it wrong fails silently:
1275    /// a find banner's Next button sits *beside* the scrolling page, not inside
1276    /// it, so a reveal walked from the button climbs out through the banner and
1277    /// never meets the scroll container the match is in. The match is selected,
1278    /// the counter moves, and the viewport does not follow.
1279    ///
1280    /// The same reasoning [`ensure_widget_visible`](Self::ensure_widget_visible)
1281    /// already records for the id-based form; this is its rect-based twin, for a
1282    /// target that is an interior span rather than a mounted child.
1283    ///
1284    /// `rect` is in absolute tree (window) coordinates.
1285    pub fn ensure_visible_from(
1286        &mut self,
1287        owner: crate::widget_id::WidgetId,
1288        rect: teksilo_canvas::Rect,
1289    ) {
1290        self.scroll_into_view_requests.push(ScrollRevealRequest {
1291            rect,
1292            margin: 0.0,
1293            align: crate::event::ScrollAlign::Minimal,
1294            motion: crate::event::ScrollMotion::Instant,
1295            from: Some(owner),
1296        });
1297    }
1298
1299    /// Like [`ensure_visible`](Self::ensure_visible), but keeps `margin`
1300    /// logical pixels of breathing room around `rect` on every edge, so the
1301    /// target does not sit flush against the viewport boundary (the caret at
1302    /// the bottom line, the selected row at the fold). `rect` is in absolute
1303    /// tree (window) coordinates.
1304    pub fn ensure_visible_with_margin(&mut self, rect: teksilo_canvas::Rect, margin: f32) {
1305        self.scroll_into_view_requests.push(ScrollRevealRequest {
1306            rect,
1307            margin: margin.max(0.0),
1308            align: crate::event::ScrollAlign::Minimal,
1309            motion: crate::event::ScrollMotion::Instant,
1310            from: None,
1311        });
1312    }
1313
1314    /// **Pin** `rect` at `fraction` of the way down the innermost enclosing
1315    /// scroll container — `0.0` flush with the top, `0.5` centred, `1.0` flush
1316    /// with the bottom — instead of merely revealing it.
1317    ///
1318    /// The difference from [`ensure_visible`](Self::ensure_visible) is that this
1319    /// scrolls **even when the target is already visible**. That is what makes
1320    /// it usable for typewriter scrolling: a caret that only moved the view once
1321    /// it fell off the edge would not be pinned to anything.
1322    ///
1323    /// Only the **innermost** clipping ancestor aligns; any further ancestors
1324    /// out fall back to a minimal reveal, since an outer container's job is to
1325    /// bring the inner viewport on screen, not to align a rectangle it does not
1326    /// own.
1327    ///
1328    /// `fraction` is clamped to `0.0..=1.0`. The container additionally clamps
1329    /// to its own scroll range, so a target near the start or end of the content
1330    /// lands as close to `fraction` as the range permits — see the scroll
1331    /// container's `scroll_past_end` for buying range past the content's end so
1332    /// the last line can still reach the pin.
1333    ///
1334    /// `rect` is in absolute tree (window) coordinates.
1335    pub fn ensure_visible_aligned(
1336        &mut self,
1337        rect: teksilo_canvas::Rect,
1338        fraction: f32,
1339        motion: crate::event::ScrollMotion,
1340    ) {
1341        self.scroll_into_view_requests.push(ScrollRevealRequest {
1342            rect,
1343            margin: 0.0,
1344            align: crate::event::ScrollAlign::Fraction(fraction.clamp(0.0, 1.0)),
1345            motion,
1346            from: None,
1347        });
1348    }
1349
1350    /// [`ensure_visible_aligned`](Self::ensure_visible_aligned), for a rect that
1351    /// belongs to **another** widget — see [`ensure_visible_from`](Self::ensure_visible_from)
1352    /// for why the distinction exists and how it fails when it is missed.
1353    pub fn ensure_visible_aligned_from(
1354        &mut self,
1355        owner: crate::widget_id::WidgetId,
1356        rect: teksilo_canvas::Rect,
1357        fraction: f32,
1358        motion: crate::event::ScrollMotion,
1359    ) {
1360        self.scroll_into_view_requests.push(ScrollRevealRequest {
1361            rect,
1362            margin: 0.0,
1363            align: crate::event::ScrollAlign::Fraction(fraction.clamp(0.0, 1.0)),
1364            motion,
1365            from: Some(owner),
1366        });
1367    }
1368
1369    /// Scroll a specific mounted widget into view inside every enclosing
1370    /// scroll container — the id-based companion to
1371    /// [`ensure_visible`](Self::ensure_visible).
1372    ///
1373    /// The framework resolves `id` to its current absolute bounds after the
1374    /// handler returns and walks *that widget's* ancestors (never `id`
1375    /// itself), dispatching
1376    /// [`WidgetEvent::ScrollIntoView`](crate::event::WidgetEvent::ScrollIntoView)
1377    /// to each `clips_children` container that doesn't already show it.
1378    ///
1379    /// Use this when the target you want revealed is a real, non-virtualized
1380    /// child whose bounds the arena already knows — a selected radio tile, a
1381    /// tab header — so you don't have to compute a rect. For a target that has
1382    /// no distinct node (a text caret) or that may not be realized (a
1383    /// virtualized list/table row), use [`ensure_visible`](Self::ensure_visible)
1384    /// with an analytic rect instead. No-op if `id` is not currently mounted.
1385    pub fn ensure_widget_visible(&mut self, id: crate::widget_id::WidgetId) {
1386        self.scroll_widget_into_view_requests.push((id, 0.0));
1387    }
1388
1389    /// Like [`ensure_widget_visible`](Self::ensure_widget_visible), but keeps
1390    /// `margin` logical pixels of breathing room around the widget.
1391    pub fn ensure_widget_visible_with_margin(
1392        &mut self,
1393        id: crate::widget_id::WidgetId,
1394        margin: f32,
1395    ) {
1396        self.scroll_widget_into_view_requests
1397            .push((id, margin.max(0.0)));
1398    }
1399
1400    /// Surface the tooltip of a keyboard-highlighted item immediately (no
1401    /// dwell), dismissing the previously-highlighted item's tooltip. Used by
1402    /// `MenuList` on arrow-key navigation so a menu item's rich/composite
1403    /// tooltip is reachable by keyboard — real focus stays on the menu panel,
1404    /// so this is keyed on the item id rather than on focus. Pass the item's
1405    /// own widget id; a tooltip-less item simply dismisses the previous one.
1406    pub fn show_highlight_tooltip(&mut self, id: crate::widget_id::WidgetId) {
1407        self.highlight_tooltip_requests.push(id);
1408    }
1409
1410    /// Cancel a pending delayed overlay by its content widget ID.
1411    /// Call this when the hover ends before the delay elapses.
1412    pub fn cancel_delayed_overlay(&mut self, content_id: crate::widget_id::WidgetId) {
1413        self.cancel_delayed_overlays.push(content_id);
1414    }
1415
1416    /// Capture the pointer: all subsequent `PointerMove` and `PointerUp`
1417    /// events will be routed to the capturing widget until the capture is
1418    /// released. Use this when starting a drag operation.
1419    pub fn capture_pointer(&mut self) {
1420        self.pointer_capture = Some(true);
1421    }
1422
1423    /// Release a previously captured pointer. Pointer events resume normal
1424    /// hit-test dispatch.
1425    pub fn release_pointer(&mut self) {
1426        self.pointer_capture = Some(false);
1427    }
1428
1429    /// Start a drag-and-drop operation from the given source widget.
1430    ///
1431    /// The `payload` carries the data being dragged. During the drag:
1432    /// - `PointerMove` events update the drag position and fire `on_drag_hover`
1433    ///   on widgets under the pointer that have drop handlers
1434    /// - `PointerUp` fires `on_drop` on the target widget (if any)
1435    /// - `Escape` cancels the drag
1436    pub fn start_drag(
1437        &mut self,
1438        source_widget: crate::widget_id::WidgetId,
1439        payload: crate::drag_payload::DragPayload,
1440    ) {
1441        self.drag_start_request = Some((source_widget, payload, None));
1442    }
1443
1444    /// Start a drag-and-drop with a preview widget that follows the pointer.
1445    pub fn start_drag_with_preview(
1446        &mut self,
1447        source_widget: crate::widget_id::WidgetId,
1448        payload: crate::drag_payload::DragPayload,
1449        preview: Box<dyn crate::widget::Widget>,
1450    ) {
1451        self.drag_start_request = Some((source_widget, payload, Some(preview)));
1452    }
1453
1454    /// Cancel the active drag-and-drop session (if any).
1455    pub fn cancel_drag(&mut self) {
1456        self.cancel_drag = true;
1457    }
1458
1459    /// Replace the tree-level theme. Composite widgets are rebuilt so any
1460    /// derived values they captured at build time pick up the new tokens,
1461    /// and all widgets are marked dirty for repaint.
1462    ///
1463    /// An explicit theme also turns **off** OS-following: the app's theme
1464    /// mode is reset to manual, so a later OS light/dark change won't
1465    /// override the chosen theme.
1466    pub fn set_theme(&mut self, theme: crate::styles::Theme) {
1467        self.theme_request = Some(theme);
1468    }
1469
1470    /// Switch the application to follow the OS theme (native / system mode):
1471    /// the app adopts the OS's colours and tracks OS light/dark changes at
1472    /// runtime. On platforms without OS-colour support it falls back to
1473    /// following the built-in light/dark presets.
1474    ///
1475    /// This is the counterpart to [`set_theme`](Self::set_theme): calling
1476    /// `set_theme` pins a fixed theme (manual mode), while this resumes
1477    /// OS-following. Parameterless by design, so widgets need not reference
1478    /// the app-layer theme-mode enum.
1479    pub fn follow_system_theme(&mut self) {
1480        self.follow_system_request = true;
1481    }
1482
1483    /// Replace the tree-level locale identifier. Composite widgets are
1484    /// rebuilt so any tr! lookups picked up at build time are re-evaluated
1485    /// against the new locale.
1486    pub fn set_locale(&mut self, locale: impl Into<String>) {
1487        self.locale_request = Some(locale.into());
1488    }
1489
1490    /// Set the user-controlled global text-scale factor (`1.0` = 100 %).
1491    ///
1492    /// The change is applied app-wide (every window) after the handler returns,
1493    /// mirroring [`set_theme`](Self::set_theme) / [`set_locale`](Self::set_locale).
1494    /// All text grows uniformly without a rebuild. Persist the value through
1495    /// `ctx.settings()` (e.g. `teksilo_settings::TEXT_SCALE_KEY`) so it survives
1496    /// a restart — the `TextScaleControl` widget does both for you.
1497    pub fn set_text_scale(&mut self, factor: f32) {
1498        self.text_scale_request = Some(factor);
1499    }
1500}
1501
1502#[cfg(test)]
1503mod multi_window_tests {
1504    use super::*;
1505    use crate::window::state::WindowStateInit;
1506    use crate::window::{
1507        NoopWindowOps, TeksiloWindowId, WindowConfig, WindowOps, WindowPlacement, WindowState,
1508    };
1509    use std::cell::RefCell;
1510    use std::rc::Rc;
1511
1512    /// Recording implementation of `WindowOps` so tests can assert
1513    /// that `EventContext` routes each method through the trait.
1514    #[derive(Default)]
1515    struct RecordingOps {
1516        open_calls: RefCell<Vec<WindowConfig>>,
1517        focus_calls: RefCell<Vec<TeksiloWindowId>>,
1518        close_calls: RefCell<Vec<TeksiloWindowId>>,
1519        next_id: RefCell<u64>,
1520        // A fake registry so `find_window` / `window_state` / `windows`
1521        // can return values.
1522        states: RefCell<Vec<WindowState>>,
1523    }
1524
1525    impl RecordingOps {
1526        fn alloc_id(&self) -> TeksiloWindowId {
1527            let mut n = self.next_id.borrow_mut();
1528            *n += 1;
1529            TeksiloWindowId::new(*n)
1530        }
1531    }
1532
1533    impl WindowOps for RecordingOps {
1534        fn open_window(&mut self, config: WindowConfig) -> TeksiloWindowId {
1535            let id = self.alloc_id();
1536            let state = WindowState::new(WindowStateInit {
1537                id,
1538                string_id: config.string_id.clone(),
1539                placement: config.initial_placement,
1540                title: config.title.clone(),
1541                size: config.size,
1542                position: config.position.unwrap_or((0, 0)),
1543                focused: true,
1544                resizable: config.resizable,
1545                always_on_top: config.always_on_top,
1546            });
1547            self.states.borrow_mut().push(state);
1548            self.open_calls.borrow_mut().push(config);
1549            id
1550        }
1551
1552        fn find_window(&self, string_id: &str) -> Option<TeksiloWindowId> {
1553            self.states
1554                .borrow()
1555                .iter()
1556                .find(|s| s.string_id() == Some(string_id))
1557                .map(|s| s.id())
1558        }
1559
1560        fn window_state(&self, id: TeksiloWindowId) -> Option<WindowState> {
1561            self.states.borrow().iter().find(|s| s.id() == id).cloned()
1562        }
1563
1564        fn windows(&self) -> Vec<WindowState> {
1565            self.states.borrow().clone()
1566        }
1567
1568        fn focus_window(&mut self, id: TeksiloWindowId) {
1569            self.focus_calls.borrow_mut().push(id);
1570        }
1571
1572        fn close_window_by_id(&mut self, id: TeksiloWindowId) {
1573            self.close_calls.borrow_mut().push(id);
1574        }
1575    }
1576
1577    fn make_state(id: u64, string_id: Option<&str>) -> WindowState {
1578        WindowState::new(WindowStateInit {
1579            id: TeksiloWindowId::new(id),
1580            string_id: string_id.map(String::from),
1581            placement: WindowPlacement::Floating,
1582            title: "Test".into(),
1583            size: (800, 600),
1584            position: (0, 0),
1585            focused: true,
1586            resizable: true,
1587            always_on_top: false,
1588        })
1589    }
1590
1591    #[test]
1592    fn window_returns_current_window_state() {
1593        let state = make_state(1, Some("main"));
1594        let mut noop = NoopWindowOps;
1595        let ctx = EventContext::new().with_window_context(&mut noop, Some(state.clone()));
1596        assert_eq!(ctx.window().unwrap().id(), TeksiloWindowId::new(1));
1597        assert_eq!(ctx.window().unwrap().string_id(), Some("main"));
1598    }
1599
1600    #[test]
1601    fn window_is_none_without_context() {
1602        let ctx = EventContext::new();
1603        assert!(ctx.window().is_none());
1604    }
1605
1606    #[test]
1607    fn open_window_routes_through_ops() {
1608        let mut ops = RecordingOps::default();
1609        let main_state = make_state(1, Some("main"));
1610        let returned_id = {
1611            let mut ctx = EventContext::new().with_window_context(&mut ops, Some(main_state));
1612            ctx.open_window(WindowConfig::new().id("help").title("Help"))
1613        };
1614        assert_eq!(ops.open_calls.borrow().len(), 1);
1615        assert_eq!(
1616            ops.open_calls.borrow()[0].string_id.as_deref(),
1617            Some("help")
1618        );
1619        // Recording ops allocates ids 2+; 1 was reserved for `main`
1620        // only in this test — Recording's counter starts from 0, so the
1621        // first alloc yields 1.
1622        assert_eq!(returned_id, TeksiloWindowId::new(1));
1623    }
1624
1625    #[test]
1626    fn find_window_routes_through_ops() {
1627        let mut ops = RecordingOps::default();
1628        ops.states.borrow_mut().push(make_state(7, Some("foo")));
1629        let main_state = make_state(1, Some("main"));
1630        let ctx = EventContext::new().with_window_context(&mut ops, Some(main_state));
1631        assert_eq!(ctx.find_window("foo"), Some(TeksiloWindowId::new(7)));
1632        assert!(ctx.find_window("missing").is_none());
1633    }
1634
1635    #[test]
1636    fn focus_window_records_via_ops() {
1637        let mut ops = RecordingOps::default();
1638        let main_state = make_state(1, None);
1639        {
1640            let mut ctx = EventContext::new().with_window_context(&mut ops, Some(main_state));
1641            ctx.focus_window(TeksiloWindowId::new(42));
1642        }
1643        assert_eq!(
1644            ops.focus_calls.borrow().as_slice(),
1645            &[TeksiloWindowId::new(42)]
1646        );
1647    }
1648
1649    #[test]
1650    fn close_window_by_id_records_via_ops() {
1651        let mut ops = RecordingOps::default();
1652        let main_state = make_state(1, None);
1653        {
1654            let mut ctx = EventContext::new().with_window_context(&mut ops, Some(main_state));
1655            ctx.close_window_by_id(TeksiloWindowId::new(9));
1656        }
1657        assert_eq!(
1658            ops.close_calls.borrow().as_slice(),
1659            &[TeksiloWindowId::new(9)]
1660        );
1661    }
1662
1663    #[test]
1664    fn close_window_sets_guarded_flag_only() {
1665        let mut ctx = EventContext::new();
1666        ctx.close_window();
1667        assert!(
1668            ctx.close_window_requested,
1669            "close_window must raise the guarded-close flag"
1670        );
1671        assert!(
1672            !ctx.force_close_requested,
1673            "close_window must NOT raise the forced-close flag"
1674        );
1675    }
1676
1677    #[test]
1678    fn close_window_forced_sets_force_flag_only() {
1679        let mut ctx = EventContext::new();
1680        ctx.close_window_forced();
1681        assert!(
1682            ctx.force_close_requested,
1683            "close_window_forced must raise the forced-close flag"
1684        );
1685        assert!(
1686            !ctx.close_window_requested,
1687            "close_window_forced must NOT raise the guarded-close flag"
1688        );
1689    }
1690
1691    /// End-to-end: a handler calling `close_window_forced` during
1692    /// dispatch must transfer the flag onto the `WidgetTree` (the
1693    /// `collect_from_ctx` teardown), where the app loop drains it via
1694    /// `take_force_close_request` — separately from the guarded
1695    /// `take_close_window_request` flag.
1696    #[test]
1697    fn forced_close_flag_propagates_to_tree_and_drains_independently() {
1698        use crate::test_widgets::FillWidget;
1699        use crate::widget_tree::WidgetTree;
1700
1701        // `run_with_event_context` only runs the `collect_from_ctx`
1702        // teardown (which transfers ctx flags onto the tree) when the
1703        // tree has a root to anchor on, so give it one.
1704        let mut tree = WidgetTree::new();
1705        tree.add(FillWidget::new());
1706        tree.run_with_event_context(&mut NoopWindowOps, |ctx| ctx.close_window_forced());
1707        assert!(
1708            tree.take_force_close_request(),
1709            "forced-close flag must reach the tree"
1710        );
1711        assert!(
1712            !tree.take_close_window_request(),
1713            "a forced close must not also raise the guarded flag"
1714        );
1715
1716        // And the guarded path stays on its own channel.
1717        let mut tree = WidgetTree::new();
1718        tree.add(FillWidget::new());
1719        tree.run_with_event_context(&mut NoopWindowOps, |ctx| ctx.close_window());
1720        assert!(tree.take_close_window_request());
1721        assert!(!tree.take_force_close_request());
1722    }
1723
1724    #[test]
1725    fn windows_enumerates_via_ops() {
1726        let mut ops = RecordingOps::default();
1727        ops.states.borrow_mut().push(make_state(1, Some("a")));
1728        ops.states.borrow_mut().push(make_state(2, Some("b")));
1729        let main_state = make_state(1, Some("a"));
1730        let ctx = EventContext::new().with_window_context(&mut ops, Some(main_state));
1731        let ids: Vec<_> = ctx.windows().iter().map(|s| s.id()).collect();
1732        assert_eq!(ids, vec![TeksiloWindowId::new(1), TeksiloWindowId::new(2)]);
1733    }
1734
1735    #[test]
1736    fn standalone_context_returns_empty_windows_and_none_lookups() {
1737        let ctx = EventContext::new();
1738        assert!(ctx.find_window("anything").is_none());
1739        assert!(ctx.window_state(TeksiloWindowId::new(1)).is_none());
1740        assert!(ctx.windows().is_empty());
1741    }
1742
1743    #[test]
1744    #[should_panic(expected = "open_window called outside of a dispatch")]
1745    fn open_window_on_standalone_context_panics() {
1746        let mut ctx = EventContext::new();
1747        let _ = ctx.open_window(WindowConfig::new());
1748    }
1749
1750    #[test]
1751    fn open_modal_builds_window_config_from_request() {
1752        use crate::modal::{ModalContent, ModalRequest};
1753        let mut ops = RecordingOps::default();
1754        let main_state = make_state(1, Some("main"));
1755        let built_widget = Rc::new(RefCell::new(false));
1756        let built_widget_flag = built_widget.clone();
1757        let request = ModalRequest {
1758            content: ModalContent::Deferred(Box::new(move |_tree| {
1759                *built_widget_flag.borrow_mut() = true;
1760                // Return a dummy WidgetId — not used in this test since
1761                // the RecordingOps doesn't actually build the tree.
1762                crate::widget_id::WidgetId::default()
1763            })),
1764            presentation: crate::modal::ModalPresentation::NativeWindow,
1765            close_behavior: crate::modal::ModalCloseBehavior::default(),
1766            title: Some("Confirm".to_string()),
1767            size: Some((420, 180)),
1768            focus_target: None,
1769            on_dismiss: None,
1770        };
1771        {
1772            let mut ctx = EventContext::new().with_window_context(&mut ops, Some(main_state));
1773            let id = ctx.open_modal(request);
1774            assert!(id.is_some());
1775        }
1776        // open_modal is a thin wrapper over open_window — the config
1777        // it built must reach RecordingOps::open_window.
1778        let calls = ops.open_calls.borrow();
1779        assert_eq!(calls.len(), 1);
1780        let cfg = &calls[0];
1781        assert_eq!(cfg.title, "Confirm");
1782        assert_eq!(cfg.size, (420, 180));
1783        assert!(cfg.is_modal());
1784        assert_eq!(cfg.modal_parent(), Some(TeksiloWindowId::new(1)));
1785        // Cell is just to let us observe something reachable via cfg.root_builder;
1786        // the builder hasn't been called yet (RecordingOps records the config
1787        // but doesn't build the tree).
1788        let _ = built_widget;
1789    }
1790
1791    #[test]
1792    fn open_modal_requires_current_window() {
1793        use crate::modal::{ModalContent, ModalRequest};
1794        let mut ops = RecordingOps::default();
1795        let mut ctx = EventContext::new().with_window_context(&mut ops, None);
1796        let request = ModalRequest {
1797            content: ModalContent::Deferred(Box::new(|_tree| {
1798                crate::widget_id::WidgetId::default()
1799            })),
1800            presentation: crate::modal::ModalPresentation::NativeWindow,
1801            close_behavior: crate::modal::ModalCloseBehavior::default(),
1802            title: None,
1803            size: None,
1804            focus_target: None,
1805            on_dismiss: None,
1806        };
1807        assert!(ctx.open_modal(request).is_none());
1808    }
1809}