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