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