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