teksilo_core/widget_tree.rs
1// SPDX-License-Identifier: MPL-2.0
2// SPDX-FileCopyrightText: 2026 FernTech
3
4use std::cell::RefCell;
5use std::rc::Rc;
6
7use crate::styles::Theme;
8use teksilo_canvas::{Canvas, Point, Rect, RenderFrame, SizeProposal};
9
10use crate::arena::WidgetArena;
11use crate::event::{EventResponse, Key, Modifiers, PointerButton, WidgetEvent};
12use crate::widget::{EventContext, LayoutContext, PaintContext, Widget, WidgetPlacement};
13use crate::widget_id::WidgetId;
14
15mod accessibility_cell_name_impl;
16mod accessibility_description_impl;
17#[cfg(test)]
18mod accessibility_description_tests;
19mod accessibility_emit_impl;
20mod accessibility_impl;
21mod accessibility_placeholder_impl;
22#[cfg(test)]
23mod accessibility_proxy_tests;
24#[cfg(test)]
25mod adapter_ids_tests;
26#[cfg(test)]
27mod announcement_ring_tests;
28#[cfg(test)]
29mod announcer_tests;
30#[cfg(test)]
31mod can_handle_tests;
32#[cfg(test)]
33mod context_menu_contribution_tests;
34#[cfg(test)]
35mod device_scale_tests;
36#[cfg(test)]
37mod dismissed_content_tests;
38mod drag_drop_impl;
39mod focus_fallback_impl;
40#[cfg(test)]
41mod focus_fallback_tests;
42mod focus_impl;
43#[cfg(test)]
44mod focus_on_click_tests;
45mod focus_region_impl;
46#[cfg(test)]
47mod focus_region_tests;
48#[cfg(test)]
49mod focus_request_tests;
50pub(crate) use focus_impl::FocusRequestMode;
51mod gesture_dispatch_impl;
52#[cfg(test)]
53mod hit_targeting_tests;
54#[cfg(test)]
55mod intent_routing_tests;
56#[cfg(test)]
57mod key_release_tests;
58mod layout_impl;
59mod lazy_theme;
60#[cfg(test)]
61mod live_image_tests;
62#[cfg(test)]
63mod local_frame_tests;
64#[cfg(test)]
65mod modal_tests;
66mod overlay_impl;
67#[cfg(test)]
68mod overlay_intent_tests;
69pub mod pan_arbiter;
70mod pointer_cancel;
71mod pointer_router;
72mod pointer_state;
73mod query_impl;
74#[cfg(test)]
75mod redraw_waker_tests;
76mod rendering_impl;
77#[cfg(test)]
78mod repaint_trigger_tests;
79mod test_api;
80#[cfg(test)]
81mod tooltip_dwell_tests;
82pub mod touch_route;
83#[cfg(test)]
84mod window_chrome_tests;
85#[cfg(test)]
86mod window_name_tests;
87#[cfg(test)]
88mod windowless_contract_tests;
89
90struct AnimatedRegistration {
91 weak: crate::signal::WeakAnimatedSignal,
92 owner: WidgetId,
93}
94
95impl AnimatedRegistration {
96 fn same_signal(&self, signal: &crate::signal::Signal<f32>) -> bool {
97 self.weak.same_signal(signal)
98 }
99
100 fn is_alive(&self) -> bool {
101 self.weak.upgrade().is_some()
102 }
103
104 fn take_pending_animation(
105 &self,
106 ) -> Option<(
107 crate::signal::Signal<f32>,
108 crate::animation::AnimationRequest,
109 WidgetId,
110 )> {
111 let signal = self.weak.upgrade()?;
112 let request = signal.take_pending_animation()?;
113 Some((signal, request, self.owner))
114 }
115
116 /// Non-consuming counterpart to [`take_pending_animation`](Self::take_pending_animation),
117 /// for [`WidgetTree::needs_reconcile`] — which must be able to ask
118 /// "is there work here?" without doing any.
119 fn has_pending_animation(&self) -> bool {
120 self.weak
121 .upgrade()
122 .is_some_and(|signal| signal.has_pending_animation())
123 }
124}
125
126/// How many crossings between trees a chain of intents may make: an intent
127/// that many crossings led to is not kept for another tree. Two actions in
128/// two trees that answer each other's intents would otherwise go on, a few
129/// rounds each turn, for as long as the application runs.
130pub(crate) const MAX_INTENT_CROSSINGS: usize = 64;
131
132/// An intent waiting for [`WidgetTree::drain_pending_intents`].
133struct PendingIntent {
134 /// The widget its walk starts at.
135 source: WidgetId,
136 intent: crate::intent::Intent,
137 /// The firing shortcut's `propagate_when_disabled` policy.
138 propagate_when_disabled: bool,
139 /// The overlays the walk from `source` crossed when the intent was sent,
140 /// the open modals on its way included: a modal that has closed by the
141 /// time the intent is dispatched is crossed as it would have been.
142 crossings: Vec<OverlayCrossing>,
143}
144
145/// A step an intent's walk takes from an overlay's content root, which has
146/// no parent, to the widget the overlay is attached to (for a modal, where
147/// what it leaves goes on to). See [`WidgetTree::intent_walk`].
148#[derive(Debug, Clone, Copy, PartialEq, Eq)]
149pub(crate) struct OverlayCrossing {
150 pub(crate) content: WidgetId,
151 pub(crate) anchor: WidgetId,
152}
153
154/// The way an intent goes: [legs](IntentLeg) in order, and every overlay
155/// crossing they make. See [`WidgetTree::intent_route`].
156pub(crate) struct IntentRoute {
157 pub(crate) legs: Vec<IntentLeg>,
158 pub(crate) crossings: Vec<OverlayCrossing>,
159}
160
161/// One [walk](WidgetTree::intent_walk) of an [`IntentRoute`]: the widgets it
162/// passes, and the content of the open modal it stopped at, if any.
163pub(crate) struct IntentLeg {
164 pub(crate) chain: Vec<WidgetId>,
165 pub(crate) modal: Option<WidgetId>,
166}
167
168impl IntentRoute {
169 /// The content of every open modal the route stopped at, in order.
170 fn modals(&self) -> impl Iterator<Item = WidgetId> + '_ {
171 self.legs.iter().filter_map(|leg| leg.modal)
172 }
173
174 /// Whether the route ends at an open modal it does not go past: a key's,
175 /// or one whose way on to the page is lost.
176 fn ends_at_a_modal(&self) -> bool {
177 self.legs.last().is_some_and(|leg| leg.modal.is_some())
178 }
179}
180
181// (line 33, above `struct AnimatedRegistration`) — remove entirely
182// (line 71, above `#[allow(clippy::type_complexity)]` / `pub struct WidgetTree`)
183/// The main widget tree orchestrating arena, layout, events, accessibility, and paint.
184/// Provides both the runtime API and the headless test API.
185#[allow(clippy::type_complexity)]
186pub struct WidgetTree {
187 pub(crate) arena: WidgetArena,
188 /// Current theme value cached for `&Theme` accessors used by layout/paint
189 /// contexts and by widgets that need an immediate read. The reactive source
190 /// of truth is `theme_signal`; both are updated in lockstep by `set_theme`.
191 theme: Theme,
192 /// Reactive theme signal. Widgets that want their visual or derived state
193 /// to track theme changes bind to this signal or build derived signals via
194 /// `zip`/`map`. `set_theme` updates the signal (firing observers) without
195 /// rebuilding the widget tree, so interaction state (focus, scroll, expanded
196 /// panels, …) survives theme switches.
197 theme_signal: crate::signal::Signal<Theme>,
198 /// How the active [`TargetDensity`](teksilo_tokens::TargetDensity) is chosen. `Fixed(Compact)` by default,
199 /// so nothing switches density unless the app asks.
200 ///
201 /// `FollowLastPointer` is **stored and read by nobody**. The pointer
202 /// ingress it was written for exists — the app event loop routes contacts
203 /// into `dispatch_pointer_with_ops` — but honouring the policy means
204 /// deciding what a stray tap costs (a density switch discards every widget
205 /// id in the tree), whether a pen counts as coarse, and how the hysteresis
206 /// commits when the user simply stops touching. None of that is settled, so
207 /// the policy is a declaration the framework does not yet act on.
208 density_policy: teksilo_tokens::DensityPolicy,
209 /// User-controlled global text-scale factor (`1.0` = 100 %). Layered on top
210 /// of the OS `text_scale_factor`: the two multiply. Set via
211 /// `set_user_text_scale`; persisted by the application through
212 /// `teksilo_settings::TEXT_SCALE_KEY`.
213 user_text_scale: f32,
214 /// Cached projection of `theme` whose `typography` is scaled by
215 /// `user_text_scale * text_scale_factor`. Recomputed by
216 /// `recompute_effective_theme` whenever the theme or either scale factor
217 /// changes; the layout and paint walkers read this instead of `theme` so
218 /// all text grows uniformly. Equal to `theme` when the combined factor is 1.
219 effective_theme: Theme,
220 /// The combined `user_text_scale * text_scale_factor`, cached so the
221 /// layout/paint context construction sites don't recompute it. The single
222 /// scalar published to widgets that size from a source *other* than
223 /// `Theme.typography` (icons, the rich-text engine, calendar constants,
224 /// scene text). Written alongside `effective_theme` in
225 /// `recompute_effective_theme`.
226 effective_text_scale: f32,
227 /// Reactive mirror of `effective_text_scale`, for build-time binders that
228 /// must react to a scale change without a rebuild path of their own (e.g.
229 /// `Calendar` binds this at `Rebuild` level). Fired by
230 /// `recompute_effective_theme`.
231 text_scale_signal: crate::signal::Signal<f32>,
232 /// Reactive window-active state (`focused AND not occluded`), the
233 /// occlusion-aware companion to `WindowState::focused` (which is raw OS
234 /// focus only). The single source of truth for "is this window active",
235 /// read by `is_window_active()` and published to widgets via
236 /// `window_active_signal()` / `BuildContext::window_active*` /
237 /// `PaintContext::window_active`. Drives caret hiding, selection
238 /// desaturation and `DimWhenInactive`. Starts `true` — winit may not send
239 /// `Focused(true)` for the first window, so a window must not be born
240 /// inactive. Mutated only by `set_window_active`.
241 window_active_signal: crate::signal::Signal<bool>,
242 text_backend: Option<Rc<RefCell<dyn teksilo_canvas::TextBackend>>>,
243 /// The widget the window's own root builder made, when a wrapper (the
244 /// debug inspector's shell, the toast host) is the tree's first root
245 /// instead. Set through [`Self::set_content_root`]; read through
246 /// [`Self::intent_anchor`].
247 content_root: Option<WidgetId>,
248 focused: Option<WidgetId>,
249 /// Reactive mirror of `focused`. Same pattern as `hovered_signal`
250 /// — kept in sync via `set_focused`. Drives the inspector's Focus
251 /// tab without polling.
252 focused_signal: crate::signal::Signal<Option<WidgetId>>,
253 /// Every pointer the tree currently knows about, plus the primary and
254 /// hover-owner elections.
255 ///
256 /// Replaces the singular `hovered` / `last_pointer_position` /
257 /// `pointer_captured_by` this tree used to carry. Hover lives on the
258 /// **hover owner**'s entry (a contact never hovers), position and the
259 /// legacy singular accessors read the **primary**, and capture is per
260 /// pointer — two contacts hold independent captures, each released only by
261 /// its own Up or Cancel. See [`crate::pointer::table`].
262 pointers: crate::pointer::table::PointerTable,
263 /// Reactive mirror of the hover owner's hovered widget. Set whenever it
264 /// changes during dispatch / hit-test recovery so external observers
265 /// (notably the debug inspector's hover tooltip) can react without
266 /// polling. Held by handle so the field is a cheap clone.
267 hovered_signal: crate::signal::Signal<Option<WidgetId>>,
268 /// Reactive mirror of the kind of the pointer that most recently produced
269 /// a sample. Lets a widget switch an affordance between the mouse and the
270 /// touch form without a rebuild, and without every widget having to
271 /// remember an `on_pointer_event` of its own just to learn the modality.
272 last_pointer_kind_signal: crate::signal::Signal<teksilo_tokens::PointerKind>,
273 /// The pointer position *before* the move currently being
274 /// dispatched — i.e. the last sample that was still over the
275 /// previously-hovered widget. Read when arming an overlay's safe
276 /// triangle: the apex belongs at the point the pointer left the
277 /// anchor, not at the first sample past it (they coincide for a
278 /// real mouse, but the distinction is what keeps the cone from
279 /// degenerating to "the apex is wherever I am, so I am always
280 /// inside it").
281 previous_pointer_position: Option<teksilo_canvas::Point>,
282 /// The hover owner left the window ([`WidgetTree::pointer_left_window`])
283 /// and has not been seen inside it since. Its cached position is then the
284 /// last one inside, not where it is, so the layout pass must not re-derive
285 /// hover (or a tooltip dwell) from it. Cleared by the next sample of a
286 /// pointer that can hover.
287 hover_owner_outside_window: bool,
288 /// A press cancelled the tooltip dwell and the pointer has not yet left
289 /// and re-entered a widget: the hover recovery at the end of a layout pass
290 /// (a click that rebuilt the anchor under a stationary pointer) must not
291 /// start the dwell again. Desktop convention: a click answers the question
292 /// the tooltip would have, until the pointer goes away and comes back.
293 tooltip_dwell_held: bool,
294 /// A rebuild destroyed the focused widget: the ancestors it had inside the
295 /// subtree that owned focus, innermost first, remembered so the end of the
296 /// layout pass can land focus back inside the innermost one still alive.
297 ///
298 /// A rebuild allocates fresh `WidgetId`s for its children, so the focused
299 /// node dies and `revalidate_interaction_state` drops focus to `None`.
300 /// Leaving it there kicks the user out of the widget they were in — most
301 /// visibly, a popover that refreshes its content when it opens would throw
302 /// away the very row the popover had just focused, so the menu comes up with
303 /// no keyboard focus at all. Focus is re-entered *after* the layout walk
304 /// (see the tail of `layout_with_ops`), once the fresh children have real
305 /// bounds for the focus-driven scroll-into-view — the same shape as the
306 /// post-layout hover refresh next to it.
307 ///
308 /// The innermost survivor, not the rebuilt root: a reconciling rebuild
309 /// keeps the children it re-attaches, so the group that held focus is often
310 /// still there, and the root's first focusable descendant is the *first*
311 /// group, whichever one the user was in.
312 ///
313 /// Each ancestor carries the focused node's position among its focusable
314 /// descendants, in tree order. The restore lands on whatever holds that
315 /// position after the rebuild, so focus in the second of two fields comes
316 /// back to the second field, not the first.
317 pending_focus_restore: Vec<(WidgetId, usize)>,
318 /// A focus request whose target was **dormant** when it was made: a page
319 /// of a `Switcher`, a `visible_when` branch, that the same handler is
320 /// about to show. Focusing a dormant node outright does not survive the
321 /// next layout — `revalidate_interaction_state` runs before the pass wakes
322 /// the page, finds the target inactive, and drops focus — so the request
323 /// waits here instead, and the tail of `layout_with_ops` honours it once
324 /// activation has settled (see `settle_pending_focus_request`).
325 ///
326 /// One slot, last request wins. Any focus move that actually happens in
327 /// the meantime (`focus_with_origin_ops`, which every move goes through)
328 /// and [`WidgetTree::clear_focus`] cancel it; a target still dormant, or
329 /// gone, when the pass ends drops it.
330 pending_focus_request: Option<focus_impl::PendingFocusRequest>,
331 /// The interaction anchors as of the last layout walk — the focused node,
332 /// each live pointer's captor, and an in-flight drag's source.
333 ///
334 /// A `culls_children` parent is told to keep what the user is in the
335 /// middle of, and it is only asked during layout. So the anchor set is an
336 /// *input* to that decision, and when it changes the decision is stale —
337 /// even though nothing moved and nothing resized, which is what the
338 /// idle-pass early-return keys off. Kept here so the pass can notice the
339 /// change and re-ask the culling parents it affects; see
340 /// `invalidate_culls_for_moved_interaction`.
341 last_interaction_anchors: Vec<WidgetId>,
342 last_proposal: SizeProposal,
343 /// How many times [`layout_with_ops`](Self::layout_with_ops) has run on
344 /// this tree; read through [`layout_passes`](Self::layout_passes).
345 layout_passes: u64,
346 /// The arena's rebuild-mark count when the last layout pass ended: a
347 /// count past it is a rebuild no pass has seen. See
348 /// [`needs_structural_layout`](Self::needs_structural_layout).
349 rebuild_marks_laid_out: u64,
350 /// The last pass left a rebuild undone because a pointer capture held
351 /// it back ([`captures_defer_rebuilds`](Self::captures_defer_rebuilds)).
352 /// Its mark is already counted in `rebuild_marks_laid_out`, so this is
353 /// what tells [`needs_structural_layout`](Self::needs_structural_layout)
354 /// that the release must be followed by a pass.
355 rebuild_deferred: bool,
356 /// The focused widget the last pass found disabled with no enabled Tab
357 /// stop to hand focus to, so focus stayed on it. While focus is still
358 /// there, [`needs_structural_layout`](Self::needs_structural_layout) does
359 /// not ask for the pass again on every event. An `enabled_when` binding
360 /// firing in the binding flush clears it, since a stop may have been
361 /// enabled, and every pass tries anew.
362 disabled_focus_stays: Option<WidgetId>,
363 /// A binding flush found a `visible_when` gate that no longer matches its
364 /// node's activation; the next `process_state_changes` settles it. See
365 /// [`needs_structural_layout`](Self::needs_structural_layout).
366 activation_pending: bool,
367 pending_modal_requests: Vec<crate::modal::QueuedModalRequest>,
368 pending_modal_dismissal: bool,
369 shortcut_registry: crate::shortcut::ShortcutRegistry,
370 /// Queue of intents awaiting dispatch. Populated either by the
371 /// keystroke interception path (`dispatch_event` for KeyDown) or
372 /// by handlers calling `ctx.send_intent(...)`. Drained between
373 /// event-handler calls by [`WidgetTree::drain_pending_intents`].
374 pending_intents: Vec<PendingIntent>,
375 /// Intents this tree's drain dispatched and no action took, kept for
376 /// the application layer to offer to another tree; `None` (the
377 /// default) keeps none. See
378 /// [`set_records_unclaimed_intents`](Self::set_records_unclaimed_intents).
379 unclaimed_intents: Option<Vec<crate::intent::Intent>>,
380 /// What the application tree takes, read by a shortcut nothing in this
381 /// tree takes. See
382 /// [`set_application_scope`](Self::set_application_scope).
383 application_scope: Option<crate::action::ApplicationScope>,
384 /// What [`command_available_signal`](Self::command_available_signal)
385 /// handed out: the widget it is for, the intent name, and the signal
386 /// kept equal to `can_handle(name)` while the widget is active.
387 command_watchers: Vec<(WidgetId, &'static str, crate::signal::Signal<bool>)>,
388 /// While a routed intent's actions run, the crossings that led to the
389 /// intents they send. See
390 /// [`dispatch_routed_intent`](Self::dispatch_routed_intent).
391 routed_crossings: Option<usize>,
392 /// Window-global actions registered via
393 /// [`BuildContext::register_action_global`](crate::BuildContext::register_action_global).
394 /// Consulted as a fallback at the end of every intent dispatch — *after* the
395 /// source→root walk finds no consuming node action — so an app-global command
396 /// is reachable no matter where the intent originated (a menu-bar dropdown
397 /// overlay, deep content, a global shortcut anchored at the root). Each entry
398 /// is owned by the registering widget and torn down on its rebuild/destroy,
399 /// mirroring `register_shortcut_global`.
400 global_actions: Vec<(WidgetId, crate::action::Action)>,
401 /// The widgets that edit text, registered via
402 /// [`BuildContext::register_text_surface`](crate::BuildContext::register_text_surface).
403 ///
404 /// Owned by the registering widget and torn down on its rebuild/destroy,
405 /// exactly like `global_actions` above. Read through
406 /// [`WidgetTree::focused_text_surface`] by a host that has taken a text
407 /// chord — `Ctrl+Z`, `Ctrl+C` — for itself and owes every text widget in the
408 /// tree an answer about what happens to it. See
409 /// [`crate::text_surface`] for why the framework is the only place that
410 /// question can be answered completely.
411 text_surfaces: crate::text_surface::TextSurfaces,
412 /// Currently-armed key-capture slot. `Some` when
413 /// [`WidgetTree::begin_key_capture`] has been called and the
414 /// returned [`CaptureHandle`](crate::shortcut::CaptureHandle)
415 /// is still alive. The slot is shared (via `Rc`) with the handle
416 /// so dropping the handle cancels the capture, and calling
417 /// `begin_key_capture` again creates a fresh slot without
418 /// touching the previous one (whose handle, if dropped later,
419 /// only clears its own orphaned slot).
420 key_capture: Option<crate::shortcut::KeyCaptureSlot>,
421 binding_registry: crate::binding::BindingRegistry,
422 idle_queue: crate::idle::IdleQueue,
423 /// Simulated clock for deterministic time-dependent testing.
424 ///
425 /// Its initial value is the tree's **epoch**, and [`Self::input_clock`] is
426 /// seeded from the very same `Instant` — so `EventTime::ZERO` and this
427 /// field's starting value name one moment, and the input timeline and the
428 /// animation timeline are one axis. See
429 /// [`crate::pointer::clock`] for why that matters.
430 sim_clock: std::time::Instant,
431 /// The one source of [`EventTime`](crate::pointer::EventTime)s for this
432 /// tree. A [`MonotonicClock`](crate::pointer::clock::MonotonicClock)
433 /// anchored at the tree epoch by default; a test swaps in a
434 /// [`ManualClock`](crate::pointer::clock::ManualClock) via
435 /// [`set_input_clock`](Self::set_input_clock).
436 input_clock: std::rc::Rc<dyn crate::pointer::clock::InputClock>,
437 /// What is known about the sample currently being dispatched, snapshotted
438 /// onto every [`EventContext`] built while it
439 /// runs. Holds its default — a mouse at the epoch — outside a pointer or
440 /// scroll dispatch.
441 current_input: crate::pointer::InputSnapshot,
442 /// Whether simulated time is *currently* what this tree measures against —
443 /// i.e. whether [`Self::sim_clock`], rather than the wall clock, is what
444 /// [`Self::animation_clock`] answers with and what freezes the input
445 /// timeline.
446 ///
447 /// Set by `enter_simulated_mode`, which
448 /// [`advance_time`](Self::advance_time) calls before it moves anything, and
449 /// cleared by [`resume_real_time`](Self::resume_real_time). Both axes turn
450 /// on this one flag, so the tree has one notion of "is time simulated right
451 /// now" rather than two that can disagree.
452 ///
453 /// It is not a latch. A headless test never hands the clock back, so for a
454 /// test it behaves like one: an animation may then only progress by
455 /// advancing the clock, never by the test taking a long time. A host
456 /// sharing a live tree with a real event loop — the debug automation bridge
457 /// — hands it back after every operation, and real time drives the tree
458 /// again until the next advance.
459 ///
460 /// What each axis does across the two transitions differs, because the two
461 /// carry different state. The animation scheduler holds absolute instants,
462 /// so switching axes **rebases** them (`AnimationScheduler::rebase`) and the
463 /// reading itself is simply whichever clock is in charge. The input axis
464 /// holds none, so it is the *reading* that is carried: see
465 /// [`Self::sim_input_origin`] and [`Self::sim_input_offset`].
466 sim_time_frozen: bool,
467 /// Where the input timeline stood when this tree entered simulated mode,
468 /// as `(the reading then, the `sim_clock` then)`.
469 ///
470 /// The input axis cannot simply become `sim_clock - epoch`: samples
471 /// dispatched *before* the switch were stamped from the wall clock, which
472 /// by then is ahead of `sim_clock`, so every one of them would sit in the
473 /// virtual future and no interval measured from them would ever elapse.
474 /// Continuing the axis from where it stood instead makes every stamp taken
475 /// before the switch lie in the past and every interval after it exactly
476 /// the duration advanced.
477 ///
478 /// `None` while the tree runs on real time, and also under a clock that has
479 /// no wall-clock anchor — a
480 /// [`ManualClock`](crate::pointer::clock::ManualClock) *is* the virtual
481 /// axis already, and is moved directly by `advance_time`.
482 ///
483 /// Cleared by [`resume_real_time`](Self::resume_real_time), which hands the
484 /// axis back to the wall clock with what was advanced carried forward in
485 /// [`Self::sim_input_offset`].
486 sim_input_origin: Option<(crate::pointer::EventTime, std::time::Instant)>,
487 /// How far ahead of the raw input clock this tree's input timeline runs,
488 /// having been advanced and then handed back to real time.
489 ///
490 /// Added to every reading of the clock, and **re-measured** (not
491 /// accumulated) at each hand-back as `frozen reading − raw reading`, floored
492 /// at zero. That is what makes the axis monotone across the hand-back: the
493 /// reading at the instant of
494 /// [`resume_real_time`](Self::resume_real_time) is the later of the frozen
495 /// reading it had and the raw one, and it moves with the wall clock from
496 /// there. Without it
497 /// the axis would jump *backwards* by everything that was advanced, and a
498 /// monotone [`EventTime`](crate::pointer::EventTime) is a platform
499 /// conformance invariant.
500 ///
501 /// So it is not monotone in itself: a tree that spent longer on the wall
502 /// clock than it was ever advanced is already ahead of its frozen reading
503 /// and the right offset is then zero, which is what the floor is for. It is
504 /// also dropped outright by
505 /// [`set_input_clock`](Self::set_input_clock) — it is a distance measured
506 /// against one clock's readings and means nothing against another's.
507 ///
508 /// It is also what keeps a deadline schedulable: `instant_for` subtracts it
509 /// again, so a long press armed after an advance is reported to the event
510 /// loop at a *future* `Instant` rather than one in the past that can never
511 /// ripen.
512 sim_input_offset: std::time::Duration,
513 /// Overlay manager for tooltips, menus, popovers.
514 pub(crate) overlay_manager: crate::overlay::OverlayManager,
515 /// Re-entrancy guard for the dismissal-callback drain. A callback may
516 /// dismiss another overlay, whose teardown drains again; the inner drain
517 /// returns at once and the outer loop picks up whatever it parked, so the
518 /// recursion is one level deep by construction rather than by luck.
519 pub(crate) draining_dismiss: std::cell::Cell<bool>,
520 /// Tooltip attachments, one per anchor. See [`TooltipEntry`].
521 tooltips: Vec<TooltipEntry>,
522 /// Simulated-clock end of the tooltip "reshow session". While any tip is
523 /// visible, or until this instant after the last tip dismissed, subsequent
524 /// anchors use `MotionTokens::tooltip_reshow_delay` instead of the full
525 /// initial delay (Windows `TTDT_RESHOW` behaviour).
526 tooltip_session_until_sim: Option<std::time::Instant>,
527 /// Real-clock counterpart of [`Self::tooltip_session_until_sim`].
528 tooltip_session_until_real: Option<std::time::Instant>,
529 /// The tooltip currently surfaced by keyboard menu navigation
530 /// (`show_highlight_tooltip`): `(overlay_id, content_id)`. At most one
531 /// is shown at a time; moving the highlight or closing the menu clears
532 /// it. Distinct from the hover/focus tooltip paths — this one is a
533 /// `Manual`-dismiss child of the menu overlay so a single Escape closes
534 /// the menu (and cascades the tooltip) rather than only the tooltip.
535 highlight_tooltip: Option<(crate::overlay::OverlayId, WidgetId)>,
536 /// How the currently focused widget gained focus.
537 focus_origin: Option<crate::focus::FocusOrigin>,
538 /// Every live pointer press, keyed by the node whose gesture arena took it.
539 /// The framework's press visual — see [`crate::press`] for the four things
540 /// a widget's own `PointerDown`/`PointerUp` bookkeeping cannot see.
541 presses: crate::press::PressTable,
542 /// Input-modality "focus-visible" state: `true` after keyboard input,
543 /// `false` after pointer input. Focus rings (e.g. `StandardItem`'s current
544 /// row) show only while this is `true`, the standard `:focus-visible`
545 /// behaviour — so a mouse click selects without a ring, and keyboard
546 /// navigation reveals it.
547 focus_visible: crate::signal::Signal<bool>,
548 /// Active focus-scope stack during build. A data view pushes its scope
549 /// (`begin_view_focus`) around its row loop so each row reads *its view's*
550 /// focus deterministically — independent of arena parenting, which may not
551 /// be wired yet while rows build (docked / virtualized content). Drives
552 /// focus-aware selection + focus rings in `StandardItem`.
553 view_focus_stack: Vec<crate::signal::Signal<bool>>,
554 /// Layout direction for RTL/LTR support.
555 pub(crate) layout_direction: crate::environment::LayoutDirection,
556 /// Animation scheduler for smooth animated state and signal transitions.
557 animation_scheduler: crate::animation::AnimationScheduler,
558 /// Weakly tracked animated values from both state and signal APIs.
559 animated_values: Vec<AnimatedRegistration>,
560 /// Registry of shader-driven animated quads (opt-in alternative to
561 /// `Signal<f32>::animate_looping` for decorative motion — progress
562 /// sweeps, sprite-atlas frame cycling, future pulse/shimmer). The
563 /// scheduler-style signal path stays for everything else. Per-slot
564 /// `AnimParams` are ticked and attached to every `RenderFrame`
565 /// produced by `render()` — the renderer reads them from there.
566 animated_quads: crate::animated_quad::AnimatedQuadRegistry,
567 /// Per-frame-effect scheduler. Owns the registry of widgets that
568 /// asked for a frame-tick subscription (Pulse, Cycle, …). Sits
569 /// alongside `animation_scheduler` and `animated_quads` as the
570 /// third visibility-aware motion source — they all consult the
571 /// same [`motion_visibility`](crate::motion_visibility) helpers.
572 /// After every `render()` the tree calls
573 /// `FrameTickScheduler::should_arm_frame_tick` and re-arms
574 /// `frame_tick_armed_by_subscribers` if any subscriber's owner was
575 /// painted this frame.
576 pub(crate) frame_tick_scheduler: crate::frame_tick_scheduler::FrameTickScheduler,
577 /// Live pans, live coasts, the window's pinch, and the palm watches — the
578 /// whole touch-motion layer, in one field. See
579 /// [`pan_arbiter`].
580 touch_motion: pan_arbiter::TouchMotion,
581 /// The claimant chain the next synthesised scroll is to walk.
582 ///
583 /// Armed immediately before that scroll is pushed through
584 /// [`dispatch_scroll`](Self::dispatch_scroll) and taken by the router arm
585 /// that routes it, because the two producers know different things: a pan
586 /// has a live session to read, a coast has only the chain it was launched
587 /// with. `None` for every scroll from a backend, which derives its own
588 /// chain from the sample's position.
589 armed_chain: Option<Vec<(WidgetId, crate::pointer::touch_action::PanClaim)>>,
590 /// Monotonic counter bumped at the start of each `render()` call.
591 /// Each widget's `last_painted_epoch` is set to this value whenever
592 /// the paint pass (or the cache-hit early-out) confirms the widget
593 /// intersects the window viewport. The animation scheduler uses it
594 /// to detect and pause animations for widgets that have scrolled
595 /// off-screen. Starts at `0`, which serves as the "never painted"
596 /// sentinel; tests that only call `layout()` see the gate bypass.
597 pub(crate) paint_epoch: u64,
598 /// Cached accessibility tree update, rebuilt only when something that
599 /// changes the AT tree has happened, not on every layout.
600 cached_a11y: Option<accesskit::TreeUpdate>,
601 /// Whether the accessibility tree needs rebuilding. Set by focus moves,
602 /// overlay changes, widget rebuilds, active↔dormant transitions,
603 /// `AccessibilityOnly` binding flips and `request_accessibility_update()`;
604 /// a plain relayout does not set it.
605 a11y_dirty: bool,
606 /// Snapshot of `shortcut_registry.version()` at the last
607 /// `sync_accessibility` call. When the live version differs the
608 /// AT cache is dirtied, so widgets that bound their announced
609 /// shortcut via `access_shortcut_id(id)` track user rebinds
610 /// without any explicit signaling from the settings UI.
611 last_synced_shortcut_version: u64,
612 /// Snapshot of `locale_signal` at the last `sync_accessibility`
613 /// call. When the locale differs the AT cache is dirtied, so
614 /// `access_label(tr!(...))` (stored as a locale-bound
615 /// `Prop<String>`) re-resolves into the announced node — even on a
616 /// same-direction switch that doesn't rebuild the composite.
617 last_synced_locale: Option<String>,
618 /// The window title the last accessibility walk named the root after.
619 /// A new title re-walks the tree, as a locale switch does, so the
620 /// window's name follows it. See `accessibility_emit_impl`.
621 last_synced_window_title: Option<String>,
622 /// Reverse map from synthetic (widget-emitted) AccessKit NodeIds
623 /// to the WidgetId that owns them. Rebuilt on every full
624 /// accessibility walk. `handle_accessibility_actions` uses this
625 /// to route an `ActionRequest` targeting a TextRun child back
626 /// to the owning rich-text editor, since synthetic NodeIds
627 /// can't be decoded back to a WidgetId by value alone.
628 pub(crate) synthetic_parent_map: std::collections::HashMap<accesskit::NodeId, WidgetId>,
629 /// Where each synthetic child sits inside its owner, for the ones that
630 /// declared their bounds in the owner's own space (a label's line
631 /// boxes, an editor's rows). A pure translation re-places them from
632 /// here; a synthetic node absent from this map — a scene item under a
633 /// view transform, which reports absolute rects — is moved by the
634 /// owner's delta instead.
635 pub(crate) synthetic_local_bounds:
636 std::collections::HashMap<accesskit::NodeId, teksilo_canvas::Rect>,
637 /// Monotonic count of accessibility walks. A consumer that has not
638 /// seen the latest one is holding a tree whose *shape* may be stale,
639 /// not merely its geometry.
640 pub(crate) a11y_walk_generation: u64,
641 /// Cached full render frame — reused when no widget needs painting.
642 /// `Rc<RenderFrame>` rather than `RenderFrame` so cache-hit frames
643 /// cost an atomic refcount bump instead of a deep clone of every
644 /// draw-command Vec. `render()` uses `Rc::make_mut` to update
645 /// `anim_params` in place when the tree is the sole owner (the
646 /// common case — the caller usually drops the previous frame
647 /// before calling render() again).
648 cached_frame: Option<std::rc::Rc<RenderFrame>>,
649 /// Dispatches that arrived while another dispatch was in flight, replayed
650 /// once the outer one completes.
651 ///
652 /// A handler that dispatches (a synthetic click, an AT action re-entering
653 /// the door) must not observe half-updated pointer state, and must not be
654 /// able to unwind the sample the outer dispatch is still standing on. So a
655 /// nested dispatch is queued here rather than run inline, and drained —
656 /// faithfully, event *and* input snapshot — after the outer sample
657 /// completes. From the caller's side nothing changes: the queue is empty
658 /// again before the top-level `dispatch_*` call returns.
659 pending_dispatch: std::collections::VecDeque<pointer_router::QueuedDispatch>,
660 /// How many dispatches are on the stack. Non-zero means "queue, do not
661 /// re-enter"; see [`Self::pending_dispatch`].
662 dispatch_depth: u32,
663 /// Pointers whose current press was cancelled and which have not pressed
664 /// again since.
665 ///
666 /// `PointerCancel` is terminal: the interaction was taken away, so an `Up`
667 /// arriving for the same press afterwards must not complete it. A platform
668 /// can genuinely send both (Windows delivers a `WM_POINTERUP` after a
669 /// capture loss), so the `Up` is swallowed rather than asserted against.
670 /// An entry is dropped by that swallowed `Up`, or by the pointer's next
671 /// press — a fresh press is a fresh interaction. Bounded by the contact
672 /// cap plus the mouse.
673 cancelled_pointers: Vec<crate::pointer::PointerId>,
674 /// Current cursor selected by hover/interaction routing.
675 current_cursor: crate::widget::CursorIcon,
676 /// What the **node-declared** cursor mechanism last resolved for the
677 /// hovered chain — the value `PointerEnter` wrote, or `Default` after the
678 /// `PointerLeave` that undid it.
679 ///
680 /// Kept so a handler can hand the cursor back
681 /// ([`EventContext::release_cursor`]) after having overridden it, without
682 /// having to re-derive the chain's declaration and risk disagreeing with
683 /// the walk that produced it. It is exactly as fresh as `current_cursor`:
684 /// both move only when the enter/leave pair fires, so a node whose
685 /// `.cursor(..)` changes under a stationary pointer is stale in the same
686 /// way, and by the same mechanism.
687 ///
688 /// [`EventContext::release_cursor`]: crate::widget::EventContext::release_cursor
689 node_declared_cursor: crate::widget::CursorIcon,
690 /// Delayed overlay requests (e.g., submenu hover-open delay).
691 pending_delayed_overlays: Vec<PendingDelayedOverlay>,
692 /// Reusable scratch buffer for active-id snapshots taken on hot
693 /// paths that mutate per-widget state inside the loop
694 /// (`tick_gestures_with_ops`, post-render dirty-bit clear,
695 /// post-layout `needs_layout` clear). Cleared and refilled on
696 /// every use via `WidgetArena::fill_active_ids`. Previously these
697 /// sites called the allocating `arena.active_ids()` per frame,
698 /// which `perf record` ranked at ~13 % of CPU on the
699 /// `widget_catalog --tab animations` scene.
700 active_ids_scratch: Vec<WidgetId>,
701 /// Widgets currently carrying a non-`None` `EventHandlers::gesture_arena`.
702 /// Updated on attach (`ensure_gesture_arena` install) and on
703 /// teardown (rebuild / destroy / handler-clear). Every per-frame
704 /// gesture pass (`tick_gestures_with_ops`, `next_gesture_deadline`)
705 /// iterates this set instead of every active widget — most active
706 /// widgets have `gesture_arena = None`, so the savings come from
707 /// not even visiting them. Filtered by `arena.is_active(id)` at
708 /// iteration time so dormant entries don't fire (a widget can be
709 /// dormant while still holding its handlers).
710 gesture_owners: std::collections::HashSet<WidgetId>,
711 /// OS-level accessibility preferences (high contrast, reduced motion, text scale).
712 /// High contrast is a signal so a colour baked at build time (a recipe's
713 /// `ColorProp::Bound`) can follow it the way it follows window activation;
714 /// mutated only by `set_accessibility_preferences`.
715 prefers_high_contrast: crate::signal::Signal<bool>,
716 prefers_reduced_motion: bool,
717 text_scale_factor: f64,
718 /// Whether an assistive technology is reading the tree, as reported by the
719 /// *operating system* — not by AccessKit. See
720 /// [`Self::set_screen_reader_state`] for why the distinction matters.
721 /// A signal so an application can follow it; written only through
722 /// `set_if_changed`, so an observer fires on a real change.
723 screen_reader: crate::signal::Signal<crate::environment::ScreenReaderState>,
724 /// The app's explore-by-touch policy. See [`Self::set_explore_by_touch`].
725 explore_by_touch: crate::environment::ExploreByTouch,
726 /// Whether an AccessKit client is currently attached to this window's
727 /// adapter. Written by `teksilo-app` from the platform adapter's
728 /// activation / deactivation handlers.
729 at_client_attached: bool,
730 /// How a density switch should be worded to a screen reader, if the
731 /// application wants one announced. See
732 /// [`Self::set_density_announcement`].
733 density_announcement: Option<std::rc::Rc<dyn Fn(teksilo_tokens::TargetDensity) -> String>>,
734 /// How "a context menu opened" should be worded to a screen reader when a
735 /// **hold** opened it, if the application wants one announced. See
736 /// [`Self::set_context_menu_announcement`].
737 context_menu_announcement: Option<std::rc::Rc<dyn Fn() -> String>>,
738 /// The tree-owned long press the router is waiting out, if any. One at a
739 /// time: two fingers holding two different controls is not a gesture any
740 /// desktop idiom assigns a meaning to, and the second contact's arrival
741 /// replaces the first's route rather than racing it. See
742 /// [`touch_route`].
743 pending_touch_route: Option<touch_route::PendingTouchRoute>,
744 /// Host window HiDPI device scale (physical px per logical px), fed by
745 /// `teksilo-app` before each layout. Surfaced to widgets via
746 /// `LayoutContext::scale_factor`. The widget tree is otherwise fully
747 /// logical (the renderer applies this scale at the vertex stage); this is
748 /// the escape hatch for widgets that must size a device-pixel OS resource
749 /// (e.g. a `WebView`'s native subview). 1.0 in headless / test contexts.
750 device_scale_factor: f32,
751 /// Reactive mirror of `device_scale_factor`, for the widgets whose layout
752 /// reads it: see [`Self::device_scale_signal`].
753 device_scale_signal: crate::signal::Signal<f32>,
754 /// What the tree's widgets attached for content updated off the UI
755 /// thread (`RepaintTrigger`), and the waker their requests wake. See
756 /// [`crate::off_thread`].
757 pub(crate) off_thread: crate::off_thread::OffThreadRegistry,
758 /// Platform safe-area insets for the host window — a notch, a rounded
759 /// corner, a home indicator — in logical pixels, fed by `teksilo-app`
760 /// after every window resize. Reaches overlay placement through
761 /// [`OverlayViewport::safe_area`](crate::overlay::OverlayViewport::safe_area).
762 /// `ZERO` on every platform that reports nothing, which is every desktop
763 /// platform but macOS.
764 safe_area: teksilo_canvas::EdgeInsets,
765 /// A rectangle of the window currently covered by something outside the
766 /// tree — a soft keyboard, a platform IME candidate window — in
767 /// window-logical pixels. Reaches overlay placement through
768 /// [`OverlayViewport::occluded`](crate::overlay::OverlayViewport::occluded).
769 /// `None` on every frame where nothing is covering the window.
770 occluded_inset: Option<Rect>,
771 /// A pending `EventContext::request_soft_keyboard` call, taken by the app
772 /// layer once per dispatch. `Some(true)` asks for the keyboard,
773 /// `Some(false)` asks it to go away.
774 soft_keyboard_request: Option<bool>,
775 /// Active drag-and-drop session, if any.
776 pub(crate) active_drag: Option<crate::drag_state::DragSession>,
777 /// Source widget of an in-flight OS (outbound) drag that escalated past
778 /// the window boundary. Set only on the window that *started* the drag.
779 /// The in-app `active_drag` session is torn down at escalation (the OS owns
780 /// the pointer); this remembers who started it so the eventual `DragEnded`
781 /// can fire the source's `on_drag_ended`.
782 pub(crate) outbound_drag_source: Option<WidgetId>,
783 /// True while *this* window currently holds the re-entered internal session
784 /// for an in-flight app-originated OS drag (the OS drag wandered back over
785 /// this window — possibly a different window than the source — and we
786 /// restored the original typed payload). Distinguishes that session from a
787 /// plain internal drag so leaving again re-stashes instead of starting a
788 /// second OS drag, and dropping doesn't double-fire `on_drag_ended`.
789 pub(crate) os_drag_reentered: bool,
790 /// True while the platform has been asked to start a native drag for the
791 /// in-app `active_drag` and answered
792 /// [`OsDragStart::Pending`](crate::OsDragStart::Pending): the in-app session
793 /// stays alive (preview, capture, hover) until the platform confirms the
794 /// start, and a release meanwhile ends the drag as `Cancelled`.
795 pub(crate) os_drag_pending: Option<crate::drag_payload::OsDragId>,
796 /// The id of the native drag this window started and handed its session
797 /// to after a confirmed [`OsDragStart::Pending`](crate::OsDragStart::Pending),
798 /// so a tagged end of another drag is not taken for this one's. `None`
799 /// for a drag the platform started at once (it posts untagged events).
800 pub(crate) outbound_drag_id: Option<crate::drag_payload::OsDragId>,
801 /// The in-app outcome of our own OS drag dropped back on the window that
802 /// started it, held until the platform's terminal `DragEnded` so the
803 /// source hears `InApp { accepted }` instead of the platform's `OsCopy`.
804 pub(crate) reentered_drop_outcome: Option<crate::drag_payload::DropOutcome>,
805 /// The accept state last pushed to the platform for an inbound OS drag, so
806 /// the same answer is not re-sent on every motion sample.
807 ///
808 /// `None` outside an OS drag, and reset when one ends — a fresh drag must
809 /// push its first verdict even if it happens to match the last drag's.
810 pub(crate) os_drop_accepted: Option<bool>,
811 /// Optional platform host for custom window chrome (set when the
812 /// application opts in via `WindowConfig::custom_chrome(true)`). Stored
813 /// here so that the root-builder closure has access during widget
814 /// construction; the same `Rc` is also held by `WindowManager` so it
815 /// outlives the widget tree if needed.
816 title_bar_host: Option<Rc<dyn crate::PlatformTitleBarHost>>,
817 /// App-level subscription state: registered event source adapter,
818 /// proxy poster, UI-side subscription callbacks. Default is empty;
819 /// teksilo-app installs a populated context when an event source is
820 /// registered on the builder.
821 pub(crate) app_context: Rc<crate::event_source::TreeAppContext>,
822 /// Active locale identifier. Cached for `Option<&str>` accessors; the
823 /// reactive source of truth is `locale_signal`. Both are updated in
824 /// lockstep by `set_locale`.
825 pub(crate) locale: Option<String>,
826 /// Reactive locale signal. Widgets and `LocalizedString` adapters bind to
827 /// this signal to react to locale changes; `set_locale` updates the signal
828 /// without rebuilding the widget tree.
829 pub(crate) locale_signal: crate::signal::Signal<Option<String>>,
830 /// Per-frame delta-seconds signal, advanced by `layout()` **only when
831 /// a frame was asked for**: through `request_frame()`, or by the
832 /// render-end re-arm for a painted frame-tick subscriber. This
833 /// preserves Teksilo's draw-when-needed model: idle trees stay idle
834 /// even if widgets have registered observers on this signal.
835 pub(crate) frame_tick: crate::signal::Signal<f32>,
836 /// Set by `request_frame()`; consumed by `advance_frame_tick()` on
837 /// the next `layout()`. Observers that need another tick after the
838 /// current one must re-request. Stored as `Rc<Cell>` so observers
839 /// fired from inside the layout pass (`ctx.effect` closures on
840 /// `frame_tick`) can chain-request without needing &mut access
841 /// to the tree — see [`frame_request_handle`](Self::frame_request_handle).
842 pub(crate) frame_tick_requested: std::rc::Rc<std::cell::Cell<bool>>,
843 /// Set after a render in which a frame-tick subscriber's owner was
844 /// painted; consumed alongside `frame_tick_requested` by
845 /// `advance_frame_tick()`.
846 ///
847 /// A flag of its own so that [`frame_tick_deadline`](Self::frame_tick_deadline)
848 /// knows *why* a frame is wanted. A throttled subscriber may stretch the
849 /// wait for its own tick to its interval; a frame asked for through
850 /// `frame_tick_requested` (the announcer's follow-up syncs, a caret, a
851 /// drag auto-scroll) is due at 60 Hz whatever is on screen. When both
852 /// reasons shared one flag they could not be told apart, and a
853 /// once-a-minute clock anywhere in the window made every requested frame
854 /// wait a minute.
855 pub(crate) frame_tick_armed_by_subscribers: bool,
856 /// Debug-only re-entrancy flag: `true` while a focus-change dispatch
857 /// (`FocusGained` / `FocusLost` handlers) is running. Threaded into each
858 /// `EventContext` so `open_window` / `focus_window` can warn if a handler
859 /// changes context merely because a control gained focus (WCAG 3.2.1). A
860 /// shared `Rc<Cell<bool>>` (like `frame_tick_requested`) so the flag is
861 /// readable from an `EventContext` that holds no `&mut` to the tree.
862 pub(crate) in_focus_dispatch: std::rc::Rc<std::cell::Cell<bool>>,
863 /// Shared "accessibility re-walk requested" flag. Set via
864 /// [`request_accessibility_update`](Self::request_accessibility_update)
865 /// (or its `BuildContext` / `EventContext` wrappers) and drained at the
866 /// top of [`sync_accessibility`](Self::sync_accessibility) into
867 /// `a11y_dirty`. A relayout no longer re-walks the AT tree on its own, so
868 /// widgets that restructure their subtree in an AT-affecting way (e.g.
869 /// `SceneView` materialising / destroying scene widgets) need this lever.
870 /// `Rc<Cell>` so the shared `&self` paths can toggle it like
871 /// `frame_tick_requested`.
872 pub(crate) a11y_update_requested: std::rc::Rc<std::cell::Cell<bool>>,
873 /// Delayed frame wake-up deadline. Widgets that need to schedule
874 /// a future frame without pumping at full framerate (caret blink,
875 /// etc.) store the target instant here via
876 /// [`wake_at_handle`](Self::wake_at_handle). `next_timer_deadline`
877 /// rolls it into the event loop's WaitUntil; when reached, the
878 /// next `layout()` automatically re-arms `frame_tick_requested`
879 /// so the frame-tick effects run on the wake-up pass.
880 pub(crate) pending_wake_at: std::rc::Rc<std::cell::Cell<Option<std::time::Instant>>>,
881 /// One-shot post-mount actions enqueued during `build()` via
882 /// [`BuildContext::run_after_mount`](crate::BuildContext::run_after_mount), drained by the app loop (and by
883 /// tests) through [`WidgetTree::run_mount_actions`] with a real
884 /// [`EventContext`] — the only place a widget
885 /// can read the OS parent handle / app-state / poster together after it is
886 /// mounted. Used by widgets that own a native resource needing a window
887 /// handle to initialise (a `WebView`'s engine subview).
888 pub(crate) pending_mount_actions: Vec<Box<dyn FnOnce(&mut crate::widget::EventContext)>>,
889 /// Wall-clock time of the previous `layout()` call (for delta computation).
890 pub(crate) last_frame_time: Option<std::time::Instant>,
891 /// Set by [`EventContext::close_window`] during dispatch; drained
892 /// by the application event loop after each event via
893 /// [`WidgetTree::take_close_window_request`]. A *guarded* close
894 /// request — the app routes it through the window's close guard.
895 pub(crate) close_window_requested: bool,
896 /// Set by [`EventContext::close_window_forced`] during dispatch;
897 /// drained via [`WidgetTree::take_force_close_request`]. An
898 /// *unconditional* close request that bypasses the window's close
899 /// guard.
900 pub(crate) force_close_requested: bool,
901 /// Raised by [`EventContext::set_locale`] during dispatch; drained by
902 /// the application event loop (see
903 /// `WindowManager::drain_pending_locale_requests`) so the switch can be
904 /// routed through the `I18nManager` (active locale + version signal +
905 /// RTL direction). `WidgetTree::set_locale` alone would only update the
906 /// tree's local locale signal — the i18n thread-local would stay put
907 /// and `tr!` lookups would not re-resolve.
908 pub(crate) pending_locale_request: Option<String>,
909 /// Raised by [`EventContext::set_theme`] during dispatch; drained by
910 /// the application event loop (see
911 /// `WindowManager::drain_pending_theme_requests`) so the switch is
912 /// routed through `WindowManager::set_theme`, which fans the new theme
913 /// out to *every* window. Applying via `WidgetTree::set_theme` inline
914 /// would only re-theme the originating window — the rest of the app
915 /// would stay on the old theme. Mirrors `pending_locale_request`.
916 pub(crate) pending_theme_request: Option<crate::styles::Theme>,
917 /// Raised by [`EventContext::follow_system_theme`] during dispatch;
918 /// drained by the application event loop (see
919 /// `WindowManager::drain_pending_follow_system_requests`), which switches
920 /// the app to `ThemeMode::Native` and recomputes the theme from current
921 /// OS colours. Mirrors `pending_theme_request`.
922 pub(crate) pending_follow_system_request: bool,
923 /// Raised by [`EventContext::set_text_scale`] during dispatch; drained by
924 /// the application event loop (see
925 /// `WindowManager::drain_pending_text_scale_requests`) so the change is
926 /// routed through `WindowManager::set_text_scale`, fanning the new factor
927 /// out to *every* window. Mirrors `pending_theme_request`.
928 pub(crate) pending_text_scale_request: Option<f32>,
929 /// Monotonic version counter bumped after every *real* accessibility
930 /// rebuild in [`Self::sync_accessibility`] (cache hits don't bump).
931 /// Mirror of [`crate::shortcut::ShortcutRegistry::version`]: an
932 /// automation / test harness can poll it to know whether the AT tree
933 /// changed without diffing the whole `TreeUpdate`.
934 at_version: crate::signal::Signal<u64>,
935 /// The framework's own live regions, one per politeness level. See
936 /// [`crate::announcer`]: each speaks every message from a node the tree
937 /// has never had, which is the only mechanism all three platform adapters
938 /// agree announces, and never in an update that moves focus.
939 announcer_polite: crate::announcer::Announcer,
940 announcer_assertive: crate::announcer::Announcer,
941 /// Where both announcers draw the id of each message's node from, so no
942 /// message is spoken from an id the tree has used before.
943 announcer_ids: crate::announcer::AnnouncerIds,
944 /// The announcements the platform adapters would have made from the
945 /// updates `sync_accessibility` returned (see
946 /// [`crate::accessibility::Announcement`]), drained by
947 /// [`Self::announcements_since`], while the tree records them
948 /// ([`Self::set_records_announcements`]).
949 announcement_ring: crate::accessibility::announcements::AnnouncementRing,
950 /// The ids the window's platform adapter holds, which differ from the
951 /// tree's own for a node that left the tree a reader sees and came back.
952 /// See [`crate::accessibility::adapter_ids`] and
953 /// [`Self::deliver_accessibility`].
954 adapter_ids: crate::accessibility::adapter_ids::AdapterIds,
955 /// What the last delivered update said about descriptions and live
956 /// regions, which is what the next one's descriptions are measured
957 /// against. See [`accessibility_description_impl`].
958 description_memory: accessibility_description_impl::DescriptionMemory,
959 /// Whether the `WidgetEvent::AccessAction` currently being dispatched was
960 /// consumed by a handler. Written by the dispatcher's `AccessAction` arm,
961 /// read (and reset) by [`Self::dispatch_access_action`], which is the only
962 /// caller that can answer "did anything happen?" to its own caller.
963 ///
964 /// A side channel because `dispatch_event_with_ops` returns `()` for every
965 /// event kind, and routing AT actions through the *same* path as everything
966 /// else is load-bearing (it is what lets an action open a window). The
967 /// alternative — reporting success whenever a live widget merely *existed*
968 /// at the target — is how an unhandled action came to look like a
969 /// successful one to every automation client.
970 access_action_handled: bool,
971 /// The `WindowState` for this tree's hosting window. Populated
972 /// by the app-level window manager when the tree is registered;
973 /// `None` for standalone trees. Cloned into every `EventContext`
974 /// and `BuildContext` so widgets can bind to the current window's
975 /// signals via `ctx.window()`.
976 pub(crate) window_state: Option<crate::window::WindowState>,
977 /// The widget each held key's press was delivered to, by key identity
978 /// (see `pointer_router`'s key-release redirect): a release goes there,
979 /// not to whatever focus moved to while the key was down.
980 key_presses: Vec<(u64, WidgetId)>,
981 /// The identity of the key event being dispatched, and whether it is an
982 /// auto-repeat.
983 current_key: Option<(u64, bool)>,
984}
985
986/// How long the shortened reshow delay stays active after the last tooltip
987/// dismisses. Long enough to cover moving between adjacent toolbar icons;
988/// short enough that a later, deliberate hover still pays the full initial
989/// delay. Not a theme token — it is session bookkeeping, not a visual feel.
990const TOOLTIP_SESSION_GRACE: std::time::Duration = std::time::Duration::from_millis(1000);
991
992/// Number of visible steps a sticky-on-dwell tooltip's promotion window is
993/// divided into.
994///
995/// The tree uses this only to decide *how often to wake* while a dwell is
996/// running — one redraw per step boundary rather than a free-run — but it must
997/// match the step count the content widget actually renders, or the indicator
998/// would advance on a different beat from the wake-ups driving it.
999/// `teksilo-widgets`' `DWELL_STEPS` is defined *as* this constant, so the two
1000/// cannot drift; the per-step *duration* is derived from each entry's own
1001/// `sticky_after`, so a caller that picks a non-default promotion window still
1002/// gets correctly-spaced wake-ups.
1003pub const TOOLTIP_DWELL_STEPS: u32 = 4;
1004
1005/// Max pointer travel (logical px) from the hover-origin before a pending
1006/// tooltip timer restarts. Mirrors Windows hover-tracking slop
1007/// (`SPI_GETMOUSEHOVERWIDTH` / height, typically ~4 px): the tip waits for a
1008/// *paused* pointer, not merely "entered the bounds."
1009const TOOLTIP_STATIONARY_SLOP: f32 = 4.0;
1010
1011/// A tooltip attachment managed by the WidgetTree.
1012struct TooltipEntry {
1013 anchor_id: WidgetId,
1014 content_id: WidgetId,
1015 /// The widget whose accessibility node should carry this tooltip's
1016 /// description, which is not always the node the overlay hangs off.
1017 ///
1018 /// A composing control anchors the *overlay* on an inner chrome node it
1019 /// built -- the thing with the right bounds to open a tooltip against --
1020 /// while its role, its name and its focusability live on its own outer
1021 /// node. A description on the inner one is a description an assistive
1022 /// technology never reads, because it never lands there.
1023 ///
1024 /// Recorded by `BuildContext`'s `attach_tooltip*` wrappers as the widget
1025 /// that was building at the time. Defaults to `anchor_id`, which is both
1026 /// the historic behaviour and the right answer for a widget that anchors
1027 /// its tooltip on itself.
1028 ///
1029 /// Naming an owner is a *claim*, not a guarantee: the accessibility walk
1030 /// honours it only where exactly one tooltip claims that node. See
1031 /// `WidgetTree::build_accessibility_recursive`.
1032 description_owner_id: WidgetId,
1033 delay: std::time::Duration,
1034 /// Simulated hover start (for deterministic tests via advance_time).
1035 hover_start: Option<std::time::Instant>,
1036 /// Real hover start (for windowed apps via layout).
1037 real_hover_start: Option<std::time::Instant>,
1038 /// Pointer position when the current pending hover started. Used to
1039 /// restart the delay if the pointer keeps moving inside the anchor
1040 /// (stationary-pointer intent filter).
1041 hover_origin: Option<teksilo_canvas::Point>,
1042 overlay_id: Option<crate::overlay::OverlayId>,
1043 /// When set, the tooltip auto-promotes to "sticky" after this
1044 /// much elapsed time since it was shown. The entry stays in the
1045 /// table and is just flagged sticky — the difference is that
1046 /// pointer-leave no longer dismisses it and the overlay's
1047 /// dismiss behavior is swapped to `EscapeOrClickOutside`.
1048 sticky_after: Option<std::time::Duration>,
1049 /// True when the dwell timer reached `sticky_after`. Causes
1050 /// `tooltip_pointer_leave` to skip the dismissal and lets the
1051 /// overlay survive pointer-leave until the user explicitly
1052 /// dismisses it via Escape or a click outside.
1053 is_sticky: bool,
1054 /// When the overlay was shown (simulated). Together with
1055 /// `sticky_after` drives auto-promotion.
1056 shown_at_sim: Option<std::time::Instant>,
1057 /// When the overlay was shown (real).
1058 shown_at_real: Option<std::time::Instant>,
1059 /// Optional shared sink the tooltip widget can read from to
1060 /// compute its own dwell progress. Mirrors `shown_at_real`:
1061 /// set on show, cleared on dismissal. Used by `RichTooltipWidget`
1062 /// to drive the dwell indicator without relying on a fragile
1063 /// paint-gap heuristic.
1064 shown_at_sink: Option<std::rc::Rc<std::cell::Cell<Option<std::time::Instant>>>>,
1065 /// True when the tooltip was *shown* by the keyboard-focus path rather
1066 /// than the pointer-hover path (the name is historical: such a tip is no
1067 /// longer promoted by its focus rest, see `dwell_promotes`). Focus-shown
1068 /// tooltips dismiss when focus moves outside both the anchor and the
1069 /// tooltip content subtree (preventing accumulation as the user Tabs
1070 /// through a form); pointer-dwelled stickies survive focus changes and
1071 /// only dismiss via Escape or click-outside.
1072 promoted_by_focus: bool,
1073 /// Whether the dwell sweep may promote this shown tip to sticky once
1074 /// `sticky_after` has run. True for a tip a pointer rest or a hold
1075 /// showed; false for one focus showed, until a pointer comes over its
1076 /// anchor (and false again when it leaves before the dwell ends). A
1077 /// focus rest is not a request to enter the tip: its text reaches a
1078 /// screen reader through the anchor's description, and it takes no Tab
1079 /// stop.
1080 dwell_promotes: bool,
1081 /// Set while this entry's pending delay was started by keyboard focus
1082 /// rather than by the pointer. Decides, at show time, that the surface
1083 /// dismisses on `Escape`/click-outside rather than on pointer-leave (there
1084 /// is no pointer in the story), that it counts as focus-shown, and that
1085 /// its dwell does not promote it.
1086 armed_by_focus: bool,
1087 /// Set while this entry's pending delay was started by a **hold** — the
1088 /// tree-owned long-press route in [`touch_route`].
1089 ///
1090 /// Decides two things at show time that neither the hover nor the focus arm
1091 /// wants: the surface dismisses on `Escape` / a press outside (a finger has
1092 /// already lifted, so there is no pointer left to leave), and it carries an
1093 /// auto-dismiss of [`touch_route::TOUCH_TOOLTIP_DISMISS`] — because with no
1094 /// pointer to leave and no focus to move, nothing else would ever retire it.
1095 armed_by_hold: bool,
1096 /// Set when the tip was dismissed while the focus that summoned it is
1097 /// still inside its anchor — i.e. Escape on a focus-promoted tooltip.
1098 ///
1099 /// Escape restores focus to the anchor, and that restore runs the ordinary
1100 /// focus path, which ends in `tooltip_focus_enter`. Without this flag the
1101 /// tip the user just dismissed re-opens on the same keystroke, because
1102 /// `dormant_dismissed_content` has already cleared `overlay_id` by then and
1103 /// the entry looks eligible again. Cleared when focus genuinely leaves the
1104 /// anchor (`tooltip_focus_leave_outside`), so Tabbing away and back
1105 /// re-summons it normally. The hover path needs no equivalent: a stationary
1106 /// pointer never re-fires `tooltip_pointer_enter`.
1107 suppressed_until_focus_leaves: bool,
1108 /// Where the tooltip opens relative to its anchor. `Below` (default)
1109 /// for the common case; `Side` for anchors stacked vertically (menu
1110 /// items, a vertical tab strip, list/tree rows) so the tooltip does
1111 /// not cover the next sibling. Consulted at show time in both the
1112 /// hover (`process_tooltips_impl`) and focus (`tooltip_focus_enter`)
1113 /// paths.
1114 placement: crate::overlay::TooltipPlacement,
1115}
1116
1117/// A delayed overlay request (e.g., submenu hover-open delay).
1118struct PendingDelayedOverlay {
1119 request: crate::overlay::OverlayRequest,
1120 delay: std::time::Duration,
1121 focus_target: Option<WidgetId>,
1122 /// Dismiss the anchor's sibling overlays when this one finally
1123 /// shows, instead of when it was requested. See
1124 /// [`EventContext::show_overlay_after_replacing_siblings`](crate::widget::EventContext::show_overlay_after_replacing_siblings).
1125 replace_siblings: bool,
1126 /// When the request was made (real time, for windowed apps).
1127 real_requested_at: std::time::Instant,
1128 /// When the request was made (simulated time, for tests).
1129 sim_requested_at: std::time::Instant,
1130}
1131
1132impl WidgetTree {
1133 pub fn new() -> Self {
1134 let initial_theme = crate::presets::intui::light();
1135 // One signal, shared: the field the tree writes and the registry the
1136 // application reads must be the same one, or a host mirroring "is the
1137 // caret in a text widget" would never see focus move.
1138 let focused_signal = crate::signal::Signal::new(None);
1139 // ONE epoch. `sim_clock` starts here and the input clock is anchored
1140 // here, so a single `advance_time` moves gesture deadlines, tooltips,
1141 // overlays and animations against the same origin.
1142 let epoch = std::time::Instant::now();
1143 // ONE scheduler. The fling pump shares the tree's per-frame table
1144 // rather than making a second one, so a coast wakes the loop through
1145 // the same path a `Pulse` does.
1146 let scheduler = crate::frame_tick_scheduler::FrameTickScheduler::new();
1147 Self {
1148 arena: WidgetArena::new(),
1149 theme: initial_theme.clone(),
1150 theme_signal: crate::signal::Signal::new(initial_theme.clone()),
1151 density_policy: teksilo_tokens::DensityPolicy::default(),
1152 user_text_scale: 1.0,
1153 effective_theme: initial_theme,
1154 effective_text_scale: 1.0,
1155 text_scale_signal: crate::signal::Signal::new(1.0),
1156 // Starts active: winit may not send `Focused(true)` for the first
1157 // window, so a window must not be born inactive (caret hidden,
1158 // selection muted) before the first focus event arrives.
1159 window_active_signal: crate::signal::Signal::new(true),
1160 text_backend: None,
1161 content_root: None,
1162 focused: None,
1163 focused_signal: focused_signal.clone(),
1164 pointers: crate::pointer::table::PointerTable::new(),
1165 hovered_signal: crate::signal::Signal::new(None),
1166 last_pointer_kind_signal: crate::signal::Signal::new(
1167 teksilo_tokens::PointerKind::Mouse,
1168 ),
1169 focus_visible: crate::signal::Signal::new(false),
1170 presses: crate::press::PressTable::default(),
1171 view_focus_stack: Vec::new(),
1172 previous_pointer_position: None,
1173 hover_owner_outside_window: false,
1174 tooltip_dwell_held: false,
1175 pending_focus_restore: Vec::new(),
1176 pending_focus_request: None,
1177 last_interaction_anchors: Vec::new(),
1178 last_proposal: SizeProposal::exact(800.0, 600.0),
1179 layout_passes: 0,
1180 rebuild_marks_laid_out: 0,
1181 rebuild_deferred: false,
1182 disabled_focus_stays: None,
1183 activation_pending: false,
1184 pending_modal_requests: Vec::new(),
1185 pending_modal_dismissal: false,
1186 shortcut_registry: {
1187 let mut registry = crate::shortcut::ShortcutRegistry::new();
1188 crate::shortcut::register_standard_shortcuts(&mut registry);
1189 crate::shortcut::register_focus_region_shortcuts(&mut registry);
1190 registry
1191 },
1192 pending_intents: Vec::new(),
1193 unclaimed_intents: None,
1194 application_scope: None,
1195 command_watchers: Vec::new(),
1196 routed_crossings: None,
1197 global_actions: Vec::new(),
1198 text_surfaces: crate::text_surface::TextSurfaces::new(focused_signal.clone()),
1199 key_capture: None,
1200 binding_registry: crate::binding::BindingRegistry::new(),
1201 idle_queue: crate::idle::IdleQueue::new(),
1202 sim_clock: epoch,
1203 input_clock: std::rc::Rc::new(crate::pointer::clock::MonotonicClock::new(epoch)),
1204 current_input: crate::pointer::InputSnapshot::default(),
1205 sim_time_frozen: false,
1206 sim_input_origin: None,
1207 sim_input_offset: std::time::Duration::ZERO,
1208 focus_origin: None,
1209 overlay_manager: crate::overlay::OverlayManager::new(),
1210 draining_dismiss: std::cell::Cell::new(false),
1211 tooltips: Vec::new(),
1212 tooltip_session_until_sim: None,
1213 tooltip_session_until_real: None,
1214 highlight_tooltip: None,
1215 layout_direction: crate::environment::LayoutDirection::default(),
1216 animation_scheduler: crate::animation::AnimationScheduler::new(),
1217 animated_values: Vec::new(),
1218 animated_quads: crate::animated_quad::AnimatedQuadRegistry::new(),
1219 frame_tick_scheduler: scheduler.clone(),
1220 touch_motion: pan_arbiter::TouchMotion::new(scheduler),
1221 armed_chain: None,
1222 paint_epoch: 0,
1223 cached_a11y: None,
1224 a11y_dirty: true,
1225 last_synced_shortcut_version: 0,
1226 last_synced_locale: None,
1227 last_synced_window_title: None,
1228 synthetic_parent_map: std::collections::HashMap::new(),
1229 synthetic_local_bounds: std::collections::HashMap::new(),
1230 a11y_walk_generation: 0,
1231 cached_frame: None,
1232 pending_dispatch: std::collections::VecDeque::new(),
1233 cancelled_pointers: Vec::new(),
1234 dispatch_depth: 0,
1235 current_cursor: crate::widget::CursorIcon::Default,
1236 node_declared_cursor: crate::widget::CursorIcon::Default,
1237 pending_delayed_overlays: Vec::new(),
1238 active_ids_scratch: Vec::new(),
1239 gesture_owners: std::collections::HashSet::new(),
1240 prefers_high_contrast: crate::signal::Signal::new(false),
1241 prefers_reduced_motion: false,
1242 text_scale_factor: 1.0,
1243 screen_reader: crate::signal::Signal::new(
1244 crate::environment::ScreenReaderState::default(),
1245 ),
1246 explore_by_touch: crate::environment::ExploreByTouch::default(),
1247 at_client_attached: false,
1248 density_announcement: None,
1249 context_menu_announcement: None,
1250 pending_touch_route: None,
1251 device_scale_factor: 1.0,
1252 device_scale_signal: crate::signal::Signal::new(1.0),
1253 off_thread: crate::off_thread::OffThreadRegistry::default(),
1254 safe_area: teksilo_canvas::EdgeInsets::ZERO,
1255 occluded_inset: None,
1256 soft_keyboard_request: None,
1257 active_drag: None,
1258 outbound_drag_source: None,
1259 os_drag_reentered: false,
1260 os_drag_pending: None,
1261 outbound_drag_id: None,
1262 reentered_drop_outcome: None,
1263 os_drop_accepted: None,
1264 title_bar_host: None,
1265 app_context: Rc::new(crate::event_source::TreeAppContext::empty()),
1266 locale: None,
1267 locale_signal: crate::signal::Signal::new(None),
1268 frame_tick: crate::signal::Signal::new(0.0_f32),
1269 frame_tick_requested: std::rc::Rc::new(std::cell::Cell::new(false)),
1270 frame_tick_armed_by_subscribers: false,
1271 in_focus_dispatch: std::rc::Rc::new(std::cell::Cell::new(false)),
1272 a11y_update_requested: std::rc::Rc::new(std::cell::Cell::new(false)),
1273 pending_wake_at: std::rc::Rc::new(std::cell::Cell::new(None)),
1274 pending_mount_actions: Vec::new(),
1275 last_frame_time: None,
1276 close_window_requested: false,
1277 force_close_requested: false,
1278 pending_locale_request: None,
1279 pending_theme_request: None,
1280 pending_follow_system_request: false,
1281 pending_text_scale_request: None,
1282 at_version: crate::signal::Signal::new(0),
1283 announcer_polite: crate::announcer::Announcer::new(
1284 crate::announcer::Politeness::Polite,
1285 ),
1286 announcer_assertive: crate::announcer::Announcer::new(
1287 crate::announcer::Politeness::Assertive,
1288 ),
1289 announcer_ids: crate::announcer::AnnouncerIds::new(),
1290 announcement_ring: crate::accessibility::announcements::AnnouncementRing::new(),
1291 adapter_ids: crate::accessibility::adapter_ids::AdapterIds::new(),
1292 description_memory: Default::default(),
1293 access_action_handled: false,
1294 window_state: None,
1295 key_presses: Vec::new(),
1296 current_key: None,
1297 }
1298 }
1299
1300 /// Construct an [`EventContext`]
1301 /// pre-populated with the tree's app-state registry, hosting
1302 /// `WindowState`, and a `&mut dyn WindowOps` handle so handlers
1303 /// can synchronously reach the multi-window API. Used by every
1304 /// dispatch site.
1305 pub(crate) fn make_event_context<'ops>(
1306 &self,
1307 ops: &'ops mut dyn crate::window::WindowOps,
1308 ) -> crate::widget::EventContext<'ops> {
1309 let drag_is_external = self.active_drag.as_ref().is_some_and(|d| d.is_external);
1310 // Read-only snapshot of tree query state that handlers may
1311 // need synchronously: the last pointer position and a
1312 // (content_id, bounds) slice of open overlays, both read by the
1313 // safe-triangle submenu hover gate, and the focused widget, read
1314 // by a container deciding whether a shortcut of its own should
1315 // yield to the widget the user is standing on.
1316 let overlay_snapshot: Vec<(
1317 crate::widget_id::WidgetId,
1318 teksilo_canvas::Rect,
1319 Option<teksilo_canvas::Point>,
1320 )> = self
1321 .overlay_manager
1322 .active_content_ids()
1323 .into_iter()
1324 .filter_map(|cid| {
1325 self.overlay_manager
1326 .bounds_for_content(cid)
1327 .map(|r| (cid, r, self.unexpired_safe_apex_for_content(cid)))
1328 })
1329 .collect();
1330 crate::widget::EventContext::new()
1331 .with_app_context(self.app_context.clone())
1332 .with_window_context(ops, self.window_state.clone())
1333 .with_drag_external(drag_is_external)
1334 .with_key_identity(self.current_key.map(|(identity, _)| identity))
1335 .with_query_snapshot(
1336 self.last_pointer_position(),
1337 overlay_snapshot,
1338 self.focused(),
1339 )
1340 .with_pointer_captor(self.current_pointer_capture())
1341 .with_layout_direction(self.layout_direction)
1342 .with_window_active(self.is_window_active())
1343 .with_screen_reader_state(self.screen_reader.get())
1344 .with_modal_open(self.overlay_manager.has_open_modal())
1345 .with_input_snapshot(self.current_input.clone())
1346 .with_touch_action(self.current_frozen_touch_action())
1347 .with_press(self.current_press_snapshot())
1348 .with_focus_dispatch_flag(self.in_focus_dispatch.clone())
1349 }
1350
1351 /// Run a closure with a fresh [`EventContext`] anchored at this
1352 /// tree, then collect any pending operations queued through the
1353 /// context. Intents are dispatched before returning; modal requests,
1354 /// frame requests and idle callbacks are collected for the event loop.
1355 ///
1356 /// Used by the `teksilo-app` event-loop dispatcher to deliver
1357 /// async-result callbacks (file dialogs, future background
1358 /// tasks) on the main thread with full handler-equivalent
1359 /// semantics. There is no source widget for app-level events,
1360 /// so intents start at the window's [content root](Self::set_content_root)
1361 /// (or are silently dropped when the tree is empty). A callback that
1362 /// gives the user's command (a native menu item) sends it with
1363 /// [`EventContext::send_intent_from_focus`](crate::widget::EventContext::send_intent_from_focus)
1364 /// so that it starts at the focused widget, while its other effects stay
1365 /// anchored at the root.
1366 pub fn run_with_event_context<F>(&mut self, ops: &mut dyn crate::window::WindowOps, f: F)
1367 where
1368 F: FnOnce(&mut crate::widget::EventContext),
1369 {
1370 let anchor = self.intent_anchor();
1371 self.run_with_event_context_from(anchor, ops, f);
1372 }
1373
1374 /// Record `id` as the widget the window's own root builder made, when
1375 /// the tree's first root is a wrapper around it (the debug inspector's
1376 /// shell, the toast host, any post-root hook). `teksilo-app` sets it as
1377 /// it builds the window.
1378 ///
1379 /// Intents with no source widget (app callbacks, a global shortcut or a
1380 /// native menu item with nothing focused, an intent routed from another
1381 /// tree with nothing focused) start there rather than at the wrapper: the walk up from the wrapper never reaches an action
1382 /// the app registered on its own root, which made such an action
1383 /// unreachable in every debug build that installed the inspector.
1384 #[doc(hidden)]
1385 pub fn set_content_root(&mut self, id: WidgetId) {
1386 self.content_root = Some(id);
1387 }
1388
1389 /// Where an intent with no source widget starts its walk to the root:
1390 /// the [content root](Self::set_content_root) while it is in the tree,
1391 /// else the tree's first root. `None` for an empty tree.
1392 pub(crate) fn intent_anchor(&self) -> Option<WidgetId> {
1393 self.content_root
1394 .filter(|&id| self.arena.get(id).is_some())
1395 .or_else(|| self.arena.roots().first().copied())
1396 }
1397
1398 fn run_with_event_context_from<F>(
1399 &mut self,
1400 anchor: Option<WidgetId>,
1401 ops: &mut dyn crate::window::WindowOps,
1402 f: F,
1403 ) where
1404 F: FnOnce(&mut crate::widget::EventContext),
1405 {
1406 let mut ctx = self.make_event_context(ops);
1407 f(&mut ctx);
1408 if let Some(anchor_id) = anchor {
1409 self.collect_from_ctx(ctx, anchor_id);
1410 // App callbacks (including close guards) have no enclosing input
1411 // dispatch to drain this queue. Waiting for another key or pointer
1412 // event can leave a vetoed close with no confirmation dialog.
1413 self.drain_pending_intents(ops);
1414 } else {
1415 // Empty tree — nothing to anchor intents on. Drop ctx;
1416 // its only side effects (frame requests, cursor) are
1417 // not meaningful for an empty tree.
1418 drop(ctx);
1419 }
1420 }
1421
1422 /// Enqueue a one-shot action to run with a real
1423 /// [`EventContext`] after the current build,
1424 /// once the tree is mounted under its window. Used via
1425 /// [`BuildContext::run_after_mount`](crate::BuildContext::run_after_mount). Drained by
1426 /// [`Self::run_mount_actions`].
1427 pub(crate) fn queue_mount_action(
1428 &mut self,
1429 action: Box<dyn FnOnce(&mut crate::widget::EventContext)>,
1430 ) {
1431 self.pending_mount_actions.push(action);
1432 }
1433
1434 /// Whether any post-mount actions are waiting to run.
1435 pub fn has_pending_mount_actions(&self) -> bool {
1436 !self.pending_mount_actions.is_empty()
1437 }
1438
1439 /// Drain and run every queued post-mount action with a fresh
1440 /// [`EventContext`] built over `ops`. The app
1441 /// loop calls this each iteration with a real `WindowOps` sink (so
1442 /// `ctx.parent_window_handle()` resolves); headless tests call it with a
1443 /// `NoopWindowOps`. Actions enqueued *by* an action (rare) are left for the
1444 /// next drain rather than run re-entrantly.
1445 pub fn run_mount_actions(&mut self, ops: &mut dyn crate::window::WindowOps) {
1446 if self.pending_mount_actions.is_empty() {
1447 return;
1448 }
1449 let actions = std::mem::take(&mut self.pending_mount_actions);
1450 self.run_with_event_context(ops, move |ctx| {
1451 for action in actions {
1452 action(ctx);
1453 }
1454 });
1455 }
1456
1457 /// Attach the [`WindowState`](crate::window::WindowState) for this
1458 /// tree's hosting window. Called by `WindowManager::create_window`.
1459 pub fn set_window_state(&mut self, state: crate::window::WindowState) {
1460 self.window_state = Some(state);
1461 }
1462
1463 pub fn window_state(&self) -> Option<&crate::window::WindowState> {
1464 self.window_state.as_ref()
1465 }
1466
1467 /// The window's title as its accessible name: `None` without a window
1468 /// state or with a blank title, since a name that is empty is still a
1469 /// name to every adapter.
1470 pub(crate) fn window_title_for_accessibility(&self) -> Option<String> {
1471 let title = self.window_state.as_ref()?.title().get();
1472 (!title.trim().is_empty()).then_some(title)
1473 }
1474
1475 /// Clone the shared "frame requested" flag. Widgets stash this
1476 /// in their state and call `.set(true)` from inside frame-tick
1477 /// closures to chain-request another frame without needing
1478 /// mutable access to the tree. See `RichTextEditor` for the
1479 /// canonical use (caret blink, drag-select auto-scroll).
1480 pub fn frame_request_handle(&self) -> std::rc::Rc<std::cell::Cell<bool>> {
1481 self.frame_tick_requested.clone()
1482 }
1483
1484 /// Clone the shared wake-at deadline cell. Widgets stash this in
1485 /// their state and call `request_wake_at` from frame-tick effects
1486 /// to schedule a one-shot deadline without keeping the event loop
1487 /// in `Poll` mode. On the next `layout()` at or past the deadline,
1488 /// the tree auto-arms `frame_tick_requested` so the effect runs on
1489 /// the wake-up pass. Canonical use: the rich text editor's caret
1490 /// blink schedules a 500 ms wake instead of pumping every frame.
1491 pub fn wake_at_handle(&self) -> std::rc::Rc<std::cell::Cell<Option<std::time::Instant>>> {
1492 self.pending_wake_at.clone()
1493 }
1494
1495 /// Schedule a one-shot frame wake at `at`. Merges with any existing
1496 /// deadline — keeps the earlier instant so the most urgent wake
1497 /// wins.
1498 pub fn request_wake_at(&self, at: std::time::Instant) {
1499 let current = self.pending_wake_at.get();
1500 let merged = match current {
1501 Some(existing) if existing <= at => existing,
1502 _ => at,
1503 };
1504 self.pending_wake_at.set(Some(merged));
1505 }
1506
1507 /// The per-frame delta-seconds signal. Observers fire **only on frames
1508 /// the tree was asked to pump** via [`request_frame`](Self::request_frame);
1509 /// merely observing the signal does not keep the event loop awake.
1510 /// See `BuildContext::frame_tick` for widget-side access and
1511 /// `BuildContext::request_frame` for the opt-in request side.
1512 pub fn frame_tick(&self) -> crate::signal::Signal<f32> {
1513 self.frame_tick.clone()
1514 }
1515
1516 /// Ask the tree to pump exactly one more frame. `needs_redraw()`
1517 /// returns true until the request is consumed by the next
1518 /// `layout()` call, which fires the per-frame tick signal and
1519 /// clears the flag. Observers that still need more frames (drag
1520 /// auto-scroll, caret blink, pending document events) must call
1521 /// `request_frame()` again from inside their tick closure.
1522 ///
1523 /// Takes `&self` on purpose: widget handlers and per-frame effects
1524 /// receive a shared reference to the tree via `EventContext` /
1525 /// `BuildContext`, and the request flag is a `Cell` specifically so
1526 /// those shared paths can toggle it without ceremony.
1527 pub fn request_frame(&self) {
1528 self.frame_tick_requested.set(true);
1529 }
1530
1531 /// Request that the AccessKit tree be re-walked on the next
1532 /// [`sync_accessibility`](Self::sync_accessibility). Takes `&self` (the
1533 /// flag is a `Cell`) so handlers and `build()` closures reaching the tree
1534 /// through a shared reference can request a re-walk without `&mut` access.
1535 /// The drain at the top of `sync_accessibility` flips `a11y_dirty`.
1536 pub fn request_accessibility_update(&self) {
1537 self.a11y_update_requested.set(true);
1538 }
1539
1540 /// Speak `message` to the screen reader, politely.
1541 ///
1542 /// For anything the user needs told that is not the name of a widget: a
1543 /// completed action, a changed count, the result of an undo. The message is
1544 /// delivered on the next two accessibility syncs, which this schedules.
1545 ///
1546 /// Prefer `EventContext::announce` inside a handler and
1547 /// `BuildContext::announce` inside a build; this is the tree-level entry
1548 /// point both of those reach.
1549 ///
1550 /// Takes `impl Into<String>`, so `tr!(…)` works directly. See
1551 /// [`crate::announcer`] for why it is a `String` and not a
1552 /// `LocalizedString`, and for why an announcement beside a `Toast` says
1553 /// everything twice.
1554 pub fn announce(&mut self, message: impl Into<String>) {
1555 self.announce_with(message, crate::announcer::Politeness::Polite);
1556 }
1557
1558 /// Speak `message` to the screen reader at the given urgency.
1559 ///
1560 /// [`Politeness::Assertive`](crate::announcer::Politeness::Assertive)
1561 /// interrupts whatever is being spoken; reserve it for something the user
1562 /// must not miss and cannot recover by re-reading the screen.
1563 pub fn announce_with(
1564 &mut self,
1565 message: impl Into<String>,
1566 politeness: crate::announcer::Politeness,
1567 ) {
1568 match politeness {
1569 crate::announcer::Politeness::Polite => self.announcer_polite.push(message.into()),
1570 crate::announcer::Politeness::Assertive => {
1571 self.announcer_assertive.push(message.into())
1572 }
1573 }
1574 // A message is put in the tree by a sync, and a sync only happens on
1575 // a frame. Without both of these a message queued from a handler that
1576 // changed nothing visible would sit unspoken until something else
1577 // happened to redraw.
1578 self.request_accessibility_update();
1579 self.request_frame();
1580 }
1581
1582 /// Clone the shared "accessibility re-walk requested" flag, for the same
1583 /// stash-and-toggle pattern as [`frame_request_handle`](Self::frame_request_handle).
1584 pub fn a11y_request_handle(&self) -> std::rc::Rc<std::cell::Cell<bool>> {
1585 self.a11y_update_requested.clone()
1586 }
1587
1588 /// Whether the next `layout()` will fire the per-frame tick: a frame
1589 /// was requested, or a render painted a frame-tick subscriber's owner
1590 /// and re-armed the chain. Exposed for tests and for the event-loop
1591 /// driver that decides when to schedule the next wake-up; *when* that
1592 /// frame is due is [`frame_tick_deadline`](Self::frame_tick_deadline).
1593 pub fn frame_requested(&self) -> bool {
1594 self.frame_tick_requested.get() || self.frame_tick_armed_by_subscribers
1595 }
1596
1597 /// Consume both reasons for a frame tick at once, returning whether
1598 /// there was one. Every path that fires `frame_tick` goes through here,
1599 /// so neither flag can outlive the tick it asked for.
1600 pub(crate) fn take_frame_tick_request(&mut self) -> bool {
1601 let requested = self.frame_tick_requested.replace(false);
1602 let armed = std::mem::take(&mut self.frame_tick_armed_by_subscribers);
1603 requested || armed
1604 }
1605
1606 /// The next wake-up deadline for the per-frame-effect path, or
1607 /// `None` when no per-frame effect is armed.
1608 ///
1609 /// This is the **60 Hz cap** for continuous per-frame animations
1610 /// (`Pulse`, caret blink, drag auto-scroll, `--cycle` drivers). The
1611 /// per-frame-effect path used to force `ControlFlow::Poll`, which
1612 /// free-runs at the display's refresh rate — so on a 300 Hz panel a
1613 /// single `Pulse`/`Cycle` rendered at 300 fps (measured ~45 % CPU) for
1614 /// motion that looks identical at 60 fps. Routing it through a fixed
1615 /// 16.667 ms deadline (folded into
1616 /// [`next_timer_deadline`](Self::next_timer_deadline)) makes it pace at
1617 /// 60 Hz regardless of refresh rate, matching the signal-tween
1618 /// [`AnimationScheduler`](crate::animation::AnimationScheduler) and
1619 /// shader-quad [`AnimatedQuadRegistry`](crate::animated_quad::AnimatedQuadRegistry),
1620 /// which already share the same interval.
1621 ///
1622 /// A **throttled** subscriber (registered via
1623 /// [`FrameTickScheduler::subscribe_throttled`](crate::frame_tick_scheduler::FrameTickScheduler::subscribe_throttled),
1624 /// e.g. `Cycle`, whose visible child only changes once per period)
1625 /// stretches the wait for **its own** tick to its interval: the loop
1626 /// then sleeps to the period instead of rendering identical 60 fps
1627 /// frames in between. The interval for the subscribers' re-arm is the
1628 /// **minimum across all currently-visible subscribers**, so a `Cycle`
1629 /// next to a `Pulse` still ticks at 60 Hz while a lone `Cycle` sleeps to
1630 /// its period.
1631 ///
1632 /// A frame asked for through [`request_frame`](Self::request_frame) or
1633 /// [`frame_request_handle`](Self::frame_request_handle) is due at 60 Hz
1634 /// whatever subscribers are visible, and the earlier of the two
1635 /// deadlines wins. The announcer, a caret, a drag auto-scroll and the
1636 /// bootstrap frame of a new subscription all ask that way, and none of
1637 /// them can be made to wait on somebody else's clock: an announcement
1638 /// queued behind a once-a-minute clock was spoken a minute late, or at
1639 /// the user's next key press.
1640 ///
1641 /// Paces from `last_frame_time` so the cadence is drift-free; before
1642 /// the first render it fires on the next loop turn.
1643 pub fn frame_tick_deadline(&self) -> Option<std::time::Instant> {
1644 const DEFAULT_INTERVAL: std::time::Duration = std::time::Duration::from_micros(16_667);
1645 // Each reason for a frame brings its own pace. A subscriber re-arm
1646 // with no visible subscriber left keeps the 60 Hz fallback, so the
1647 // one frame that finds nothing to re-arm still runs and the flag
1648 // does not linger.
1649 let requested = self.frame_tick_requested.get().then_some(DEFAULT_INTERVAL);
1650 let subscribed = self.frame_tick_armed_by_subscribers.then(|| {
1651 self.frame_tick_scheduler
1652 .min_visible_interval(&self.arena, self.paint_epoch)
1653 .unwrap_or(DEFAULT_INTERVAL)
1654 });
1655 let interval = requested.into_iter().chain(subscribed).min()?;
1656 Some(match self.last_frame_time {
1657 Some(prev) => prev + interval,
1658 None => std::time::Instant::now(),
1659 })
1660 }
1661
1662 /// Subscribe `owner` to the per-frame-effect scheduler. The
1663 /// returned [`FrameTickSubscription`](crate::frame_tick_scheduler::FrameTickSubscription)
1664 /// is an RAII guard — drop it (typically by replacing the field on
1665 /// the owning widget on rebuild, or letting the widget's `Drop`
1666 /// run) to remove the subscription. While the guard is alive, the
1667 /// tree will keep re-arming the frame tick after every render
1668 /// in which `owner` was painted, and stop on frames where it
1669 /// wasn't — so a subscribed widget hidden inside a non-selected
1670 /// `Switcher` branch contributes zero idle frames.
1671 ///
1672 /// Apps should not call this directly — use
1673 /// [`BuildContext::subscribe_frame_tick`](crate::build_context::BuildContext::subscribe_frame_tick)
1674 /// from inside `Widget::build`.
1675 pub fn subscribe_frame_tick(
1676 &self,
1677 owner: WidgetId,
1678 ) -> crate::frame_tick_scheduler::FrameTickSubscription {
1679 self.frame_tick_scheduler.subscribe(owner)
1680 }
1681
1682 /// Like [`subscribe_frame_tick`](Self::subscribe_frame_tick), but the
1683 /// owner only needs to wake **at most once per `interval`** while
1684 /// visible. Same visibility gate; between wakes the event loop sleeps
1685 /// to the interval deadline instead of rendering identical 60 fps
1686 /// frames. Use for effects whose visible output changes far less often
1687 /// than 60 Hz — e.g. `Cycle`'s once-per-period index advance.
1688 ///
1689 /// Apps should not call this directly — use
1690 /// [`BuildContext::subscribe_frame_tick_throttled`](crate::build_context::BuildContext::subscribe_frame_tick_throttled)
1691 /// from inside `Widget::build`.
1692 pub fn subscribe_frame_tick_throttled(
1693 &self,
1694 owner: WidgetId,
1695 interval: std::time::Duration,
1696 ) -> crate::frame_tick_scheduler::FrameTickSubscription {
1697 self.frame_tick_scheduler
1698 .subscribe_throttled(owner, interval)
1699 }
1700
1701 /// Advance the frame tick signal when (and only when) a frame was
1702 /// requested. Called by `layout()` before the scheduler tick so the
1703 /// per-frame observers fire on the same frame they asked for.
1704 pub(crate) fn advance_frame_tick(&mut self, now: std::time::Instant) {
1705 if !self.take_frame_tick_request() {
1706 self.last_frame_time = Some(now);
1707 return;
1708 }
1709 let delta = match self.last_frame_time {
1710 Some(prev) => {
1711 let d = now.saturating_duration_since(prev).as_secs_f32();
1712 // Clamp absurd deltas (pause/breakpoint) so observers never see a spike.
1713 d.clamp(0.0, 0.1)
1714 }
1715 None => 0.0,
1716 };
1717 self.last_frame_time = Some(now);
1718 self.frame_tick.set(delta);
1719 }
1720
1721 /// Replace the per-tree app context. Called by `teksilo-app` when
1722 /// constructing a window so the widget tree can reach the registered
1723 /// event source adapter and post subscription events through the
1724 /// event-loop proxy.
1725 pub fn set_app_context(&mut self, app_context: Rc<crate::event_source::TreeAppContext>) {
1726 self.app_context = app_context;
1727 }
1728
1729 /// Get the per-tree app context. Used by `BuildContext::subscribe_event`
1730 /// and by the event-loop handler when dispatching incoming
1731 /// `AppEvent::SubscriptionEvent`.
1732 pub fn app_context(&self) -> &Rc<crate::event_source::TreeAppContext> {
1733 &self.app_context
1734 }
1735
1736 /// Switch the tree-level locale at runtime.
1737 ///
1738 /// Updates `locale_signal` (a reactive `Signal<Option<String>>`) and marks
1739 /// all widgets dirty for relayout and repaint. Widgets are **not** rebuilt:
1740 /// per-string reactivity flows through `LocalizedString::to_signal()` which
1741 /// observes the teksilo-i18n manager, and anything else that depends on the
1742 /// tree-level locale can bind to `locale_signal()`.
1743 pub fn set_locale(&mut self, locale: String) {
1744 if self.locale.as_deref() == Some(locale.as_str()) {
1745 return;
1746 }
1747 let new = Some(locale);
1748 self.locale = new.clone();
1749 self.locale_signal.set(new);
1750 self.arena.mark_all_dirty();
1751 }
1752
1753 /// Currently active locale identifier, if any.
1754 pub fn locale(&self) -> Option<&str> {
1755 self.locale.as_deref()
1756 }
1757
1758 /// Reactive handle on the current locale. Mirrors `locale()` but updates
1759 /// observers when `set_locale` is called.
1760 pub fn locale_signal(&self) -> &crate::signal::Signal<Option<String>> {
1761 &self.locale_signal
1762 }
1763
1764 fn pointer_inside_overlay_region(
1765 &self,
1766 overlay_id: crate::overlay::OverlayId,
1767 position: Point,
1768 ) -> bool {
1769 let Some(overlay) = self
1770 .overlay_manager
1771 .stack
1772 .iter()
1773 .find(|overlay| overlay.id == overlay_id)
1774 else {
1775 return false;
1776 };
1777
1778 if self.arena.is_active(overlay.anchor)
1779 && self.arena.bounds(overlay.anchor).contains(position)
1780 {
1781 return true;
1782 }
1783
1784 self.overlay_manager.stack.iter().any(|candidate| {
1785 (candidate.id == overlay_id
1786 || self
1787 .overlay_manager
1788 .is_descendant_of(candidate.id, overlay_id))
1789 && candidate.bounds.contains(position)
1790 })
1791 }
1792
1793 /// Whether the overlay's safe region is armed and still within
1794 /// [`SAFE_REGION_BUDGET`](crate::overlay::SAFE_REGION_BUDGET).
1795 ///
1796 /// Both clocks are consulted and either expiring is enough: the real
1797 /// one drives a running app, the simulated one drives headless tests
1798 /// (`advance_time`), and an overlay armed in one and aged in the
1799 /// other must still expire.
1800 fn safe_region_unexpired(
1801 &self,
1802 overlay_id: crate::overlay::OverlayId,
1803 real_now: std::time::Instant,
1804 sim_now: std::time::Instant,
1805 ) -> bool {
1806 let Some(overlay) = self
1807 .overlay_manager
1808 .stack
1809 .iter()
1810 .find(|overlay| overlay.id == overlay_id)
1811 else {
1812 return false;
1813 };
1814 if overlay.safe_apex.is_none() {
1815 return false;
1816 }
1817 let budget = crate::overlay::SAFE_REGION_BUDGET;
1818 let real_ok = overlay
1819 .safe_apex_started_real
1820 .is_none_or(|started| real_now.saturating_duration_since(started) < budget);
1821 let sim_ok = overlay
1822 .safe_apex_started_sim
1823 .is_none_or(|started| sim_now.saturating_duration_since(started) < budget);
1824 real_ok && sim_ok
1825 }
1826
1827 /// The armed safe-triangle apex of the overlay rooted at
1828 /// `content_id`, or `None` when no region is armed or its budget is
1829 /// spent.
1830 ///
1831 /// This is the form the per-dispatch `EventContext` snapshot carries,
1832 /// because a widget asking "is a traversal toward that submenu still
1833 /// live?" must get the same answer the dismissal path acts on — an
1834 /// unfiltered apex outlives the region by up to a frame and makes a
1835 /// sibling row stand aside for a submenu the framework has already
1836 /// stopped protecting.
1837 fn unexpired_safe_apex_for_content(
1838 &self,
1839 content_id: crate::widget_id::WidgetId,
1840 ) -> Option<teksilo_canvas::Point> {
1841 // Cheap short-circuit first: nothing is armed in the common case,
1842 // and this runs once per node per pointer dispatch.
1843 let apex = self.overlay_manager.safe_apex_for_content(content_id)?;
1844 let id = self.overlay_manager.find_by_content(content_id)?;
1845 self.safe_region_unexpired(id, std::time::Instant::now(), self.sim_clock)
1846 .then_some(apex)
1847 }
1848
1849 fn update_pointer_leave_overlays(
1850 &mut self,
1851 position: Point,
1852 ops: &mut dyn crate::window::WindowOps,
1853 ) {
1854 let overlay_ids: Vec<crate::overlay::OverlayId> = self
1855 .overlay_manager
1856 .stack
1857 .iter()
1858 .filter(|overlay| {
1859 matches!(
1860 overlay.dismiss,
1861 crate::overlay::DismissBehavior::PointerLeave { .. }
1862 )
1863 })
1864 .map(|overlay| overlay.id)
1865 .collect();
1866
1867 let real_now = std::time::Instant::now();
1868 let sim_now = self.sim_clock;
1869
1870 for overlay_id in overlay_ids {
1871 let inside = self.pointer_inside_overlay_region(overlay_id, position);
1872 // A pointer travelling the safe triangle toward this overlay
1873 // is still "inside" as far as dismissal is concerned — that
1874 // is the whole point of the triangle. Without this the
1875 // grace period runs for the entire diagonal and closes the
1876 // submenu mid-flight, no matter what the hover handlers do.
1877 // See `overlay::safe_triangle`.
1878 let armed = self.safe_region_unexpired(overlay_id, real_now, sim_now);
1879 let travelling = !inside
1880 && armed
1881 && self
1882 .overlay_manager
1883 .point_in_safe_region(overlay_id, position);
1884 // Arrived, or returned to the trigger row: the traversal is
1885 // over and the ordinary rules apply again.
1886 //
1887 // Straying out of the cone deliberately does NOT disarm. The
1888 // cone is a needle at its apex — the first sample after the
1889 // pointer leaves the trigger row is a pixel or two away, so
1890 // whether it lands inside is one quantized step's direction
1891 // rather than the user's intent. Disarming there made that
1892 // sample final, because a region is only ever armed as the
1893 // pointer leaves the row and the pointer has already left:
1894 // nothing could re-arm it. Keeping it armed makes the cone a
1895 // per-sample hold that the grace below re-evaluates instead,
1896 // so a wobble mid-diagonal costs nothing while a real change
1897 // of mind still closes the submenu one close-delay later. The
1898 // budget is what retires a region for good; the frame pass
1899 // spends it even for a pointer that stopped moving entirely.
1900 if armed && inside {
1901 self.overlay_manager.clear_safe_region(overlay_id);
1902 }
1903 if let Some(overlay) = self
1904 .overlay_manager
1905 .stack
1906 .iter_mut()
1907 .find(|overlay| overlay.id == overlay_id)
1908 {
1909 if inside || travelling {
1910 overlay.pointer_leave_started_real = None;
1911 overlay.pointer_leave_started_sim = None;
1912 } else if overlay.pointer_leave_started_real.is_none() {
1913 overlay.pointer_leave_started_real = Some(real_now);
1914 overlay.pointer_leave_started_sim = Some(sim_now);
1915 self.arena.mark_needs_paint(overlay.anchor);
1916 }
1917 }
1918 }
1919
1920 self.process_pointer_leave_overlays_real(&mut *ops);
1921 }
1922
1923 fn process_pointer_leave_overlays(&mut self) {
1924 let sim_now = self.sim_clock;
1925 let mut noop = crate::window::NoopWindowOps;
1926 self.process_pointer_leave_overlays_impl(
1927 |overlay| {
1928 overlay
1929 .pointer_leave_started_sim
1930 .map(|started| sim_now.saturating_duration_since(started))
1931 },
1932 &mut noop,
1933 );
1934 }
1935
1936 fn process_pointer_leave_overlays_real(&mut self, ops: &mut dyn crate::window::WindowOps) {
1937 let real_now = std::time::Instant::now();
1938 self.process_pointer_leave_overlays_impl(
1939 |overlay| {
1940 overlay
1941 .pointer_leave_started_real
1942 .map(|started| real_now.saturating_duration_since(started))
1943 },
1944 &mut *ops,
1945 );
1946 }
1947
1948 fn process_auto_dismiss_overlays(&mut self) {
1949 let sim_now = self.sim_clock;
1950 let mut noop = crate::window::NoopWindowOps;
1951 self.process_auto_dismiss_overlays_impl(
1952 |overlay| {
1953 overlay
1954 .auto_dismiss_after
1955 .map(|_| sim_now.saturating_duration_since(overlay.shown_at_sim))
1956 },
1957 &mut noop,
1958 );
1959 }
1960
1961 fn process_auto_dismiss_overlays_real(&mut self, ops: &mut dyn crate::window::WindowOps) {
1962 let real_now = std::time::Instant::now();
1963 self.process_auto_dismiss_overlays_impl(
1964 |overlay| {
1965 overlay
1966 .auto_dismiss_after
1967 .map(|_| real_now.saturating_duration_since(overlay.shown_at_real))
1968 },
1969 &mut *ops,
1970 );
1971 }
1972
1973 /// Drain overlays whose fade-out tween has completed (set up by
1974 /// `OverlayRequest::with_fade`). Parks the content as the normal
1975 /// dismiss path does, and hands focus back only when that leaves it
1976 /// nowhere ([`restore_focus_left_behind`](Self::restore_focus_left_behind)):
1977 /// the dismissal that started the fade may have meant to leave focus
1978 /// alone, and the user may have moved it on since; called once per layout pass
1979 /// after `process_auto_dismiss_overlays_real` so an overlay that
1980 /// hits its auto-dismiss deadline kicks off its fade-out tween
1981 /// in the same pass.
1982 pub(crate) fn process_overlay_fade_dismissals_real(
1983 &mut self,
1984 ops: &mut dyn crate::window::WindowOps,
1985 ) {
1986 let now = std::time::Instant::now();
1987 let mark = self.dismissal_mark();
1988 let pending = self.overlay_manager.process_pending_fade_dismissals(now);
1989 for (_id, dismissed, focus_restore) in pending {
1990 self.dormant_dismissed_content(&dismissed, &mut *ops);
1991 self.restore_focus_left_behind(focus_restore, mark, &mut *ops);
1992 }
1993 }
1994
1995 /// Sim-clock variant for headless tests. Same shape as
1996 /// [`process_overlay_fade_dismissals_real`](Self::process_overlay_fade_dismissals_real)
1997 /// but reads `dismissing_started_sim`.
1998 pub(crate) fn process_overlay_fade_dismissals_sim(&mut self) {
1999 let mut noop = crate::window::NoopWindowOps;
2000 let mark = self.dismissal_mark();
2001 let pending = self
2002 .overlay_manager
2003 .process_pending_fade_dismissals_sim(self.sim_clock);
2004 for (_id, dismissed, focus_restore) in pending {
2005 self.dormant_dismissed_content(&dismissed, &mut noop);
2006 self.restore_focus_left_behind(focus_restore, mark, &mut noop);
2007 }
2008 }
2009
2010 /// Hand focus to `restore` after an overlay has gone of its own accord
2011 /// (its auto-dismiss timer ran out, or its fade-out ended), but only when
2012 /// focus is left nowhere: the overlay held it and
2013 /// [`dormant_dismissed_content`](Self::dormant_dismissed_content) has just
2014 /// taken it away with the content, or nothing held it. Focus the user has
2015 /// moved elsewhere since the overlay opened stays where they put it. A tip
2016 /// that focus summoned holds its anchor as `restore`, and restoring that
2017 /// whatever held focus sent a reader who had Tabbed on back to the control
2018 /// they had just left. When `restore` cannot take focus, the fallback
2019 /// chain of `return_focus_after_dismissal` runs, under the same rule.
2020 fn restore_focus_left_behind(
2021 &mut self,
2022 restore: Option<WidgetId>,
2023 mark: focus_fallback_impl::DismissMark,
2024 ops: &mut dyn crate::window::WindowOps,
2025 ) {
2026 if self.focus_left_nowhere() {
2027 self.return_focus_after_dismissal(restore, mark, ops);
2028 }
2029 }
2030
2031 fn process_auto_dismiss_overlays_impl(
2032 &mut self,
2033 elapsed_fn: impl Fn(&crate::overlay::ActiveOverlay) -> Option<std::time::Duration>,
2034 ops: &mut dyn crate::window::WindowOps,
2035 ) {
2036 let mut to_dismiss = Vec::new();
2037
2038 for overlay in self.overlay_manager.stack.iter().rev() {
2039 let Some(delay) = overlay.auto_dismiss_after else {
2040 continue;
2041 };
2042
2043 if to_dismiss
2044 .iter()
2045 .any(|ancestor| self.overlay_manager.is_descendant_of(overlay.id, *ancestor))
2046 {
2047 continue;
2048 }
2049
2050 if let Some(elapsed) = elapsed_fn(overlay)
2051 && elapsed >= delay
2052 {
2053 to_dismiss.push(overlay.id);
2054 }
2055 }
2056
2057 for overlay_id in to_dismiss {
2058 let mark = self.dismissal_mark();
2059 let (dismissed, focus_restore) =
2060 self.overlay_manager.dismiss_with_focus_restore(overlay_id);
2061 self.dormant_dismissed_content(&dismissed, &mut *ops);
2062 self.restore_focus_left_behind(focus_restore, mark, &mut *ops);
2063 }
2064 }
2065
2066 fn process_pointer_leave_overlays_impl(
2067 &mut self,
2068 elapsed_fn: impl Fn(&crate::overlay::ActiveOverlay) -> Option<std::time::Duration>,
2069 ops: &mut dyn crate::window::WindowOps,
2070 ) {
2071 // Retire safe regions whose budget is spent. `update_pointer_leave_overlays`
2072 // does this too, but only when the pointer moves — and a pointer parked
2073 // inside the cone generates no moves at all, so without this pass the
2074 // submenu would stay open indefinitely. Expiring here also starts the
2075 // ordinary grace, so the overlay closes `delay` later exactly as if the
2076 // triangle had never been armed.
2077 let real_now = std::time::Instant::now();
2078 let sim_now = self.sim_clock;
2079 let expired: Vec<crate::overlay::OverlayId> = self
2080 .overlay_manager
2081 .stack
2082 .iter()
2083 .filter(|overlay| overlay.safe_apex.is_some())
2084 .map(|overlay| overlay.id)
2085 .filter(|id| !self.safe_region_unexpired(*id, real_now, sim_now))
2086 .collect();
2087 let budget = crate::overlay::SAFE_REGION_BUDGET;
2088 for id in expired {
2089 if let Some(overlay) = self
2090 .overlay_manager
2091 .stack
2092 .iter_mut()
2093 .find(|overlay| overlay.id == id)
2094 && overlay.pointer_leave_started_real.is_none()
2095 {
2096 // Backdate to the instant the budget ran out: the
2097 // pointer stopped counting as "inside" then, not when a
2098 // frame got around to noticing. Otherwise the grace
2099 // silently restarts from zero and the total wait
2100 // depends on the frame rate.
2101 let backdate = |started: Option<std::time::Instant>, now: std::time::Instant| {
2102 started
2103 .and_then(|s| s.checked_add(budget))
2104 .map(|deadline| deadline.min(now))
2105 .unwrap_or(now)
2106 };
2107 overlay.pointer_leave_started_real =
2108 Some(backdate(overlay.safe_apex_started_real, real_now));
2109 overlay.pointer_leave_started_sim =
2110 Some(backdate(overlay.safe_apex_started_sim, sim_now));
2111 }
2112 self.overlay_manager.clear_safe_region(id);
2113 }
2114
2115 let mut to_dismiss = Vec::new();
2116
2117 for overlay in self.overlay_manager.stack.iter().rev() {
2118 let crate::overlay::DismissBehavior::PointerLeave { delay } = overlay.dismiss else {
2119 continue;
2120 };
2121
2122 if to_dismiss
2123 .iter()
2124 .any(|ancestor| self.overlay_manager.is_descendant_of(overlay.id, *ancestor))
2125 {
2126 continue;
2127 }
2128
2129 if let Some(elapsed) = elapsed_fn(overlay)
2130 && elapsed >= delay
2131 {
2132 to_dismiss.push(overlay.id);
2133 }
2134 }
2135
2136 for overlay_id in to_dismiss {
2137 let mark = self.dismissal_mark();
2138 let (dismissed, focus_restore) =
2139 self.overlay_manager.dismiss_with_focus_restore(overlay_id);
2140 self.dormant_dismissed_content(&dismissed, &mut *ops);
2141 self.return_focus_after_dismissal(focus_restore, mark, &mut *ops);
2142 }
2143 }
2144
2145 pub fn with_theme(mut self, theme: Theme) -> Self {
2146 // Update both the cached `Theme` AND the reactive
2147 // `theme_signal` — widgets that observe the signal (e.g.
2148 // `TextInputField` resetting the rich-text engine's default
2149 // text colour) would otherwise see the constructor's
2150 // `presets::intui::light()` initial value forever, even when
2151 // `TeksiloAppBuilder.theme(crate::presets::intui::dark())` was used.
2152 // `set_theme` already does this; `with_theme` was the
2153 // builder-time analogue that forgot to keep them aligned.
2154 self.theme = theme.clone();
2155 self.theme_signal.set(theme);
2156 self.recompute_effective_theme();
2157 self
2158 }
2159
2160 pub fn with_text_backend(
2161 mut self,
2162 backend: Rc<RefCell<dyn teksilo_canvas::TextBackend>>,
2163 ) -> Self {
2164 self.text_backend = Some(backend);
2165 self
2166 }
2167
2168 /// Attach a platform host for custom window chrome. Set by the
2169 /// `WindowManager` when the application opts in via
2170 /// `WindowConfig::custom_chrome(true)`. Widgets like `TitleBar` retrieve
2171 /// it from inside the root-builder closure via [`Self::title_bar_host`].
2172 pub fn with_title_bar_host(mut self, host: Rc<dyn crate::PlatformTitleBarHost>) -> Self {
2173 self.title_bar_host = Some(host);
2174 self
2175 }
2176
2177 pub fn set_title_bar_host(&mut self, host: Rc<dyn crate::PlatformTitleBarHost>) {
2178 self.title_bar_host = Some(host);
2179 }
2180
2181 /// Get the platform title bar host, if one was attached. Returns `None`
2182 /// when the application did not opt into custom chrome, or when the
2183 /// platform does not support it (X11 without an EWMH-capable window
2184 /// manager, or a headless build).
2185 pub fn title_bar_host(&self) -> Option<Rc<dyn crate::PlatformTitleBarHost>> {
2186 self.title_bar_host.clone()
2187 }
2188
2189 pub fn theme(&self) -> &Theme {
2190 &self.theme
2191 }
2192
2193 /// Reactive handle on the current theme. Updates fire when `set_theme`
2194 /// is called; widgets that want theme-derived values to stay live should
2195 /// build derived signals via `theme_signal.map(...)` or combine with
2196 /// other inputs using `.zip(...)`.
2197 pub fn theme_signal(&self) -> &crate::signal::Signal<Theme> {
2198 &self.theme_signal
2199 }
2200
2201 /// Whether any widget needs layout or paint (i.e., a redraw would be useful).
2202 ///
2203 /// Uses `has_running` rather than `has_active` so that animations
2204 /// parked by the window-inactive gate stop forcing the event loop
2205 /// into `ControlFlow::WaitUntil`. Without this, an unfocused window
2206 /// would still wake at the animation frame interval and the
2207 /// pause would save nothing. Both the signal scheduler AND the
2208 /// shader-driven animated-quad registry are consulted — a
2209 /// ProgressBar::indeterminate whose widget has no pending paint
2210 /// dirt still needs the loop to keep waking at the animation
2211 /// frame interval so its phase advances.
2212 pub fn needs_redraw(&self) -> bool {
2213 self.arena.any_needs_layout()
2214 || self.arena.any_needs_paint()
2215 || self.animation_scheduler.has_running()
2216 || self.animated_quads.has_running()
2217 || self.frame_requested()
2218 }
2219
2220 /// Whether a tree that is never painted has a logic frame to run now
2221 /// (`now` on the real clock): reactive work to reconcile, a node to lay
2222 /// out, an idle callback, or a [timer](Self::next_unpainted_deadline)
2223 /// due. Unlike [`needs_render`](Self::needs_render), which such a tree
2224 /// always reports, it turns false once a frame has run.
2225 pub fn needs_logic_frame(&self, now: std::time::Instant) -> bool {
2226 self.needs_reconcile()
2227 || self.arena.any_needs_layout()
2228 || self.has_idle_work()
2229 || self
2230 .next_unpainted_deadline()
2231 .is_some_and(|deadline| deadline <= now)
2232 }
2233
2234 /// Whether a handler asked for something the application layer carries
2235 /// out after the dispatch: a locale, a theme, following the system
2236 /// theme, a text scale, a close, a modal to present or dismiss, or a
2237 /// mount action to run. A tree whose handlers run outside a window event
2238 /// tells the event loop this way that a drain is owed.
2239 pub fn has_pending_app_requests(&self) -> bool {
2240 self.has_pending_dispatch_requests() || !self.pending_mount_actions.is_empty()
2241 }
2242
2243 /// [`has_pending_app_requests`](Self::has_pending_app_requests) less the
2244 /// mount actions, which a window blocked by a modal keeps queued on
2245 /// purpose until the modal closes.
2246 pub fn has_pending_dispatch_requests(&self) -> bool {
2247 self.pending_locale_request.is_some()
2248 || self.pending_theme_request.is_some()
2249 || self.pending_follow_system_request
2250 || self.pending_text_scale_request.is_some()
2251 || self.close_window_requested
2252 || self.force_close_requested
2253 || !self.pending_modal_requests.is_empty()
2254 || self.pending_modal_dismissal
2255 }
2256
2257 /// Whether a render pass is needed (any widget needs layout or paint).
2258 pub fn needs_render(&self) -> bool {
2259 self.arena.any_needs_layout() || self.arena.any_needs_paint()
2260 }
2261
2262 /// Whether the next layout pass changes which widgets exist, which are
2263 /// active or which one has focus, so an event dispatched before it would
2264 /// reach the wrong widget:
2265 ///
2266 /// - a focus request waits for a dormant target to wake (see
2267 /// [`focus`](Self::focus)): until a pass runs, keys go to the widget
2268 /// focused before it;
2269 /// - an active widget was marked for a rebuild since the last pass: until
2270 /// then its old children take the events;
2271 /// - a rebuild the last pass held back for a pointer capture
2272 /// ([`captures_defer_rebuilds`](Self::captures_defer_rebuilds)) can go
2273 /// ahead, the capture being over: the release must not leave the next
2274 /// click on the old children;
2275 /// - a binding flush ([`reconcile`](Self::reconcile)) found a
2276 /// `visible_when` gate that disagrees with its node: a node to park,
2277 /// still active and focusable until then, or one to wake under an
2278 /// active parent;
2279 /// - the focused control has become disabled, unless the last pass
2280 /// found nowhere to send focus and no enabled state has changed since:
2281 /// until a pass hands focus on, a key reaches the disabled control,
2282 /// which refuses it.
2283 ///
2284 /// Paint and relayout marks are not in it. Until the pass, the widgets
2285 /// and the focus stay as they are, and hit-testing uses the geometry on
2286 /// screen, which is what the user aimed at. Asking reads a few fields,
2287 /// compares two counters, scans the live pointers for a capture and
2288 /// asks whether the focused widget is enabled (a walk up its ancestors):
2289 /// no arena walk. A layout pass settles every term, or, for a deferred
2290 /// rebuild under a capture and a focus with nowhere to go, records why it
2291 /// could not, so none of them asks for a layout per event.
2292 #[doc(hidden)]
2293 pub fn needs_structural_layout(&self) -> bool {
2294 self.pending_focus_request.is_some()
2295 || self.activation_pending
2296 || self.arena.rebuild_marks() != self.rebuild_marks_laid_out
2297 || (self.rebuild_deferred && !self.captures_defer_rebuilds())
2298 || self.focus_waits_to_leave_a_disabled_control()
2299 }
2300
2301 /// Whether a layout pass leaves a captured widget and its ancestors
2302 /// unrebuilt: some pointer holds a capture and no drag session owns the
2303 /// pointer. Rebuilding the captor would tear down the node the gesture's
2304 /// next move and its release are delivered to; a drag session routes by
2305 /// itself, so it does not need the guard.
2306 pub(crate) fn captures_defer_rebuilds(&self) -> bool {
2307 self.active_drag.is_none()
2308 && self
2309 .pointers
2310 .iter()
2311 .any(|entry| entry.captured_by.is_some())
2312 }
2313
2314 /// Whether focus sits on an active control that has become disabled and
2315 /// a pass could move it on: a pass that found nowhere to send it recorded
2316 /// the widget in `disabled_focus_stays`.
2317 fn focus_waits_to_leave_a_disabled_control(&self) -> bool {
2318 self.focused.is_some_and(|focused| {
2319 self.disabled_focus_stays != Some(focused)
2320 && self.arena.is_active(focused)
2321 && !self.arena.is_enabled(focused)
2322 })
2323 }
2324
2325 /// Whether this tree has reactive work that only [`reconcile`](Self::reconcile)
2326 /// or a `layout()` pass can turn into arena dirt, that is, whether
2327 /// reconciling it right now could change what
2328 /// [`needs_render`](Self::needs_render) reports.
2329 ///
2330 /// Read-only and cheap: `O(unique bound sources)` `u64` comparisons
2331 /// plus one peek per registered animated signal. No arena walk, no
2332 /// rebuilds, no geometry. Asking does not consume the answer, so it
2333 /// can be asked every dispatch.
2334 ///
2335 /// # Why this is exactly the right question, and no broader
2336 ///
2337 /// `teksilo_app::WindowManager::request_redraw_needing_render` exists
2338 /// for ONE case: a handler in window A wrote a `Signal` that window
2339 /// B's widgets also bind, and B — which never saw the event — must be
2340 /// reconciled before anyone can tell it needs repainting. Every OTHER
2341 /// thing `layout_with_ops` drives already has its own scheduling
2342 /// path and does not need this sweep:
2343 ///
2344 /// - tooltip dwell + sticky steps, delayed overlays, auto-dismiss,
2345 /// overlay fades, the animation scheduler, animated quads,
2346 /// gestures, `wake_at` and the 60 Hz frame tick are all timing
2347 /// driven, and every one of them contributes to
2348 /// [`next_timer_deadline`](Self::next_timer_deadline) — which
2349 /// `request_redraw_due` polls to wake precisely the due windows;
2350 /// - drag ticks ask for the frame tick while the drop target has a tick
2351 /// handler, so they too run on a deadline;
2352 /// - a handler that called `request_rebuild` marked the arena
2353 /// directly, so `needs_render()` is already true without any
2354 /// reconcile.
2355 ///
2356 /// So the two terms below are what the sweep uniquely covers:
2357 /// binding-registry staleness (the whole point), and a *pending*
2358 /// `animate_to` — which the scheduler has not started yet, so it
2359 /// contributes no deadline, and which only `process_pending_animations`
2360 /// (inside `reconcile` and `layout`) can promote into one. The second term is
2361 /// belt-and-braces: arming an animation also advances the signal's
2362 /// generation, so a bound animated signal is already covered by the
2363 /// first — but an animated signal registered without being bound
2364 /// would not be, and this makes that impossible to get wrong.
2365 pub fn needs_reconcile(&self) -> bool {
2366 self.binding_registry.any_dirty()
2367 || self
2368 .animated_values
2369 .iter()
2370 .any(AnimatedRegistration::has_pending_animation)
2371 }
2372
2373 /// Register a `Signal<f32>` for animation support. The framework
2374 /// checks registered signals each frame for pending `animate_to`
2375 /// requests. Called automatically by `BuildContext::animated_signal()`
2376 /// — `owner` is `ctx.self_id()` of the widget whose `build()` created
2377 /// the signal. Used by the scheduler to pause/cancel animations when
2378 /// the owning widget is offscreen, dormant, or destroyed.
2379 pub fn register_animated_signal(
2380 &mut self,
2381 signal: &crate::signal::Signal<f32>,
2382 owner: WidgetId,
2383 ) {
2384 self.animated_values
2385 .retain(|registration| registration.is_alive());
2386 if let Some(existing) = self
2387 .animated_values
2388 .iter_mut()
2389 .find(|registration| registration.same_signal(signal))
2390 {
2391 // Signal may have been registered earlier with a placeholder
2392 // owner (e.g. a widget field constructed pre-build and
2393 // re-registered during build()) — prefer the latest owner.
2394 existing.owner = owner;
2395 return;
2396 }
2397 if let Some(weak_signal) = signal.weak_handle() {
2398 self.animated_values.push(AnimatedRegistration {
2399 weak: weak_signal,
2400 owner,
2401 });
2402 }
2403 }
2404
2405 /// Whether any animation is currently running.
2406 pub fn has_active_animations(&self) -> bool {
2407 self.animation_scheduler.has_active()
2408 }
2409
2410 /// Pick up pending `animate_to` requests from registered signals
2411 /// and start them on the animation scheduler.
2412 fn process_pending_animations(&mut self) {
2413 let now = self.animation_clock();
2414 self.process_pending_animations_at(now);
2415 }
2416
2417 /// Pick up pending animations using the given time (for sim clock).
2418 fn process_pending_animations_at(&mut self, now: std::time::Instant) {
2419 let mut pending = Vec::new();
2420 self.animated_values.retain(|registration| {
2421 if let Some(animation) = registration.take_pending_animation() {
2422 pending.push(animation);
2423 true
2424 } else {
2425 registration.is_alive()
2426 }
2427 });
2428
2429 for (signal, req, owner) in pending {
2430 if req.looping {
2431 let start = signal.get();
2432 self.animation_scheduler.animate_looping(
2433 &signal,
2434 owner,
2435 start,
2436 req.target,
2437 req.duration,
2438 req.easing,
2439 req.frame_interval,
2440 req.epsilon,
2441 req.max_duration,
2442 now,
2443 );
2444 } else {
2445 self.animation_scheduler.animate_with_options(
2446 &signal,
2447 owner,
2448 req.target,
2449 req.duration,
2450 req.easing,
2451 req.frame_interval,
2452 req.epsilon,
2453 req.max_duration,
2454 now,
2455 );
2456 }
2457 }
2458 }
2459
2460 /// Mark every node paint-dirty (no relayout, no rebuild) so the next
2461 /// render re-runs their `paint()`. What teksilo-app does on receiving the
2462 /// deprecated [`RepaintWindowRequest`](crate::RepaintWindowRequest); a
2463 /// widget whose content changes off the UI thread attaches a
2464 /// [`RepaintTrigger`](crate::RepaintTrigger) instead, which repaints that
2465 /// widget alone.
2466 pub fn mark_all_needs_paint_only(&mut self) {
2467 self.arena.mark_all_needs_paint_only();
2468 }
2469
2470 /// Mark a widget as needing repaint.
2471 pub fn mark_needs_paint(&mut self, id: WidgetId) {
2472 self.arena.mark_needs_paint(id);
2473 }
2474
2475 /// Invalidate all per-widget paint caches (paint AND post-paint) and
2476 /// the assembled frame cache. Forces every widget to repaint on the
2477 /// next `render()` call. Used by the glyph-atlas eviction recovery:
2478 /// after an eviction, any retained frame may hold quads whose atlas
2479 /// UVs now point at recycled slots.
2480 pub fn invalidate_all_paints(&mut self) {
2481 for id in self.arena.active_ids() {
2482 if let Some(node) = self.arena.get_mut(id) {
2483 node.dirty.needs_paint = true;
2484 node.cached_paint = None;
2485 node.cached_post_paint = None;
2486 }
2487 }
2488 self.cached_frame = None;
2489 }
2490
2491 /// Mark the owning window as active (focused AND not occluded) or
2492 /// inactive. Propagates to the animation scheduler and to the
2493 /// animated-quad registry, which do not pause the same things:
2494 ///
2495 /// - The scheduler pauses only its **looping** animations: they stop
2496 /// ticking and stop waking frames, and resume where they were when the
2497 /// window is active again. A one-shot tween keeps running to its end,
2498 /// and keeps the frame clock awake until it does, so whatever it
2499 /// drives (a `Collapse` opened by an assistive technology, say) does
2500 /// not stop partway. See
2501 /// [`AnimationScheduler::set_window_active`](crate::animation::AnimationScheduler::set_window_active).
2502 /// - The animated-quad registry pauses all of its shader loops: no ticks,
2503 /// no frame wakes and no GPU submits until the window is active again.
2504 ///
2505 /// On an actual state change it also fires `window_active_signal`
2506 /// (so build-time binders and `DimWhenInactive` react) and issues a
2507 /// global paint-only dirty mark, so every widget that reads
2508 /// `PaintContext::window_active` (caret gates, selection bands) repaints
2509 /// once. This is a repaint, not a relayout: geometry never changes when
2510 /// the window's active state flips (the caret keeps its space). Window
2511 /// focus changes are rare and user-driven, so the O(n) mark is cheap and
2512 /// strictly lighter than `set_theme`'s `mark_all_dirty` (layout + paint).
2513 pub fn set_window_active(&mut self, active: bool) {
2514 let mut noop = crate::window::NoopWindowOps;
2515 self.set_window_active_with_ops(active, &mut noop);
2516 }
2517
2518 /// [`set_window_active`](Self::set_window_active) with the caller's
2519 /// app-level [`WindowOps`](crate::window::WindowOps) sink, so the
2520 /// `on_pointer_cancel` handlers a deactivation fires can reach the
2521 /// multi-window API like any other handler.
2522 pub fn set_window_active_with_ops(
2523 &mut self,
2524 active: bool,
2525 ops: &mut dyn crate::window::WindowOps,
2526 ) {
2527 // The scheduler is measured on the tree's animation axis, so its pause
2528 // mark has to be taken there too — a pause stamped on the wall clock
2529 // while time is simulated would rebase every animation by the gap
2530 // between the axes on resume. The shader-driven quad registry has no
2531 // simulated door at all (it is ticked from `render()`), so it keeps the
2532 // wall clock.
2533 self.animation_scheduler
2534 .set_window_active(active, self.animation_clock());
2535 self.animated_quads
2536 .set_window_active(active, std::time::Instant::now());
2537 if self.window_active_signal.get() != active {
2538 self.window_active_signal.set(active);
2539 self.arena.mark_all_needs_paint_only();
2540 // Presses recorded before the window last lost the focus have had
2541 // their releases (the platform makes them up as the focus goes);
2542 // any left over is stale, and must not take a later release.
2543 if active {
2544 self.key_presses.clear();
2545 }
2546 if !active {
2547 // A held pointer first, before any other state is cleared: a
2548 // widget that captured the pointer for a drag (a column-resize
2549 // grip, a splitter divider, a scrollbar thumb, a slider) will
2550 // never see the matching `PointerUp` — the user releases the
2551 // button over the window that took focus, and this window is
2552 // told nothing. Releasing the capture silently, which is what
2553 // this used to do, strands the widget instead: it keeps the
2554 // half of the interaction it owns, with no event left that
2555 // could clear it. The cancel funnel releases the capture *and*
2556 // tells it, so it can let go.
2557 self.cancel_all_pointers(
2558 crate::pointer::CancelReason::WindowDeactivated,
2559 &mut *ops,
2560 );
2561 // The pointer has left for another window; the OS sends no
2562 // leave event we can rely on, so a tooltip shown at the moment
2563 // of the switch would float over the newly-focused window's
2564 // chrome with nothing left to dismiss it. Retire tips and
2565 // cancel pending dwells — but leave *sticky* ones, which the
2566 // user pinned deliberately and expects to find on return.
2567 self.tooltip_window_deactivated();
2568 }
2569 }
2570 }
2571
2572 /// Whether the owning window is currently active (`focused AND not
2573 /// occluded`). The reactive companion is [`Self::window_active_signal`].
2574 pub fn is_window_active(&self) -> bool {
2575 self.window_active_signal.get()
2576 }
2577
2578 /// Reactive handle on window-active state. Fires when the window gains or
2579 /// loses active status. Bind at [`BindingLevel::RepaintOnly`] — an
2580 /// active-state flip never affects geometry. Starts `true`.
2581 ///
2582 /// [`BindingLevel::RepaintOnly`]: crate::binding::BindingLevel::RepaintOnly
2583 pub fn window_active_signal(&self) -> crate::signal::Signal<bool> {
2584 self.window_active_signal.clone()
2585 }
2586
2587 /// Register a new animated quad for the currently-building widget.
2588 /// Called by [`crate::build_context::BuildContext::animated_quad`];
2589 /// returns an opaque handle the widget stashes for its `paint()`
2590 /// call.
2591 pub fn register_animated_quad(
2592 &mut self,
2593 owner: WidgetId,
2594 kind: crate::animated_quad::AnimatedQuadKind,
2595 ) -> crate::animated_quad::AnimatedQuadHandle {
2596 self.animated_quads
2597 .register(owner, kind, std::time::Instant::now())
2598 }
2599
2600 /// Active animated-quad slot count. Test / debug helper.
2601 pub fn animated_quad_count(&self) -> usize {
2602 self.animated_quads.active_count()
2603 }
2604
2605 /// Advance animations by simulated time (for deterministic testing).
2606 ///
2607 /// An **alias** of [`advance_time`](Self::advance_time), not a second door.
2608 /// It was one once, and the two moved disjoint halves of the tree from
2609 /// clocks they each advanced independently: a caller that wanted both had
2610 /// to call both, which advanced simulated time twice, and a caller that
2611 /// wanted one silently froze the other — an animation and the fling it was
2612 /// racing could not be moved to the same instant by any sequence of calls.
2613 /// Kept as a name rather than folded away because it reads correctly at
2614 /// its ~120 call sites, all of which mean "advance the clock".
2615 pub fn tick_animations(&mut self, duration: std::time::Duration) {
2616 self.advance_time(duration);
2617 }
2618
2619 /// Switch the tree-level theme at runtime.
2620 ///
2621 /// Updates `theme_signal` (a reactive `Signal<Theme>`) and marks all widgets
2622 /// dirty for relayout and repaint. Widgets are **not** rebuilt: the
2623 /// `LayoutContext` and `PaintContext` already resolve the current theme on
2624 /// every pass, and any widget that derives state from theme tokens should
2625 /// do so through a `theme_signal()` subscription rather than a build-time
2626 /// capture. Preserves focus, scroll offsets, and other interaction state.
2627 pub fn set_theme(&mut self, theme: Theme) {
2628 self.theme = theme.clone();
2629 self.theme_signal.set(theme);
2630 self.recompute_effective_theme();
2631 self.arena.mark_all_dirty();
2632 // A theme change re-resolves typography, so every label re-shapes —
2633 // inside bounds the layout pass may leave untouched, which means no
2634 // resize is recorded and nothing else would dirty the tree. The
2635 // label's lines, and therefore its text runs, can be a different
2636 // set at the same size.
2637 self.a11y_dirty = true;
2638 }
2639
2640 /// The [`TargetDensity`] the active theme was projected onto.
2641 ///
2642 /// [`TargetDensity`]: teksilo_tokens::TargetDensity
2643 pub fn input_density(&self) -> teksilo_tokens::TargetDensity {
2644 self.theme.input.density
2645 }
2646
2647 /// Project the active theme onto another density and **rebuild** the tree.
2648 ///
2649 /// A rebuild, not [`Self::set_theme`]'s `mark_all_dirty()`: a target size is
2650 /// baked in `build()` (a `MinSize` wrapper, a recipe's `Rc<dyn FooStyle>`,
2651 /// the number of `Toolbar` items that fit), and marking layout + paint
2652 /// cannot re-bake it. This reuses the exact path a
2653 /// `BindingLevel::Rebuild` binding takes — `mark_needs_rebuild` on each
2654 /// root plus `mark_ancestors_need_layout` — so the next layout pass drains
2655 /// it through `process_rebuilds`, which already handles focus restoration,
2656 /// the a11y re-walk and interaction-state revalidation.
2657 ///
2658 /// A no-op when the density is already the requested one: a density switch
2659 /// throws away every widget id in the tree, so it must not fire on a
2660 /// repeated set.
2661 ///
2662 /// [`TargetDensity`]: teksilo_tokens::TargetDensity
2663 pub fn set_input_density(&mut self, density: teksilo_tokens::TargetDensity) {
2664 if self.theme.input.density == density {
2665 return;
2666 }
2667 // Exactly one utterance per switch, guaranteed by the guard above:
2668 // every widget id in the tree is about to be thrown away, so a screen
2669 // reader that was reading one is about to lose its place and needs to
2670 // be told what happened.
2671 if let Some(wording) = self.density_announcement.clone() {
2672 self.announce(wording(density));
2673 }
2674 self.set_theme(self.theme.with_density(density));
2675 // The `BindingLevel::Rebuild` arm of `process_state_changes`
2676 // (`widget_tree/layout_impl.rs`), applied at every root.
2677 for root in self.arena.roots() {
2678 self.arena.mark_needs_rebuild(root);
2679 self.arena.mark_ancestors_need_layout(root);
2680 }
2681 }
2682
2683 /// Announce density switches to a screen reader, in the application's own
2684 /// words.
2685 ///
2686 /// A density switch rebuilds the entire tree, so a screen reader loses its
2687 /// place and the user hears no explanation for it. Registering a wording
2688 /// makes [`Self::set_input_density`] speak once — and only once — per real
2689 /// switch, through the same [`Self::announce`] path everything else uses.
2690 ///
2691 /// The wording is the application's because it cannot be the framework's:
2692 /// `teksilo-i18n` depends on this crate, so nothing here can name
2693 /// `LocalizedString` or reach a translation bundle, and a hardcoded English
2694 /// sentence spoken into a French screen reader is worse than silence. Pass
2695 /// a closure that resolves `tr!(…)`:
2696 ///
2697 /// ```ignore
2698 /// tree.set_density_announcement(Some(std::rc::Rc::new(|d| match d {
2699 /// TargetDensity::Compact => tr!(layout_compact()).into(),
2700 /// TargetDensity::Comfortable => tr!(layout_comfortable()).into(),
2701 /// TargetDensity::Touch => tr!(layout_touch()).into(),
2702 /// })));
2703 /// ```
2704 ///
2705 /// `None` — the default — announces nothing.
2706 pub fn set_density_announcement(
2707 &mut self,
2708 wording: Option<std::rc::Rc<dyn Fn(teksilo_tokens::TargetDensity) -> String>>,
2709 ) {
2710 self.density_announcement = wording;
2711 }
2712
2713 /// How to word "a context menu opened" for a screen reader, when the menu
2714 /// was opened by a **hold**.
2715 ///
2716 /// The other three routes need nothing: a secondary press, `Shift+F10` and
2717 /// the AccessKit `ShowContextMenu` action are all deliberate, and the menu
2718 /// takes focus, which is announcement enough. A hold is the one route whose
2719 /// user cannot see the menu appear — a finger is on top of where it opens —
2720 /// and which they may not have meant.
2721 ///
2722 /// The wording is the application's for the same reason
2723 /// [`Self::set_density_announcement`]'s is: `teksilo-i18n` depends on this
2724 /// crate, so nothing here can name a `LocalizedString`, and a hardcoded
2725 /// English sentence spoken into a French screen reader is worse than
2726 /// silence.
2727 ///
2728 /// ```ignore
2729 /// tree.set_context_menu_announcement(Some(std::rc::Rc::new(|| {
2730 /// tr!(context_menu_opened()).into()
2731 /// })));
2732 /// ```
2733 ///
2734 /// `None` — the default — announces nothing. Where it is set, the
2735 /// announcement is still suppressed if the **pressed node's** own subtree
2736 /// already carries a live region — the widget speaking for itself, so the
2737 /// framework does not speak over it — through
2738 /// [`Self::announce_unless_widget_speaks`]. The menu's own subtree is not
2739 /// consulted: it is raised by this very call and has not been walked yet.
2740 pub fn set_context_menu_announcement(
2741 &mut self,
2742 wording: Option<std::rc::Rc<dyn Fn() -> String>>,
2743 ) {
2744 self.context_menu_announcement = wording;
2745 }
2746
2747 /// Speak `message`, unless `widget` already speaks for itself.
2748 ///
2749 /// A framework announcement that lands beside a widget's own live region
2750 /// says everything twice — the failure mode [`crate::announcer`] warns
2751 /// about for `Toast`. This is the check that avoids it: if the last
2752 /// accessibility tree carried a live region *inside* `widget`'s subtree
2753 /// that the platform adapters would speak for (in the filtered tree, with
2754 /// a name), the widget is already talking and this stays quiet. A live
2755 /// region that is hidden, or that carries its text where its role takes
2756 /// no name from, is silent on every platform and does not count.
2757 /// Returns whether the message was queued.
2758 ///
2759 /// It necessarily reads **one tree behind**. An announcement is queued
2760 /// during event dispatch; the live-region text it would duplicate is
2761 /// whatever the *last* built update carried, because the next one has not
2762 /// been built yet. A widget that speaks for the first time in the same
2763 /// dispatch is therefore not yet visible here — which is the right bias:
2764 /// it errs toward saying something rather than toward silence.
2765 pub fn announce_unless_widget_speaks(
2766 &mut self,
2767 widget: WidgetId,
2768 message: impl Into<String>,
2769 ) -> bool {
2770 if self.widget_subtree_speaks(widget) {
2771 return false;
2772 }
2773 self.announce(message);
2774 true
2775 }
2776
2777 /// Whether the last delivered accessibility tree had a live node in
2778 /// `widget`'s subtree that the platform adapters would speak for.
2779 ///
2780 /// Read through `accesskit_consumer`, so by the adapters' rules, whether
2781 /// or not this tree records announcements: the node is in the filtered
2782 /// tree (not hidden, not inside a hidden subtree), it is live, itself or
2783 /// through an ancestor, and it has a name, which for a `Status` is its
2784 /// label and not its value.
2785 /// A live region no platform can hear does not speak, and must not keep
2786 /// the framework quiet. The politeness must be set inside the subtree,
2787 /// too: a widget that is live only because it sits in somebody else's
2788 /// live region is not the one speaking.
2789 ///
2790 /// Synthetic children count too, resolved to their owning widget through
2791 /// the same parent map the AccessKit action router uses. `teksilo-scene`
2792 /// can mark a scene item as a live region, and a live region is a live
2793 /// region wherever it was emitted from.
2794 fn widget_subtree_speaks(&self, widget: WidgetId) -> bool {
2795 let mut wanted: std::collections::HashSet<accesskit::NodeId> =
2796 std::collections::HashSet::new();
2797 let mut stack = vec![widget];
2798 while let Some(id) = stack.pop() {
2799 if self.arena.get(id).is_none() {
2800 continue;
2801 }
2802 wanted.insert(crate::accessibility::widget_id_to_node_id(id));
2803 stack.extend_from_slice(self.arena.children(id));
2804 }
2805 let Some(update) = &self.cached_a11y else {
2806 return false;
2807 };
2808 crate::accessibility::announcements::speaks_within(update, |node_id| {
2809 wanted.contains(&node_id)
2810 || self
2811 .synthetic_parent_map
2812 .get(&node_id)
2813 .is_some_and(|owner| {
2814 wanted.contains(&crate::accessibility::widget_id_to_node_id(*owner))
2815 })
2816 })
2817 }
2818
2819 /// How the active density is chosen. See [`DensityPolicy`].
2820 ///
2821 /// [`DensityPolicy`]: teksilo_tokens::DensityPolicy
2822 pub fn density_policy(&self) -> teksilo_tokens::DensityPolicy {
2823 self.density_policy
2824 }
2825
2826 /// Set the density-selection policy.
2827 ///
2828 /// Storing a `Fixed(d)` policy does **not** by itself switch the density —
2829 /// call [`Self::set_input_density`] for that. `FollowLastPointer` is not
2830 /// acted on either: it is state and an accessor, and the field's own
2831 /// documentation says what is still undecided about honouring it.
2832 pub fn set_density_policy(&mut self, policy: teksilo_tokens::DensityPolicy) {
2833 self.density_policy = policy;
2834 }
2835
2836 /// Whether touch input is accepted. See
2837 /// [`InputTokens::touch_enabled`](teksilo_tokens::InputTokens::touch_enabled).
2838 pub fn touch_enabled(&self) -> bool {
2839 self.theme.input.touch_enabled
2840 }
2841
2842 /// The runtime touch kill switch. With `false`, the platform translator
2843 /// drops touch input and the router installs no touch-only recognizers,
2844 /// so an app can fall back to mouse-only behaviour at runtime.
2845 ///
2846 /// Repaint-level only: turning touch off changes which events are accepted,
2847 /// never a dimension, so nothing is rebuilt or relaid out here. (The
2848 /// translator and router honour it from P08 / P15; this is the state.)
2849 pub fn set_touch_enabled(&mut self, enabled: bool) {
2850 if self.theme.input.touch_enabled == enabled {
2851 return;
2852 }
2853 let mut theme = self.theme.clone();
2854 theme.input.touch_enabled = enabled;
2855 self.theme = theme.clone();
2856 self.theme_signal.set(theme);
2857 self.recompute_effective_theme();
2858 }
2859
2860 /// Recompute [`Self::effective_theme`] from the current `theme` and the
2861 /// combined text scale (`user_text_scale * text_scale_factor`). Callers
2862 /// that change either input are responsible for `mark_all_dirty()`.
2863 fn recompute_effective_theme(&mut self) {
2864 let combined = (self.user_text_scale as f64 * self.text_scale_factor) as f32;
2865 self.effective_theme = if (combined - 1.0).abs() < f32::EPSILON {
2866 self.theme.clone()
2867 } else {
2868 let mut t = self.theme.clone();
2869 t.typography = t.typography.scaled(combined);
2870 t
2871 };
2872 // Single source: every downstream consumer (the layout/paint context
2873 // `text_scale` field, the reactive `text_scale_signal`) reads from here.
2874 self.effective_text_scale = combined;
2875 self.text_scale_signal.set(combined);
2876 }
2877
2878 /// The combined effective text scale (`user_text_scale * OS text_scale_factor`).
2879 /// Read by the layout/paint walkers to populate `ctx.text_scale` for widgets
2880 /// that size from a source other than `Theme.typography`.
2881 pub fn effective_text_scale(&self) -> f32 {
2882 self.effective_text_scale
2883 }
2884
2885 /// Reactive handle on [`Self::effective_text_scale`]. Build-time binders that
2886 /// must react to a scale change without their own rebuild path bind this
2887 /// (e.g. `Calendar` binds it at `Rebuild` level so its fixed cell constants
2888 /// recompute). Fires on `set_user_text_scale` / theme / OS-pref change.
2889 pub fn text_scale_signal(&self) -> crate::signal::Signal<f32> {
2890 self.text_scale_signal.clone()
2891 }
2892
2893 /// Set the user-controlled global text-scale factor (`1.0` = 100 %).
2894 ///
2895 /// The factor multiplies with the OS accessibility text-scale preference to
2896 /// produce the rendered scale. Recomputes the effective theme and marks all
2897 /// widgets dirty so every text widget grows on the next pass; no rebuild,
2898 /// so focus/scroll/interaction state survive. Values outside `[0.25, 8.0]`
2899 /// are clamped. Persisted by the application via
2900 /// `teksilo_settings::TEXT_SCALE_KEY`.
2901 pub fn set_user_text_scale(&mut self, factor: f32) {
2902 let clamped = factor.clamp(0.25, 8.0);
2903 if (self.user_text_scale - clamped).abs() < f32::EPSILON {
2904 return;
2905 }
2906 self.user_text_scale = clamped;
2907 self.recompute_effective_theme();
2908 self.arena.mark_all_dirty();
2909 // Same reasoning as `set_theme`: bigger text re-wraps inside a box
2910 // whose size the parent may hold fixed.
2911 self.a11y_dirty = true;
2912 }
2913
2914 /// The current user-controlled text-scale factor (`1.0` = 100 %).
2915 pub fn user_text_scale(&self) -> f32 {
2916 self.user_text_scale
2917 }
2918
2919 /// After a rebuild that destroyed subtrees — or after a `visible_when` /
2920 /// `Switcher` pass parks the focused widget dormant — drop any interaction
2921 /// state (focus, hover) whose target `WidgetId` is no longer active.
2922 ///
2923 /// **FocusLost is load-bearing.** Clearing `self.focused` alone leaves the
2924 /// widget's own `on_focus` / `has_focus` / caret-blink state thinking it is
2925 /// still focused. A rich-text editor in that state keeps scheduling
2926 /// `wake_at` caret toggles and re-arming `frame_request` from its tick
2927 /// effect — and because `frame_tick` observers are **not** gated on
2928 /// dormancy, every open tab's editor (TabWidget mounts them all) still runs
2929 /// on those wakes. Rapid tab switches that park a focused editor without a
2930 /// real focus move (programmatic selection, race with pointer focus) used
2931 /// to accumulate stuck "focused" editors and unbounded frame work. Dispatch
2932 /// `FocusLost` first so widgets clear that state, then drop the tree's
2933 /// focus pointer.
2934 ///
2935 /// Preserves state when the target still exists *and* is active. Called from
2936 /// data-driven rebuild paths (`process_state_changes`) and after every
2937 /// rebuild drain; theme and locale switches no longer rebuild.
2938 pub(crate) fn revalidate_interaction_state(&mut self, ops: &mut dyn crate::window::WindowOps) {
2939 if let Some(id) = self.focused
2940 && !self.arena.is_active(id)
2941 {
2942 let old = self.focused;
2943 // Deliver FocusLost while the node still exists (dormant or about to
2944 // be torn down). Skip if the node is already gone — destroy paths
2945 // take care of bookkeeping without a deliverable target.
2946 if self.arena.get(id).is_some() {
2947 // Direct: no bubble through dormant ancestors, no overlay
2948 // dismiss side-effects — this is a teardown signal, not a
2949 // user-driven focus move.
2950 self.dispatch_to_widget_direct(
2951 id,
2952 &crate::event::WidgetEvent::FocusLost,
2953 &mut *ops,
2954 );
2955 }
2956 self.set_focused(None);
2957 self.focus_origin = None;
2958 self.update_focus_within_signals(old, None);
2959 self.update_view_focus_signals(old, None);
2960 self.a11y_dirty = true;
2961 }
2962 if self.focused.is_none() {
2963 self.focus_origin = None;
2964 }
2965 if let Some(id) = self.hovered_id()
2966 && !self.arena.is_active(id)
2967 {
2968 let old = self.hovered_id();
2969 self.set_hovered(None);
2970 self.update_hover_within_signals(old, None);
2971 }
2972 // Pointer capture anchored at a destroyed widget would otherwise
2973 // swallow every subsequent Move/Up — dispatch_to_widget rejects
2974 // inactive targets. Drop the capture so events resume normal
2975 // hit-test dispatch. Same for any in-flight drag session whose
2976 // source was torn down: the user sees the drag "stick".
2977 self.pointers.retain_active(&self.arena);
2978 // External (OS) drags have no in-app source widget, so they are never
2979 // torn down by source destruction — only internal drags are salvaged.
2980 let source_gone = self
2981 .active_drag
2982 .as_ref()
2983 .and_then(|s| s.source_widget)
2984 .is_some_and(|sw| !self.arena.is_active(sw));
2985 if source_gone {
2986 // `cancel_active_drag` fires on_drag_leave on the current
2987 // target before cleanup — the same contract as Escape.
2988 self.cancel_active_drag(&mut *ops);
2989 } else {
2990 // The drag *source* survived but its current hover **target** was
2991 // torn down by the rebuild (e.g. a side disabled / collapsed
2992 // mid-drag destroyed the panel under the pointer). Clear the stale
2993 // target id so a subsequent drop doesn't resolve to a destroyed
2994 // widget (and silently vanish); the next move — or the drop's own
2995 // re-hit-test — re-engages a live target.
2996 let stale_target = self
2997 .active_drag
2998 .as_ref()
2999 .and_then(|d| d.current_target)
3000 .is_some_and(|t| !self.arena.is_active(t));
3001 if stale_target && let Some(drag) = self.active_drag.as_mut() {
3002 drag.current_target = None;
3003 }
3004 }
3005 }
3006
3007 /// Rebuild a single composite widget: destroy old children, re-run `build()`,
3008 /// and wire up new children. Called from `process_state_changes()` when a
3009 /// binding at `BindingLevel::Rebuild` fires (data-driven rebuild). Theme
3010 /// and locale changes do **not** rebuild — they update reactive signals
3011 /// that widgets bind to via `theme_signal()` / `locale_signal()`.
3012 /// Test-only: force-mark a widget for rebuild on the next layout
3013 /// pass. Lets regression tests exercise the rebuild path without
3014 /// needing to trip a Signal binding. Exposed cross-crate (not
3015 /// `#[cfg(test)]`-gated) so widget-crate tests in `teksilo-widgets`
3016 /// and elsewhere can also drive rebuilds; the `_for_testing`
3017 /// suffix marks it as not intended for application code.
3018 pub fn arena_mark_needs_rebuild_for_testing(&mut self, id: WidgetId) {
3019 self.arena.mark_needs_rebuild(id);
3020 }
3021
3022 /// Force a [`DeferredSubtree`](crate::deferred_subtree::DeferredSubtree) at
3023 /// `id` to build its content now. A no-op for any other widget.
3024 ///
3025 /// The framework's own door into deferred content, for the case where the
3026 /// decision to show is the tree's rather than a widget's: a tooltip whose
3027 /// dwell has just matured has no open signal anyone could have handed over.
3028 pub(crate) fn materialize_deferred(&mut self, id: WidgetId) {
3029 let forced = self
3030 .arena
3031 .get_mut(id)
3032 .and_then(|n| n.widget.as_any_mut())
3033 .and_then(|any| any.downcast_mut::<crate::deferred_subtree::DeferredSubtree>())
3034 .map(|deferred| {
3035 let needed = !deferred.is_materialized();
3036 deferred.force();
3037 needed
3038 })
3039 .unwrap_or(false);
3040 if forced {
3041 self.rebuild_single_widget(id);
3042 }
3043 }
3044
3045 pub(crate) fn rebuild_single_widget(&mut self, widget_id: WidgetId) {
3046 // Per §9.4.5, drop the source handle first (stops further source-side
3047 // dispatch) and then remove the UI-side callback. Either order gives
3048 // the same user-visible outcome for events that get posted between
3049 // the two steps, but dropping the source handle first stops the
3050 // publisher thread's work sooner.
3051 //
3052 // ⚠ That reasoning is about the two steps below, and it used to be
3053 // read as covering the whole problem. It does not. The dangerous gap
3054 // is not the microseconds between these two lines, it is the whole
3055 // span from *publish* to *dispatch*: a backend event is posted with
3056 // the id its publisher captured and is handled by the UI thread
3057 // frames later, so any rebuild in between used to strand it. The ids
3058 // are therefore carried across into the new build (see
3059 // `BuildContext::reusable_sub_ids`) rather than being retired here.
3060 // Skribisto's Analysis pane hit this every time it was the restored
3061 // view at project open: it starts a long operation in `build()` and
3062 // sets its own `Rebuild`-bound state signal, the operation finished
3063 // inside its own rebuild, and the pane sat on "Reading the
3064 // manuscript…" for the rest of the session with nothing logged.
3065 // Cancel any looping/one-shot animations owned by this widget
3066 // before build() runs. Without this, a widget that creates a
3067 // fresh `animated_signal` in build() would leak the previous
3068 // instance's scheduler entry: the old Signal<f32> clone lives
3069 // in `animations` forever, ticking against an orphaned signal
3070 // (silent CPU waste) and, for looping animations, doubling up
3071 // when the new one registers.
3072 self.animation_scheduler.cancel_by_widget(widget_id);
3073 // Same pattern for shader-driven animated quads: free the
3074 // widget's slot(s) so `build()` can allocate fresh handles.
3075 // The old cached_paint (if any) carries stale slot indices —
3076 // clear it so paint() re-runs and re-emits DrawCommands with
3077 // the newly-allocated slot.
3078 self.animated_quads.cancel_by_widget(widget_id);
3079 // Its off-thread attachments: `build()` attaches its triggers and
3080 // sets its hook again. The wake state stays, with whatever was
3081 // requested and not yet taken: a request is posted with nothing that
3082 // names the build it was meant for, as a subscription id is above.
3083 self.off_thread.begin_rebuild(widget_id);
3084
3085 let drained_subs = if let Some(node) = self.arena.get_mut(widget_id) {
3086 node.effect_handles.clear();
3087 node.actions.clear();
3088 node.dirty.needs_rebuild = false;
3089 node.cached_paint = None;
3090 node.dirty.needs_paint = true;
3091 // Reset only the OWN handler bucket so `apply_self_handlers`
3092 // during this build's fresh build() starts from empty and
3093 // doesn't stack N-fold handler chains across rebuilds.
3094 // `external_handlers` — set by the `WidgetBuilder` chain at
3095 // creation time or by a composing parent's
3096 // `apply_handlers(child_id, ...)` — persists: those handlers
3097 // come from outside the widget and aren't re-emitted by its
3098 // own `build()`.
3099 //
3100 // `node_focusable` / `node_tab_index` / `node_cursor` /
3101 // `clips_children` / `context_menu_factory` are simple
3102 // values, not accumulating closures. Leave them alone —
3103 // apply_self_handlers rewrites them if the new build
3104 // specifies non-None values; otherwise values from the
3105 // creation site survive the rebuild.
3106 //
3107 // The gesture arena goes with the own bucket, but its tap streak
3108 // is carried over to the arena the next press installs, so a
3109 // double click whose first click rebuilt the node still counts
3110 // two. Only when an arena exists: with none, no press happened
3111 // since the last carry and the carried value is still the latest.
3112 // A contact live at this rebuild loses its release (it will find
3113 // no arena), so nothing is carried then: the earlier count would
3114 // turn a later single tap into a double one.
3115 if let Some(set) = node.handlers.gesture_arena.as_mut() {
3116 node.carried_tap_streak = if set.is_live() {
3117 None
3118 } else {
3119 Some(set.take_streak())
3120 };
3121 }
3122 node.handlers = crate::event_handlers::EventHandlers::new();
3123 std::mem::take(&mut node.subscription_handles)
3124 } else {
3125 Vec::new()
3126 };
3127 // Rebuild wiped the OWN handler bucket above (the gesture arena
3128 // lived there), so the widget no longer owns any recognizers.
3129 // The next pointer hit re-runs `ensure_gesture_arena` and
3130 // re-inserts if the new build still wires gesture handlers, seeding
3131 // the new arena with the tap streak carried in `carried_tap_streak`.
3132 // External handlers (set via the builder chain at creation time)
3133 // persist, but `external_handlers` never carries a gesture arena
3134 // directly — it's always built by `ensure_gesture_arena` into
3135 // the OWN bucket.
3136 self.gesture_owners.remove(&widget_id);
3137 // Shortcuts the widget declared are torn down too — they will
3138 // be re-registered during the upcoming `build()` call. User
3139 // overrides live in a separate map keyed by id, so user
3140 // rebindings survive this round-trip (see ShortcutRegistry
3141 // graveyard semantics).
3142 self.shortcut_registry.unregister_all_for_owner(widget_id);
3143 self.global_actions.retain(|(owner, _)| *owner != widget_id);
3144 self.text_surfaces.remove(widget_id);
3145 // Re-apply `Widget::declare_shortcuts` so the static metadata
3146 // survives the rebuild (the unregister above wiped both
3147 // declared and build-registered entries; build() will refill
3148 // the handler-bearing ones, but it can't be relied on to
3149 // refill the metadata-only declarations).
3150 self.apply_declared_shortcuts(widget_id);
3151 // Drop any signal→widget bindings from the previous build
3152 // cycle so `build()` can re-register a fresh set without
3153 // accumulating duplicates across rebuilds.
3154 self.binding_registry.unregister_for_widget(widget_id);
3155 // Kept, in order, and handed to the upcoming `build()` so it re-subscribes under
3156 // the same ids. A subscription's id is what a publisher captured and posted with;
3157 // minting new ones here would leave every event already queued for this widget
3158 // naming an id nothing answers to. See `BuildContext::reusable_sub_ids`.
3159 let mut reusable_sub_ids = Vec::with_capacity(drained_subs.len());
3160 for (sub_id, handle) in drained_subs {
3161 drop(handle);
3162 self.app_context
3163 .subscription_callbacks
3164 .borrow_mut()
3165 .remove(&sub_id);
3166 self.app_context
3167 .subscription_ctx_callbacks
3168 .borrow_mut()
3169 .remove(&sub_id);
3170 reusable_sub_ids.push(sub_id);
3171 }
3172
3173 // Decide how to treat the existing children. Two modes:
3174 //
3175 // * Default (`preserves_children_on_rebuild() == false`): the widget
3176 // re-derives its whole subtree, so tear down every old child up
3177 // front and let `build()` produce a fresh set.
3178 //
3179 // * Reconcile (`preserves_children_on_rebuild() == true`): the widget
3180 // re-attaches the children it keeps (by id) and drops the rest. We
3181 // snapshot the old children, run `build()`, then destroy only the
3182 // old children the new build did NOT re-attach and did NOT re-parent
3183 // elsewhere. Re-attached children keep their state (focus, scroll,
3184 // text, subscriptions); dropped children are reaped rather than left
3185 // as stranded, still-active orphans.
3186 let preserve_children = self
3187 .arena
3188 .get(widget_id)
3189 .map(|n| n.widget.preserves_children_on_rebuild())
3190 .unwrap_or(false);
3191 let old_children: Vec<WidgetId> = self.arena.children(widget_id).to_vec();
3192 if !preserve_children {
3193 // The widget being rebuilt is marked for layout and paint
3194 // already, which covers what its old children drew.
3195 for child_id in &old_children {
3196 self.destroy_subtree_inner(*child_id, false);
3197 }
3198 }
3199
3200 // The parentless nodes the *previous* build owned. Taken now so
3201 // `build()` records its new set into an empty list, and destroyed after
3202 // it returns — by then the widget's own fields point at the new nodes,
3203 // so tearing the old ones down cannot strand a live id in the widget.
3204 // Both the `preserve_children` reconcile and the plain path want this:
3205 // detached content is rebuilt wholesale either way (it is not addressed
3206 // by id from the outside, so there is nothing to preserve).
3207 let old_detached: Vec<WidgetId> = self
3208 .arena
3209 .get_mut(widget_id)
3210 .map(|node| std::mem::take(&mut node.detached))
3211 .unwrap_or_default();
3212
3213 let mut widget_box = match self.arena.take_widget(widget_id) {
3214 Some(widget) => widget,
3215 None => {
3216 self.finish_off_thread_rebuild(widget_id);
3217 return;
3218 }
3219 };
3220
3221 let mut build_ctx = crate::build_context::BuildContext {
3222 tree: self,
3223 composite_id: Some(widget_id),
3224 effect_handles: Vec::new(),
3225 subscription_handles: Vec::new(),
3226 reusable_sub_ids,
3227 };
3228 let new_children = widget_box.build(&mut build_ctx);
3229 let effect_handles = std::mem::take(&mut build_ctx.effect_handles);
3230 let subscription_handles = std::mem::take(&mut build_ctx.subscription_handles);
3231
3232 self.arena.restore_widget(widget_id, widget_box);
3233 self.finish_off_thread_rebuild(widget_id);
3234
3235 for &child_id in &new_children {
3236 if let Some(child_node) = self.arena.get_mut(child_id) {
3237 child_node.parent = Some(widget_id);
3238 }
3239 }
3240
3241 // Reconcile the preserve path: reap any old child the new build
3242 // dropped (not in `new_children`) and did not re-parent elsewhere
3243 // (its `parent` still points here). Authoritative parent pointers mean
3244 // a kept subtree re-parented out of a dropped sibling survives. Runs
3245 // before `node.children` is overwritten so the destroy walk can't see
3246 // the new list. Re-parented survivors already have their new parent by
3247 // now (`ctx.add` builds nested widgets synchronously and re-homes their
3248 // children), so the `parent == widget_id` test correctly excludes them.
3249 if preserve_children {
3250 let new_set: std::collections::HashSet<WidgetId> =
3251 new_children.iter().copied().collect();
3252 for &old_c in &old_children {
3253 if !new_set.contains(&old_c) && self.arena.parent(old_c) == Some(widget_id) {
3254 self.destroy_subtree_inner(old_c, true);
3255 }
3256 }
3257 }
3258
3259 if let Some(node) = self.arena.get_mut(widget_id) {
3260 node.children = new_children;
3261 node.effect_handles = effect_handles;
3262 node.subscription_handles = subscription_handles;
3263 }
3264
3265 // Reap the previous build's parentless content, now that the fresh set
3266 // is recorded and the widget points at it.
3267 for id in old_detached {
3268 self.destroy_subtree_inner(id, false);
3269 }
3270 }
3271
3272 /// Record that `owner` created and owns the parentless node `detached` —
3273 /// pre-built overlay content that is deliberately not a child. See
3274 /// [`BuildContext::add_detached`](crate::build_context::BuildContext::add_detached)
3275 /// and [`WidgetNode::detached`](crate::arena::WidgetNode).
3276 pub(crate) fn record_detached(&mut self, owner: WidgetId, detached: WidgetId) {
3277 if let Some(node) = self.arena.get_mut(owner) {
3278 node.detached.push(detached);
3279 }
3280 }
3281
3282 /// Destroy every parentless node `owner` owns, and forget them.
3283 ///
3284 /// Taken out of the node first: the destroy walk below can re-enter this
3285 /// function (a detached node may own detached nodes of its own — a rich
3286 /// tooltip's cascade children each pre-build their own), and it must not
3287 /// see a list it is halfway through consuming.
3288 fn destroy_detached_of(&mut self, owner: WidgetId) {
3289 let detached = self
3290 .arena
3291 .get_mut(owner)
3292 .map(|node| std::mem::take(&mut node.detached))
3293 .unwrap_or_default();
3294 for id in detached {
3295 self.destroy_subtree_inner(id, false);
3296 }
3297 }
3298
3299 /// Recursively destroy a subtree, dropping per-widget subscription
3300 /// handles and removing their UI-side callbacks. Use this in place of
3301 /// `arena.destroy()` whenever a widget that may have subscribed to
3302 /// events is being torn down.
3303 ///
3304 /// What the subtree drew is in the composed frame, and its ancestors'
3305 /// layouts made room for it: both are recomputed, as for a subtree made
3306 /// dormant. Without that the next frame, where nothing else changed,
3307 /// replayed the destroyed widgets' drawing, and a live picture among
3308 /// them kept its texture until something repainted their parent.
3309 pub(crate) fn destroy_subtree(&mut self, widget_id: WidgetId) {
3310 self.arena.mark_ancestors_need_layout(widget_id);
3311 self.cached_frame = None;
3312 self.a11y_dirty = true;
3313 self.destroy_subtree_inner(widget_id, false);
3314 }
3315
3316 /// Shared teardown for [`destroy_subtree`](Self::destroy_subtree) and the
3317 /// reconciling rebuild path. When `reparent_aware` is `true`, recursion
3318 /// descends into a child only if that child's `parent` still points at
3319 /// `widget_id`.
3320 ///
3321 /// A reconciling rebuild (a [`preserves_children_on_rebuild`] widget) may
3322 /// re-parent a kept subtree *out* of a dropped sibling and *into* the new
3323 /// tree. The dropped sibling's `children` list still lists that subtree
3324 /// (stale), so following it would tear down a node that is actually alive
3325 /// elsewhere. Following the authoritative `parent` pointer instead stops
3326 /// at the boundary of what genuinely still belongs to the node being
3327 /// destroyed. The per-node teardown ends with `arena.remove_node` (a
3328 /// single-node removal), NOT `arena.destroy` (which would re-recurse the
3329 /// stale `children` list and undo the skip).
3330 ///
3331 /// [`preserves_children_on_rebuild`]: crate::widget::Widget::preserves_children_on_rebuild
3332 fn destroy_subtree_inner(&mut self, widget_id: WidgetId, reparent_aware: bool) {
3333 // See the matching cancel in `rebuild_single_widget` — the
3334 // scheduler holds strong Signal<f32> clones, so the animation
3335 // would outlive its widget without this explicit cancellation.
3336 self.animation_scheduler.cancel_by_widget(widget_id);
3337 // Release the animated-quad slot(s) too.
3338 self.animated_quads.cancel_by_widget(widget_id);
3339 // And what it attached for off-thread content.
3340 self.off_thread.cancel_by_widget(widget_id);
3341 // A tooltip's content widget is parentless (`ctx.add`), so the child
3342 // walk below never reaches it — reap it explicitly or the entry and
3343 // its node outlive the anchor for the lifetime of the tree.
3344 self.retire_tooltips_of_destroyed_anchor(widget_id);
3345 // Same reasoning, one level up: every *other* parentless node this
3346 // widget built (a dropdown menu, a calendar, a tooltip's nested
3347 // cascade children) is unreachable from the child walk and dies here
3348 // or never.
3349 self.destroy_detached_of(widget_id);
3350
3351 let children: Vec<WidgetId> = self.arena.children(widget_id).to_vec();
3352 for child in children {
3353 if reparent_aware && self.arena.parent(child) != Some(widget_id) {
3354 // Re-parented into the surviving tree by this rebuild — leave it.
3355 continue;
3356 }
3357 self.destroy_subtree_inner(child, reparent_aware);
3358 }
3359 let drained_subs = self
3360 .arena
3361 .get_mut(widget_id)
3362 .map(|node| std::mem::take(&mut node.subscription_handles))
3363 .unwrap_or_default();
3364 for (sub_id, handle) in drained_subs {
3365 drop(handle);
3366 self.app_context
3367 .subscription_callbacks
3368 .borrow_mut()
3369 .remove(&sub_id);
3370 self.app_context
3371 .subscription_ctx_callbacks
3372 .borrow_mut()
3373 .remove(&sub_id);
3374 }
3375 // Drop any shortcuts the destroyed widget owned. Unlike
3376 // `rebuild_single_widget`, destruction is permanent; if the
3377 // user had overrides, they stay in the graveyard.
3378 self.shortcut_registry.unregister_all_for_owner(widget_id);
3379 self.global_actions.retain(|(owner, _)| *owner != widget_id);
3380 self.text_surfaces.remove(widget_id);
3381 // Bindings from this widget stop being relevant; clean them
3382 // up so the registry doesn't leak dead entries for the
3383 // lifetime of the app.
3384 self.binding_registry.unregister_for_widget(widget_id);
3385 // Keep `gesture_owners` honest — destroying the widget tears
3386 // down its handlers, so the per-frame gesture pass must stop
3387 // visiting it.
3388 self.gesture_owners.remove(&widget_id);
3389 // If focus pointed at the widget about to disappear, drop it
3390 // so later dispatch doesn't anchor intent walks at a dead id
3391 // (which would silently swallow the intent).
3392 if self.focused == Some(widget_id) {
3393 let old = self.focused;
3394 self.set_focused(None);
3395 self.focus_origin = None;
3396 self.update_focus_within_signals(old, None);
3397 self.update_view_focus_signals(old, None);
3398 }
3399 if self.hovered_id() == Some(widget_id) {
3400 let old = self.hovered_id();
3401 self.set_hovered(None);
3402 self.update_hover_within_signals(old, None);
3403 }
3404 // Symmetric with focus/hover above: a pointer capture anchored at the
3405 // widget about to disappear would otherwise swallow every subsequent
3406 // Move/Up (dispatch rejects inactive targets) until the next layout
3407 // pass runs `revalidate_interaction_state`. Drop it eagerly so capture
3408 // never outlives its owner, even when a destroy happens mid-gesture.
3409 self.pointers.release_captures_of(widget_id);
3410 // Single-node removal: this function already recursed into the
3411 // children above (honouring re-parenting when `reparent_aware`).
3412 // `arena.destroy` would re-recurse the now-stale `children` list and
3413 // tear down a survivor re-homed out of this subtree.
3414 self.arena.remove_node(widget_id);
3415 }
3416
3417 /// Set the layout direction (LTR/RTL). Marks all widgets as needing layout.
3418 pub fn set_layout_direction(&mut self, direction: crate::environment::LayoutDirection) {
3419 // A name can depend on the direction (a docking side is "Left panel"
3420 // or "Right panel" by where it is drawn), and a relayout alone does
3421 // not re-walk the accessibility tree.
3422 if self.layout_direction != direction {
3423 self.a11y_dirty = true;
3424 }
3425 self.layout_direction = direction;
3426 self.arena.mark_all_dirty();
3427 }
3428
3429 /// The current layout direction.
3430 pub fn layout_direction(&self) -> crate::environment::LayoutDirection {
3431 self.layout_direction
3432 }
3433
3434 /// Set OS-level accessibility preferences.
3435 ///
3436 /// Called by `teksilo-app` after querying the platform layer. Updates the
3437 /// values fed into `PaintContext` and `Environment` on subsequent frames.
3438 /// Marks all widgets dirty so the new preferences take effect immediately.
3439 pub fn set_accessibility_preferences(
3440 &mut self,
3441 high_contrast: bool,
3442 reduced_motion: bool,
3443 text_scale_factor: f64,
3444 ) {
3445 let changed = self.prefers_high_contrast.get() != high_contrast
3446 || self.prefers_reduced_motion != reduced_motion
3447 || (self.text_scale_factor - text_scale_factor).abs() > f64::EPSILON;
3448
3449 if changed {
3450 if self.prefers_high_contrast.get() != high_contrast {
3451 self.prefers_high_contrast.set(high_contrast);
3452 }
3453 self.prefers_reduced_motion = reduced_motion;
3454 self.text_scale_factor = text_scale_factor;
3455 // The OS factor feeds the effective text scale (multiplied with the
3456 // user factor), so refresh the cached scaled typography.
3457 self.recompute_effective_theme();
3458 self.arena.mark_all_dirty();
3459 }
3460 }
3461
3462 /// Whether the OS has requested high-contrast mode.
3463 pub fn prefers_high_contrast(&self) -> bool {
3464 self.prefers_high_contrast.get()
3465 }
3466
3467 /// Reactive handle on the high-contrast preference. Fires when
3468 /// [`set_accessibility_preferences`](Self::set_accessibility_preferences)
3469 /// changes it. Bind at [`BindingLevel::RepaintOnly`]: the preference only
3470 /// changes colours. Starts `false`.
3471 ///
3472 /// [`BindingLevel::RepaintOnly`]: crate::binding::BindingLevel::RepaintOnly
3473 pub fn high_contrast_signal(&self) -> crate::signal::Signal<bool> {
3474 self.prefers_high_contrast.clone()
3475 }
3476
3477 /// The [`PaintState`](crate::styles::PaintState) this tree paints under:
3478 /// its window-active state and the high-contrast preference. The paint
3479 /// walker hands it to [`Theme::for_paint_state`](crate::styles::Theme::for_paint_state).
3480 pub fn paint_state(&self) -> crate::styles::PaintState {
3481 crate::styles::PaintState {
3482 window_active: self.is_window_active(),
3483 high_contrast: self.prefers_high_contrast(),
3484 }
3485 }
3486
3487 /// Whether the OS has requested reduced motion.
3488 pub fn prefers_reduced_motion(&self) -> bool {
3489 self.prefers_reduced_motion
3490 }
3491
3492 /// OS text scaling factor (1.0 = normal).
3493 pub fn text_scale_factor(&self) -> f64 {
3494 self.text_scale_factor
3495 }
3496
3497 /// Report whether the *operating system* says an assistive technology is
3498 /// reading the screen.
3499 ///
3500 /// Fed by `teksilo-app` from `teksilo_platform::AccessibilityPreferences`,
3501 /// which asks Windows for `SPI_GETSCREENREADER`, AT-SPI for
3502 /// `org.a11y.Status.ScreenReaderEnabled`, and macOS for
3503 /// `NSWorkspace::isVoiceOverEnabled`. A platform that cannot answer leaves
3504 /// it [`ScreenReaderState::Unknown`], which behaves as "no".
3505 ///
3506 /// [`ScreenReaderState::Unknown`]: crate::environment::ScreenReaderState::Unknown
3507 ///
3508 /// **Not** AccessKit activation. An AccessKit adapter activates for
3509 /// anything that walks the tree — a screen magnifier, a voice-control front
3510 /// end, a UI-automation inspector, a tree browser like Accerciser — none of
3511 /// which want a touch to become a probe. Treating activation as evidence of
3512 /// a screen reader is how explore-by-touch gets switched on under an
3513 /// inspector and makes the app untouchable.
3514 ///
3515 /// Observers of [`Self::screen_reader_signal`] fire when the value
3516 /// changes. Nothing is marked dirty here: a binding chooses its own
3517 /// [`BindingLevel`](crate::binding::BindingLevel).
3518 ///
3519 /// [`ScreenReaderState`]: crate::environment::ScreenReaderState
3520 pub fn set_screen_reader_state(&mut self, state: crate::environment::ScreenReaderState) {
3521 self.screen_reader.set_if_changed(state);
3522 }
3523
3524 /// The screen-reader state most recently reported by the platform.
3525 ///
3526 /// [`ScreenReaderState::Unknown`] until something reports one.
3527 ///
3528 /// [`ScreenReaderState::Unknown`]: crate::environment::ScreenReaderState::Unknown
3529 pub fn screen_reader_state(&self) -> crate::environment::ScreenReaderState {
3530 self.screen_reader.get()
3531 }
3532
3533 /// Reactive handle on the operating system's screen-reader state, the
3534 /// companion of [`Self::high_contrast_signal`]. Starts
3535 /// [`ScreenReaderState::Unknown`].
3536 ///
3537 /// It is the OS flag, not AccessKit attachment: attaching a client
3538 /// changes nothing, and a client detaching forces `Inactive`. Only
3539 /// `Active` means a reader is present; `Unknown` (cannot tell) and
3540 /// `Inactive` both mean the framework does not treat one as present, so
3541 /// an application must never remove or disable anything unless the
3542 /// state is `Active`.
3543 ///
3544 /// A new window starts with the window manager's last reading (taken at
3545 /// startup or when a window last took the focus). The reading is taken
3546 /// again when a window takes the focus, and a detaching AccessKit client
3547 /// forces `Inactive`, which then holds until the OS flag itself changes.
3548 /// The value is per window tree, so two windows can briefly disagree.
3549 ///
3550 /// Read it, do not write it: the framework writes it, and a write to the
3551 /// signal would also switch the `Auto` explore-by-touch gate. The type is
3552 /// `teksilo_core::ScreenReaderState` (`teksilo::core::ScreenReaderState`
3553 /// from the umbrella crate); it is not in the prelude.
3554 ///
3555 /// Nothing is marked dirty when it changes: bind at the level you need
3556 /// ([`BindingLevel::Rebuild`](crate::binding::BindingLevel::Rebuild) to
3557 /// swap widgets, `AccessibilityOnly` for an accessibility property,
3558 /// `RepaintOnly` for colour). An effect does not replay the current
3559 /// value: read [`Self::screen_reader_state`] once, then subscribe.
3560 ///
3561 /// Use it for additive presentation (longer status wording, a one-time
3562 /// offer the user can refuse). It is not a switch for a second, reduced
3563 /// interface, not a gate on semantics, focus or the AccessKit tree, and
3564 /// not a substitute for the reduced-motion preference. Many readers
3565 /// never set the OS flag.
3566 ///
3567 /// [`ScreenReaderState::Unknown`]: crate::environment::ScreenReaderState::Unknown
3568 pub fn screen_reader_signal(
3569 &self,
3570 ) -> crate::signal::Signal<crate::environment::ScreenReaderState> {
3571 self.screen_reader.clone()
3572 }
3573
3574 /// Choose how explore-by-touch is decided for this window.
3575 ///
3576 /// [`ExploreByTouch::Off`] is the default and today's behaviour;
3577 /// [`ExploreByTouch::Auto`] follows [`Self::screen_reader_state`];
3578 /// [`ExploreByTouch::On`] forces it regardless. Read the resolved answer
3579 /// with [`Self::explore_by_touch_active`].
3580 ///
3581 /// [`ExploreByTouch::Off`]: crate::environment::ExploreByTouch::Off
3582 /// [`ExploreByTouch::Auto`]: crate::environment::ExploreByTouch::Auto
3583 /// [`ExploreByTouch::On`]: crate::environment::ExploreByTouch::On
3584 pub fn set_explore_by_touch(&mut self, mode: crate::environment::ExploreByTouch) {
3585 self.explore_by_touch = mode;
3586 }
3587
3588 /// The explore-by-touch policy most recently set.
3589 pub fn explore_by_touch(&self) -> crate::environment::ExploreByTouch {
3590 self.explore_by_touch
3591 }
3592
3593 /// Whether explore-by-touch is in force right now.
3594 ///
3595 /// `On` is unconditional; `Auto` requires the platform to have reported an
3596 /// active screen reader; `Off` is never in force. Nothing in the framework
3597 /// consumes this yet — the touch-as-probe interaction it gates has no
3598 /// owner — so it is a supply, a policy and a query, and no pointer path
3599 /// branches on it.
3600 pub fn explore_by_touch_active(&self) -> bool {
3601 use crate::environment::{ExploreByTouch, ScreenReaderState};
3602 match self.explore_by_touch {
3603 ExploreByTouch::Off => false,
3604 ExploreByTouch::On => true,
3605 ExploreByTouch::Auto => self.screen_reader.get() == ScreenReaderState::Active,
3606 }
3607 }
3608
3609 /// Report whether an AccessKit client is attached to this window.
3610 ///
3611 /// Written by `teksilo-app` from the platform adapter's activation and
3612 /// deactivation handlers, and used **asymmetrically** on purpose:
3613 ///
3614 /// * Attaching proves nothing. Magnifier, Voice Access and a UI-automation
3615 /// inspector all activate the adapter, so this never sets
3616 /// [`ScreenReaderState::Active`].
3617 /// * Detaching proves something. When the last client goes away there is
3618 /// no screen reader either, so a `true` → `false` transition forces
3619 /// [`ScreenReaderState::Inactive`] and an
3620 /// [`ExploreByTouch::Auto`](crate::environment::ExploreByTouch::Auto)
3621 /// window stops exploring immediately, without waiting for the next OS
3622 /// query. A later OS query is free to say `Active` again.
3623 ///
3624 /// [`ScreenReaderState::Active`]: crate::environment::ScreenReaderState::Active
3625 /// [`ScreenReaderState::Inactive`]: crate::environment::ScreenReaderState::Inactive
3626 pub fn set_at_client_attached(&mut self, attached: bool) {
3627 if self.at_client_attached && !attached {
3628 self.screen_reader
3629 .set_if_changed(crate::environment::ScreenReaderState::Inactive);
3630 }
3631 self.at_client_attached = attached;
3632 }
3633
3634 /// Whether an AccessKit client is currently attached to this window.
3635 pub fn at_client_attached(&self) -> bool {
3636 self.at_client_attached
3637 }
3638
3639 /// Set the host window HiDPI device scale (physical px per logical px).
3640 /// Written by `teksilo-app` when the window is created and again on
3641 /// `WindowEvent::ScaleFactorChanged`. Surfaced to widgets via
3642 /// `LayoutContext::scale_factor` and [`Self::device_scale_signal`].
3643 ///
3644 /// A scale change relayouts nothing by itself: the tree is logical, and
3645 /// when the window's logical size stays the same the next layout pass
3646 /// finds nothing to do. A widget whose layout reads the scale binds
3647 /// [`Self::device_scale_signal`] at `Relayout`, which this sets. The
3648 /// accessibility tree is marked here, because the scale is the root
3649 /// node's transform (AccessKit wants physical coordinates, the tree emits
3650 /// logical ones): dragging a window between a 1x and a 2x monitor would
3651 /// otherwise leave every reported rectangle at the old display's scale.
3652 pub fn set_device_scale_factor(&mut self, scale_factor: f32) {
3653 if self.device_scale_factor != scale_factor {
3654 self.device_scale_factor = scale_factor;
3655 self.device_scale_signal.set(scale_factor);
3656 self.a11y_dirty = true;
3657 }
3658 }
3659
3660 /// The host window HiDPI device scale most recently set (1.0 by default).
3661 pub fn device_scale_factor(&self) -> f32 {
3662 self.device_scale_factor
3663 }
3664
3665 /// Reactive handle on [`Self::device_scale_factor`]. A scale change
3666 /// relayouts nothing by itself; a widget whose layout or placement reads
3667 /// `LayoutContext::scale_factor` binds this at `BindingLevel::Relayout`.
3668 pub fn device_scale_signal(&self) -> crate::signal::Signal<f32> {
3669 self.device_scale_signal.clone()
3670 }
3671
3672 /// Set the waker content updated off the UI thread uses to wake this
3673 /// tree's window (see [`teksilo_canvas::wake`]). teksilo-app installs each
3674 /// window's before its root widget is built, so a source attached in
3675 /// `build()` already has it. `None`, the default, wakes nobody: a headless
3676 /// tree renders when its owner says so.
3677 pub fn set_redraw_waker(
3678 &mut self,
3679 waker: Option<std::sync::Arc<dyn teksilo_canvas::wake::RedrawWaker>>,
3680 ) {
3681 self.off_thread.set_waker(waker);
3682 }
3683
3684 /// The waker [`set_redraw_waker`](Self::set_redraw_waker) installed.
3685 #[doc(hidden)]
3686 pub fn redraw_waker(&self) -> Option<&std::sync::Arc<dyn teksilo_canvas::wake::RedrawWaker>> {
3687 self.off_thread.waker()
3688 }
3689
3690 /// Report the host window's platform safe-area insets — the region the
3691 /// window owns but a person cannot fully see or touch (a display cutout, a
3692 /// rounded corner, a home indicator).
3693 ///
3694 /// Fed by `teksilo-app` from
3695 /// `teksilo_platform::safe_area`, which reads the window on macOS and
3696 /// answers `ZERO` everywhere else because no other desktop platform
3697 /// reports one. Overlays clamp into what is left; the root layout
3698 /// proposal is deliberately **not** shrunk — a safe area moves what floats
3699 /// over the content, not the content.
3700 pub fn set_safe_area(&mut self, insets: teksilo_canvas::EdgeInsets) {
3701 if self.safe_area != insets {
3702 self.safe_area = insets;
3703 // Overlay placement is recomputed from scratch by every layout
3704 // pass, so the change reaches the screen as soon as one runs; the
3705 // frame request is what guarantees one does.
3706 self.request_frame();
3707 }
3708 }
3709
3710 /// The safe-area insets most recently set (`ZERO` by default).
3711 pub fn safe_area(&self) -> teksilo_canvas::EdgeInsets {
3712 self.safe_area
3713 }
3714
3715 /// Report a rectangle of the window currently covered from outside the
3716 /// tree — a soft keyboard, a platform IME candidate window — in
3717 /// window-logical pixels, or `None` when nothing covers it.
3718 ///
3719 /// A **rectangle**, not a named edge, because that is what a platform
3720 /// reports and because the placement code resolves it by keeping the
3721 /// largest free slab rather than by insetting an edge: a keyboard at the
3722 /// bottom gives the band above it, a candidate window at a side gives the
3723 /// band beside it, and neither needs the platform to say which edge it
3724 /// came from.
3725 ///
3726 /// Scope: like the safe area, this reaches **overlay placement only**. The
3727 /// root layout proposal keeps the whole window, so a scroll container
3728 /// still extends behind the keyboard and nothing reflows when one rises —
3729 /// which is what the desktop convention wants, and what keeps a keyboard
3730 /// appearing from being a full relayout of the document. Bringing a
3731 /// focused field out from behind the band is a scroll, against
3732 /// [`usable_viewport`](Self::usable_viewport), not a resize.
3733 pub fn set_occluded_inset(&mut self, occluded: Option<Rect>) {
3734 if self.occluded_inset != occluded {
3735 self.occluded_inset = occluded;
3736 self.request_frame();
3737 }
3738 }
3739
3740 /// The occluding rectangle most recently set (`None` by default).
3741 pub fn occluded_inset(&self) -> Option<Rect> {
3742 self.occluded_inset
3743 }
3744
3745 /// The viewport overlays are placed into: the last laid-out window size,
3746 /// less the safe area, less anything covering it.
3747 ///
3748 /// The same rectangle `position_overlays` clamps into, exposed so a
3749 /// consumer that must put something *in front of* a keyboard — a
3750 /// scroll-into-view for the focused field — can ask for it rather than
3751 /// re-deriving it.
3752 pub fn usable_viewport(&self) -> Rect {
3753 let proposal = self.last_proposal();
3754 let size = teksilo_canvas::Size::new(
3755 proposal.width.unwrap_or(0.0),
3756 proposal.height.unwrap_or(0.0),
3757 );
3758 self.overlay_viewport_for(size)
3759 .usable(self.layout_direction)
3760 }
3761
3762 /// Build the overlay viewport for a window of `size`, folding in the
3763 /// safe area and the occluding rectangle.
3764 pub(crate) fn overlay_viewport_for(
3765 &self,
3766 size: teksilo_canvas::Size,
3767 ) -> crate::overlay::OverlayViewport {
3768 crate::overlay::OverlayViewport::new(size)
3769 .with_safe_area(self.safe_area)
3770 .with_occluded(self.occluded_inset)
3771 }
3772
3773 /// Ask the platform to show (`true`) or hide (`false`) its on-screen
3774 /// keyboard.
3775 ///
3776 /// Recorded here rather than pushed straight at the window because the one
3777 /// thing the request must not do is re-assert IME allowance while a
3778 /// composition is live, and the IME-allowance state lives in the app
3779 /// layer's per-window reconcile. `teksilo-app` takes the request once per
3780 /// dispatch, after that reconcile, and applies it against the platform's
3781 /// [`SoftKeyboardSupport`](crate::window::SoftKeyboardSupport) answer.
3782 pub fn request_soft_keyboard(&mut self, visible: bool) {
3783 self.soft_keyboard_request = Some(visible);
3784 }
3785
3786 /// Take the pending soft-keyboard request, if any. Called by the app layer
3787 /// once per dispatch.
3788 pub fn take_soft_keyboard_request(&mut self) -> Option<bool> {
3789 self.soft_keyboard_request.take()
3790 }
3791
3792 /// Mark a widget as clipping its children to its bounds (scroll areas).
3793 pub fn set_clips_children(&mut self, id: WidgetId, clips: bool) {
3794 self.arena.set_clips_children(id, clips);
3795 }
3796
3797 /// Apply a `HandlerSet` to an existing node in the arena, routed
3798 /// into the rebuild-cleared `handlers` slot (the widget's own
3799 /// self-applied handlers).
3800 /// Register any *bound* builder-level accessibility Props
3801 /// (`access_hidden` / `access_label` / `access_description` /
3802 /// `access_value`) at `BindingLevel::AccessibilityOnly`, so that a change
3803 /// to the underlying signal flips `a11y_dirty` and the AccessKit tree
3804 /// re-walks — re-resolving the announced hidden-state / name / description
3805 /// / value — without a visual relayout. Static Props are ignored by
3806 /// `register_if_bound`. Takes the registry explicitly (rather than `&self`)
3807 /// so insertion-path callers can keep a disjoint `&mut self.arena` borrow
3808 /// on the node alive.
3809 fn register_access_prop_bindings(
3810 access: &crate::widget_builder::AccessibilityOverrides,
3811 id: WidgetId,
3812 registry: &crate::binding::BindingRegistry,
3813 ) {
3814 use crate::binding::BindingLevel::AccessibilityOnly;
3815 if let Some(p) = access.hidden.as_ref() {
3816 p.register_if_bound(id, registry, AccessibilityOnly);
3817 }
3818 if let Some(p) = access.label.as_ref() {
3819 p.register_if_bound(id, registry, AccessibilityOnly);
3820 }
3821 if let Some(p) = access.description.as_ref() {
3822 p.register_if_bound(id, registry, AccessibilityOnly);
3823 }
3824 if let Some(p) = access.value.as_ref() {
3825 p.register_if_bound(id, registry, AccessibilityOnly);
3826 }
3827 }
3828
3829 pub(crate) fn apply_self_handler_set(
3830 &mut self,
3831 id: WidgetId,
3832 mut handler_set: crate::widget_builder::HandlerSet,
3833 ) {
3834 // `visible_when` needs the binding registry (which the arena lacks), so
3835 // pull it out here and apply it via `self.visible_when` after.
3836 let visible_when = handler_set.visible_when.take();
3837 // Same reason for the reactive access Props: the arena can't reach the
3838 // registry, so register them here before handing the set to the arena.
3839 if let Some(access) = handler_set.access.as_ref() {
3840 Self::register_access_prop_bindings(access, id, &self.binding_registry);
3841 }
3842 self.arena
3843 .apply_handler_set(id, handler_set, crate::arena::HandlerScope::Own);
3844 if let Some(prop) = visible_when {
3845 self.visible_when(id, prop);
3846 }
3847 }
3848
3849 /// Apply a `HandlerSet` to an existing node as *external* handlers —
3850 /// the kind attached by a composing parent via
3851 /// `BuildContext::apply_handlers(child_id, ...)` or by the
3852 /// `WidgetBuilder` chain at insertion time. These persist across
3853 /// the target widget's own rebuilds.
3854 pub(crate) fn apply_external_handler_set(
3855 &mut self,
3856 id: WidgetId,
3857 mut handler_set: crate::widget_builder::HandlerSet,
3858 ) {
3859 // See `apply_self_handler_set`: route `visible_when` and the reactive
3860 // access Props through the registry (the arena can't reach it).
3861 let visible_when = handler_set.visible_when.take();
3862 if let Some(access) = handler_set.access.as_ref() {
3863 Self::register_access_prop_bindings(access, id, &self.binding_registry);
3864 }
3865 self.arena
3866 .apply_handler_set(id, handler_set, crate::arena::HandlerScope::External);
3867 if let Some(prop) = visible_when {
3868 self.visible_when(id, prop);
3869 }
3870 }
3871
3872 /// Append an accessibility `labelled_by` relation onto an already-mounted
3873 /// node, *preserving* any overrides the widget already carries — unlike
3874 /// `apply_external_handler_set`, which replaces the whole override struct.
3875 /// Used by container widgets (e.g. `FormLayout`) to name a field after its
3876 /// label once both ids are known. Idempotent: re-adding the same target is
3877 /// a no-op, so a composite may re-register the relation on every rebuild.
3878 ///
3879 /// Both ends are resolved through layout wrappers first (see
3880 /// [`labelled_field_end`](Self::labelled_field_end) and
3881 /// [`labelled_label_end`](Self::labelled_label_end)), because the
3882 /// container only knows the ids it was handed, and a `FixedSize` or a
3883 /// `VStack` around a field or a label is a node no reader keeps.
3884 pub(crate) fn push_access_labelled_by(&mut self, id: WidgetId, label_id: WidgetId) {
3885 let id = self.labelled_field_end(id);
3886 let label_id = self.labelled_label_end(label_id);
3887 if let Some(node) = self.arena.get_mut(id) {
3888 let overrides = node.access_overrides.get_or_insert_with(|| {
3889 Box::new(crate::widget_builder::AccessibilityOverrides::default())
3890 });
3891 // A composite that names itself from its content re-registers the
3892 // relation on every rebuild. Appending blindly would concatenate the
3893 // title into the name once per rebuild.
3894 if overrides.labelled_by.contains(&label_id) {
3895 return;
3896 }
3897 overrides.labelled_by.push(label_id);
3898 self.a11y_dirty = true;
3899 }
3900 }
3901
3902 /// The node a `labelled_by` relation pushed onto `id` should sit on.
3903 ///
3904 /// `id` itself when it holds focus or hands its node to a proxy
3905 /// ([`Widget::accessibility_proxy`]),
3906 /// or when its own node is one a reader keeps. Otherwise `id` is a layout
3907 /// wrapper the consumer prunes, and a relation on it names nothing; the
3908 /// relation goes to the one control inside it instead: the outermost
3909 /// descendant that holds focus or has a proxy, so a composite such as a
3910 /// `DateEdit` takes it and hands it on to its field at walk time, and a
3911 /// rebuild of the composite's inside does not strand it. With no such
3912 /// control, or several (a field and a browse button), `id` is kept and
3913 /// nothing is guessed. Only descendants already built are found.
3914 fn labelled_field_end(&self, id: WidgetId) -> WidgetId {
3915 // A composite asking about itself from its own `build()` is a
3916 // placeholder in the arena at that moment: its node and proxy are
3917 // unknown, so the id stays as it is.
3918 if self.is_mid_build(id) {
3919 return id;
3920 }
3921 let speaks = |w: WidgetId| {
3922 self.arena
3923 .get(w)
3924 .is_some_and(|node| self.is_node_focusable(node))
3925 || self.live_accessibility_proxy(w).is_some()
3926 };
3927 if !self.arena.is_active(id) || speaks(id) || !self.is_pruned_wrapper(id) {
3928 return id;
3929 }
3930 let found = self.outermost_descendants(id, speaks);
3931 match found.as_slice() {
3932 [only] => *only,
3933 _ => id,
3934 }
3935 }
3936
3937 /// The node a `labelled_by` relation should point at to name something
3938 /// with `label_id`.
3939 ///
3940 /// `label_id` itself when its node has a name or a value to give (see
3941 /// `has_name_to_give`). Otherwise, the one descendant that has: a label
3942 /// text inside a `FixedSize` or a `Padding`. With none, or several,
3943 /// `label_id` is kept.
3944 fn labelled_label_end(&self, label_id: WidgetId) -> WidgetId {
3945 if self.is_mid_build(label_id) {
3946 return label_id;
3947 }
3948 // A label that is a node a reader keeps (a control, a group) is
3949 // pointed at as it is, named or not: only a layout wrapper is seen
3950 // through, never into a control's parts.
3951 if !self.arena.is_active(label_id)
3952 || self.has_name_to_give(label_id)
3953 || !self.is_pruned_wrapper(label_id)
3954 {
3955 return label_id;
3956 }
3957 let found = self.outermost_descendants(label_id, |w| self.has_name_to_give(w));
3958 match found.as_slice() {
3959 [only] => *only,
3960 _ => label_id,
3961 }
3962 }
3963
3964 /// Whether `id` is being built right now: its widget is out of the arena,
3965 /// a placeholder in its place.
3966 fn is_mid_build(&self, id: WidgetId) -> bool {
3967 self.arena
3968 .get(id)
3969 .is_some_and(|node| node.widget.type_name().ends_with("PlaceholderWidget"))
3970 }
3971
3972 /// Whether `id`'s own node is one the consumer drops: a
3973 /// `GenericContainer` or `Unknown` role with no name and no value.
3974 fn is_pruned_wrapper(&self, id: WidgetId) -> bool {
3975 use accesskit::Role;
3976 let builder = self.build_overridden_builder(id);
3977 let empty = |s: Option<&str>| s.is_none_or(|s| s.trim().is_empty());
3978 matches!(builder.role(), Role::GenericContainer | Role::Unknown)
3979 && empty(builder.name())
3980 && empty(builder.value())
3981 }
3982
3983 /// The active strict descendants of `id` that match `hit`, without
3984 /// descending into one once found, in document order.
3985 fn outermost_descendants(&self, id: WidgetId, hit: impl Fn(WidgetId) -> bool) -> Vec<WidgetId> {
3986 let mut found = Vec::new();
3987 let mut stack: Vec<WidgetId> = self.arena.children(id).iter().rev().copied().collect();
3988 while let Some(w) = stack.pop() {
3989 if !self.arena.is_active(w) {
3990 continue;
3991 }
3992 if hit(w) {
3993 found.push(w);
3994 continue;
3995 }
3996 stack.extend(self.arena.children(w).iter().rev().copied());
3997 }
3998 found
3999 }
4000
4001 /// Append an accessibility `described_by` relation onto an already-mounted
4002 /// node, preserving existing overrides (the `described_by` counterpart of
4003 /// [`push_access_labelled_by`](Self::push_access_labelled_by)).
4004 pub(crate) fn push_access_described_by(&mut self, id: WidgetId, target_id: WidgetId) {
4005 if let Some(node) = self.arena.get_mut(id) {
4006 let overrides = node.access_overrides.get_or_insert_with(|| {
4007 Box::new(crate::widget_builder::AccessibilityOverrides::default())
4008 });
4009 if overrides.described_by.contains(&target_id) {
4010 return;
4011 }
4012 overrides.described_by.push(target_id);
4013 self.a11y_dirty = true;
4014 }
4015 }
4016
4017 /// Set a per-child alignment override on a widget.
4018 pub fn set_alignment(&mut self, id: WidgetId, alignment: teksilo_tokens::Alignment) {
4019 self.arena.set_alignment_override(id, alignment);
4020 }
4021
4022 /// Get the binding registry for registering State→Widget bindings.
4023 pub fn binding_registry(&self) -> &crate::binding::BindingRegistry {
4024 &self.binding_registry
4025 }
4026
4027 /// Shared access to the shortcut registry. Widgets register their
4028 /// default shortcuts through here during `build()` (via
4029 /// `BuildContext::register_shortcut`); settings UIs and
4030 /// persistence layers read and mutate overrides directly.
4031 pub fn shortcut_registry(&self) -> &crate::shortcut::ShortcutRegistry {
4032 &self.shortcut_registry
4033 }
4034
4035 pub fn shortcut_registry_mut(&mut self) -> &mut crate::shortcut::ShortcutRegistry {
4036 &mut self.shortcut_registry
4037 }
4038
4039 /// Install a one-shot key-capture callback, returning a
4040 /// [`CaptureHandle`](crate::shortcut::CaptureHandle) whose `Drop`
4041 /// cancels the capture if it hasn't already fired. The next
4042 /// `KeyDown` the tree receives bypasses shortcut-registry lookup
4043 /// and invokes the callback with:
4044 /// - the captured [`KeyStroke`](crate::shortcut::KeyStroke)
4045 /// - mutable access to the registry (rebind in-place)
4046 /// - a mutable [`EventContext`] (so the handler can also emit
4047 /// commands, send intents, dismiss overlays, …)
4048 ///
4049 /// Calling this while a previous capture is armed creates a
4050 /// **separate** slot; the prior handle, when eventually dropped,
4051 /// cancels only its own (now-orphaned) slot. The new capture
4052 /// wins.
4053 pub fn begin_key_capture(
4054 &mut self,
4055 callback: impl FnOnce(
4056 crate::shortcut::KeyStroke,
4057 &mut crate::shortcut::ShortcutRegistry,
4058 &mut EventContext,
4059 ) + 'static,
4060 ) -> crate::shortcut::CaptureHandle {
4061 let slot: crate::shortcut::KeyCaptureSlot =
4062 std::rc::Rc::new(std::cell::RefCell::new(Some(Box::new(callback))));
4063 self.key_capture = Some(slot.clone());
4064 crate::shortcut::CaptureHandle::new(slot)
4065 }
4066
4067 /// Cancel any currently-armed key capture without invoking it.
4068 /// Equivalent to dropping the [`CaptureHandle`](crate::shortcut::CaptureHandle),
4069 /// but exposed here so callers that lost the handle (or never
4070 /// kept one) can still bail out.
4071 pub fn cancel_key_capture(&mut self) {
4072 if let Some(slot) = self.key_capture.take() {
4073 slot.borrow_mut().take();
4074 }
4075 }
4076
4077 /// Whether a key-capture callback is currently armed.
4078 pub fn is_capturing_keys(&self) -> bool {
4079 self.key_capture
4080 .as_ref()
4081 .map(|slot| slot.borrow().is_some())
4082 .unwrap_or(false)
4083 }
4084
4085 /// Consume any pending key-capture callback. Used internally by
4086 /// the dispatch path — returns the boxed closure so the caller
4087 /// can invoke it once the KeyStroke has been constructed. Also
4088 /// drops the outer `Option<Rc<...>>` so `is_capturing_keys` goes
4089 /// back to `false`.
4090 pub(crate) fn take_key_capture(&mut self) -> Option<crate::shortcut::KeyCaptureCallback> {
4091 let slot = self.key_capture.take()?;
4092 slot.borrow_mut().take()
4093 }
4094
4095 /// Append an [`Action`](crate::action::Action) to a widget's arena
4096 /// node. Invoked by `BuildContext::register_action`; not meant
4097 /// to be called directly.
4098 /// Record that `widget_id` edits text. Replaces any previous registration
4099 /// from the same widget, so a rebuild re-points rather than accumulating.
4100 pub(crate) fn push_text_surface(
4101 &mut self,
4102 widget_id: WidgetId,
4103 surface: std::rc::Rc<dyn crate::text_surface::TextSurface>,
4104 ) {
4105 self.text_surfaces.insert(widget_id, surface);
4106 }
4107
4108 /// A cloneable view of this tree's text surfaces, for a caller that must ask
4109 /// the question later, without a `&WidgetTree` in hand.
4110 ///
4111 /// What a host hands a window's platform text-input bridge, which the
4112 /// platform calls back while no tree is in reach: it answers for the
4113 /// focused widget with
4114 /// [`TextSurfaces::with_focused_input_document`](crate::text_surface::TextSurfaces::with_focused_input_document).
4115 pub fn text_surfaces(&self) -> crate::text_surface::TextSurfaces {
4116 self.text_surfaces.clone()
4117 }
4118
4119 /// The text-editing widget that currently holds the keyboard focus.
4120 ///
4121 /// `None` when focus is elsewhere — or nowhere — which is exactly what a
4122 /// host needs in order to know that a text chord is safe to route itself.
4123 pub fn focused_text_surface(
4124 &self,
4125 ) -> Option<std::rc::Rc<dyn crate::text_surface::TextSurface>> {
4126 self.text_surfaces.focused()
4127 }
4128
4129 /// Is the keyboard focus inside a widget that edits text?
4130 ///
4131 /// The cheap half of [`focused_text_surface`](Self::focused_text_surface),
4132 /// for a host that only needs to decide whether to step aside.
4133 pub fn focused_is_text_surface(&self) -> bool {
4134 self.text_surfaces.focused_is_text_surface()
4135 }
4136
4137 pub(crate) fn push_action(&mut self, widget_id: WidgetId, action: crate::action::Action) {
4138 if let Some(node) = self.arena.get_mut(widget_id) {
4139 node.actions.push(action);
4140 }
4141 }
4142
4143 /// Telemetry dispatch tap. Looks up a registered
4144 /// [`crate::telemetry::TelemetryContext`] in `app_state` and emits
4145 /// an `intent.dispatched` event with the intent's name. No-op when
4146 /// no telemetry is configured. Errors and consent gating are
4147 /// handled inside the reporter — this site only needs to call
4148 /// `record`.
4149 fn tap_intent_dispatched(&self, intent: &crate::intent::Intent) {
4150 let Some(tcx) = self
4151 .app_context()
4152 .app_state::<crate::telemetry::TelemetryContext>()
4153 else {
4154 return;
4155 };
4156 let install_id = tcx.reporter.install_id();
4157 let props = [
4158 crate::telemetry::Prop {
4159 key: "name",
4160 value: crate::telemetry::PropValue::StaticStr(intent.name),
4161 },
4162 crate::telemetry::Prop {
4163 key: "source",
4164 value: crate::telemetry::PropValue::Enum {
4165 variant: intent.source.as_str(),
4166 },
4167 },
4168 ];
4169 let event = crate::telemetry::Event {
4170 name: "intent.dispatched",
4171 category: crate::telemetry::EventCategory::Intent,
4172 timestamp: std::time::SystemTime::now(),
4173 install_id,
4174 session_id: &tcx.session_id,
4175 schema_version: tcx.schema_version,
4176 props: &props,
4177 };
4178 tcx.reporter.record(&event);
4179 }
4180
4181 /// Histogram of widget concrete-type names across the active
4182 /// arena. Used by the `widget.census` telemetry emitter to surface
4183 /// "which widgets does this app actually use" data back to the
4184 /// framework. Keyed by
4185 /// `std::any::type_name::<T>()` of the concrete widget — a
4186 /// dotted, fully-qualified path like
4187 /// `teksilo_widgets::button::Button`.
4188 ///
4189 /// `&'static str` keys: `type_name_of_val` returns a
4190 /// compile-time string, so the histogram preserves the static
4191 /// lifetime all the way to the wire-format prop. This avoids
4192 /// any allocation for the type-name strings themselves.
4193 ///
4194 /// Cost: one `Box<dyn Widget>` indirection per active node plus
4195 /// a `HashMap` insert. Sub-millisecond on arenas with thousands
4196 /// of widgets. Safe to call every frame in tests; in production
4197 /// gate behind a periodic ticker (hourly or on-idle).
4198 pub fn widget_type_histogram(&self) -> std::collections::HashMap<&'static str, u32> {
4199 let mut out = std::collections::HashMap::<&'static str, u32>::new();
4200 for id in self.arena.active_ids_iter() {
4201 if let Some(node) = self.arena.get(id) {
4202 // `Widget::type_name` is monomorphized per impl, so
4203 // calling through the vtable correctly resolves to
4204 // the concrete type — `type_name_of_val(&*widget)`
4205 // alone would collapse to `"dyn teksilo_core::widget::Widget"`.
4206 let name: &'static str = node.widget.type_name();
4207 *out.entry(name).or_insert(0) += 1;
4208 }
4209 }
4210 out
4211 }
4212
4213 /// Number of active widgets in the arena. Cheap; matches the
4214 /// totals returned by `widget_type_histogram` when summed.
4215 pub fn active_widget_count(&self) -> usize {
4216 self.arena.active_ids_iter().count()
4217 }
4218
4219 /// Enqueue an intent for dispatch from `source`. Called from
4220 /// `collect_from_ctx` after a handler runs `ctx.send_intent(...)`
4221 /// and from the KeyDown shortcut-interception path.
4222 ///
4223 /// The overlays the walk from `source` crosses are recorded now, so
4224 /// the intent still reaches the widget an overlay is attached to when
4225 /// the handler that sent it also closed that overlay.
4226 pub(crate) fn enqueue_intent(
4227 &mut self,
4228 source: WidgetId,
4229 intent: crate::intent::Intent,
4230 propagate_when_disabled: bool,
4231 ) {
4232 let crossings = self.intent_route(source, &[], true).crossings;
4233 self.enqueue_intent_crossing(source, intent, propagate_when_disabled, crossings);
4234 }
4235
4236 /// [`enqueue_intent`](Self::enqueue_intent) with the overlay crossings
4237 /// recorded earlier, before the overlays they name were closed.
4238 pub(crate) fn enqueue_intent_crossing(
4239 &mut self,
4240 source: WidgetId,
4241 intent: crate::intent::Intent,
4242 propagate_when_disabled: bool,
4243 crossings: Vec<OverlayCrossing>,
4244 ) {
4245 let mut intent = intent;
4246 if let Some(routed) = self.routed_crossings {
4247 intent.note_crossings(routed);
4248 }
4249 self.pending_intents.push(PendingIntent {
4250 source,
4251 intent,
4252 propagate_when_disabled,
4253 crossings,
4254 });
4255 }
4256
4257 /// The widgets an intent sent from `source` walks through, `source`
4258 /// first, the overlays the walk crosses on the way (with the open modal
4259 /// it stopped at, if any), and the content of that modal.
4260 ///
4261 /// From a widget the walk goes to its parent. From the content root of
4262 /// an open overlay, which has none, it goes on to the widget the overlay
4263 /// is attached to (its [anchor](crate::overlay::OverlayRequest::anchor)),
4264 /// so a menu row or a popover's button reaches the actions of the
4265 /// widget the popup belongs to and of its ancestors, up to
4266 /// the window's root; nested overlays are crossed the same way (a
4267 /// submenu's anchor is a row of its parent menu). A content root whose
4268 /// overlay has closed is crossed by `recorded`, the crossings noted when
4269 /// the intent was sent. The anchor, not the widget focus goes back to
4270 /// when the overlay closes: that one may be unrelated to the popup (a
4271 /// context menu opened on a row while a search field has focus), and an
4272 /// overlay that took no focus has none.
4273 ///
4274 /// The walk stops at a root with no overlay, at a widget it has already
4275 /// passed (an overlay attached to a widget of its own content), and at
4276 /// the content of an open [modal](crate::overlay::OverlayPlacement::is_modal)
4277 /// overlay (a dialog in the window, a command palette), which goes first
4278 /// while it is open, as a native modal window does: its own actions take
4279 /// what is sent inside it, then of the window-global actions those
4280 /// registered inside it ([`global_applies_after`](Self::global_applies_after)), and
4281 /// only what they leave goes on to the page
4282 /// ([`intent_route`](Self::intent_route)). Its crossing is recorded, to
4283 /// where its leftovers go on from
4284 /// ([`modal_resume_point`](Self::modal_resume_point)), so an intent sent
4285 /// as the modal closes (a dialog's button closing the dialog, then asking
4286 /// the page for something) walks on from there once it has closed, as
4287 /// one it leaves while open does.
4288 pub(crate) fn intent_walk(
4289 &self,
4290 source: WidgetId,
4291 recorded: &[OverlayCrossing],
4292 ) -> (Vec<WidgetId>, Vec<OverlayCrossing>, Option<WidgetId>) {
4293 let mut chain = vec![source];
4294 let mut crossings = Vec::new();
4295 let mut modal = None;
4296 let mut current = source;
4297 loop {
4298 let next = match self.arena.parent(current) {
4299 Some(parent) => parent,
4300 None => {
4301 let open = self
4302 .overlay_manager
4303 .find_by_content(current)
4304 .and_then(|id| self.overlay_manager.overlay(id));
4305 // An open modal ends this walk, as a native modal window's
4306 // tree ends; its crossing is noted for the route on to
4307 // the page, and for when it has closed.
4308 if let Some(overlay) = open.filter(|overlay| overlay.placement.is_modal()) {
4309 crossings.push(OverlayCrossing {
4310 content: current,
4311 anchor: self.modal_resume_point(overlay),
4312 });
4313 modal = Some(current);
4314 break;
4315 }
4316 let anchor = open.map(|overlay| overlay.anchor).or_else(|| {
4317 recorded
4318 .iter()
4319 .find(|crossing| crossing.content == current)
4320 .map(|crossing| crossing.anchor)
4321 });
4322 let Some(anchor) = anchor else { break };
4323 crossings.push(OverlayCrossing {
4324 content: current,
4325 anchor,
4326 });
4327 anchor
4328 }
4329 };
4330 // Only a crossing can lead back into the chain; a tree's own
4331 // parent links cannot.
4332 if !crossings.is_empty() && chain.contains(&next) {
4333 break;
4334 }
4335 chain.push(next);
4336 current = next;
4337 }
4338 (chain, crossings, modal)
4339 }
4340
4341 /// Where what an open modal leaves goes on to the page from: the widget
4342 /// it is attached to; when that one is not up any more (a row of the
4343 /// closed menu that opened the dialog), the widget focus goes back to
4344 /// when it closes; else the [content root](Self::set_content_root).
4345 fn modal_resume_point(&self, overlay: &crate::overlay::ActiveOverlay) -> WidgetId {
4346 [Some(overlay.anchor), overlay.focus_restore]
4347 .into_iter()
4348 .flatten()
4349 .find(|id| self.arena.is_active(*id))
4350 .or_else(|| self.intent_anchor())
4351 .unwrap_or(overlay.anchor)
4352 }
4353
4354 /// The way an intent sent from `source` goes: the [walk](Self::intent_walk)
4355 /// from `source`, and, while `past_modals`, from each open modal it stops
4356 /// at, a further walk from where the modal's leftovers go on
4357 /// ([`modal_resume_point`](Self::modal_resume_point)): a dialog opened
4358 /// over the page leaves the page what it does not take, and a dialog
4359 /// opened over another leaves it to that one first. A key's intent stays
4360 /// in the first modal (`past_modals` false), as a key pressed in a modal
4361 /// window reaches nothing of the window it blocks, and so does a row of
4362 /// the native menu bar's
4363 /// ([`Intent::kept_in_modal`](crate::intent::Intent::kept_in_modal)). The route stops where
4364 /// it would walk again through a widget it has passed.
4365 pub(crate) fn intent_route(
4366 &self,
4367 source: WidgetId,
4368 recorded: &[OverlayCrossing],
4369 past_modals: bool,
4370 ) -> IntentRoute {
4371 let mut route = IntentRoute {
4372 legs: Vec::new(),
4373 crossings: Vec::new(),
4374 };
4375 let mut start = source;
4376 loop {
4377 let (chain, crossings, modal) = self.intent_walk(start, recorded);
4378 route.crossings.extend(crossings);
4379 route.legs.push(IntentLeg { chain, modal });
4380 if modal.is_none() || !past_modals {
4381 break;
4382 }
4383 // The last crossing is the modal's, to where its leftovers go.
4384 let Some(next) = route.crossings.last().map(|crossing| crossing.anchor) else {
4385 break;
4386 };
4387 if route.legs.iter().any(|leg| leg.chain.contains(&next)) {
4388 break;
4389 }
4390 start = next;
4391 }
4392 route
4393 }
4394
4395 /// The content of the first open modal on the walk from `owner`, if any:
4396 /// the modal a window-global action or shortcut registered by `owner`
4397 /// belongs to.
4398 fn modal_of(&self, owner: WidgetId) -> Option<WidgetId> {
4399 self.intent_walk(owner, &[]).2
4400 }
4401
4402 /// Whether a window-global shortcut registered by `owner` applies to a
4403 /// key whose walk stopped at the modal `modal`: always with no modal, and
4404 /// otherwise only when `owner` sits inside that modal (on the walk from
4405 /// `owner`, which crosses popovers opened inside it). A native modal
4406 /// window's tree has the shortcuts of its own widgets and none of the
4407 /// window it blocks; an in-tree modal behaves the same for keys. An
4408 /// intent goes on past the modal ([`intent_route`](Self::intent_route)).
4409 ///
4410 /// Not asked for the tree's own shortcuts (the standard edits), which
4411 /// apply in a modal whoever re-registered them
4412 /// (`select_shortcut_for_focus`).
4413 pub(crate) fn global_applies(&self, owner: WidgetId, modal: Option<WidgetId>) -> bool {
4414 modal.is_none_or(|modal| self.modal_of(owner) == Some(modal))
4415 }
4416
4417 /// The window-global actions an intent on `route` is offered after the
4418 /// walk `leg` (an index into `route.legs`): those registered inside the
4419 /// modal the leg stopped at; after the last leg, unless the route ends at
4420 /// a modal, every one not offered yet (all of them for a route with no
4421 /// modal on its way).
4422 fn global_applies_after(&self, owner: WidgetId, route: &IntentRoute, leg: usize) -> bool {
4423 let owner_modal = self.modal_of(owner);
4424 match route.legs[leg].modal {
4425 Some(modal) if owner_modal == Some(modal) => true,
4426 _ if leg + 1 < route.legs.len() || route.ends_at_a_modal() => false,
4427 _ => owner_modal.is_none_or(|owner_modal| !route.modals().any(|m| m == owner_modal)),
4428 }
4429 }
4430
4431 /// Dispatch every queued intent. Handlers may call
4432 /// `ctx.send_intent(...)` to enqueue more; the loop consumes
4433 /// those too until the queue drains. No ordering guarantee
4434 /// beyond "first-enqueued is first-dispatched"; the `pop` path
4435 /// uses `remove(0)` to keep that FIFO behavior.
4436 ///
4437 /// With [`set_records_unclaimed_intents`](Self::set_records_unclaimed_intents)
4438 /// on, an intent no action took is kept for
4439 /// [`take_unclaimed_intents`](Self::take_unclaimed_intents). One with a
4440 /// shortcut's source is kept on the shortcut's terms
4441 /// ([`keeps_unclaimed`](Self::keeps_unclaimed)): only when the
4442 /// application tree takes it. Shortcuts do not dispatch through this
4443 /// drain; the check covers an intent re-sent with the shortcut's source.
4444 pub(crate) fn drain_pending_intents(&mut self, ops: &mut dyn crate::window::WindowOps) {
4445 while !self.pending_intents.is_empty() {
4446 let PendingIntent {
4447 source,
4448 intent,
4449 propagate_when_disabled,
4450 crossings,
4451 } = self.pending_intents.remove(0);
4452 let intent = self.sent_here(intent);
4453 let keep = self.keeps_unclaimed(&intent).then(|| intent.clone());
4454 let consumed = self.dispatch_intent_with(
4455 source,
4456 intent,
4457 propagate_when_disabled,
4458 &mut *ops,
4459 true,
4460 &crossings,
4461 );
4462 if !consumed && let Some(intent) = keep {
4463 self.keep_unclaimed(intent, &mut *ops);
4464 }
4465 }
4466 }
4467
4468 /// Whether `intent`, once no action of this tree takes it, is kept for
4469 /// [`take_unclaimed_intents`](Self::take_unclaimed_intents): always while
4470 /// recording is on, except a shortcut's. That one is kept only when the
4471 /// [application scope](Self::set_application_scope) takes it; otherwise
4472 /// its key falls through to the focused widget (`Ctrl+C` copies in an
4473 /// editor), and acting on it in another tree as well would run two
4474 /// things for one chord.
4475 pub(crate) fn keeps_unclaimed(&self, intent: &crate::intent::Intent) -> bool {
4476 self.unclaimed_intents.is_some()
4477 && (intent.source != crate::telemetry::IntentSource::Shortcut
4478 || self
4479 .application_scope
4480 .as_ref()
4481 .is_some_and(|scope| scope.takes(intent.name)))
4482 }
4483
4484 /// Keep `intent`, which no action of this tree took, for
4485 /// [`take_unclaimed_intents`](Self::take_unclaimed_intents), with the
4486 /// activation token of the event being dispatched while `ops` still
4487 /// holds it unused, taken from `ops`, so the tree it crosses to can
4488 /// activate a window with it and nothing else uses it twice.
4489 pub(crate) fn keep_unclaimed(
4490 &mut self,
4491 mut intent: crate::intent::Intent,
4492 ops: &mut dyn crate::window::WindowOps,
4493 ) {
4494 if intent.crossings() >= MAX_INTENT_CROSSINGS {
4495 // In every build, once each time a chain reaches the bound (the
4496 // chain ends here): the symptom, a command that runs over and
4497 // over or stops, is the user's in a release build too.
4498 eprintln!(
4499 "teksilo: intent `{}` was not offered to another tree: {MAX_INTENT_CROSSINGS} \
4500 crossings between trees led to it, so two actions in two trees are likely \
4501 answering each other's intents",
4502 intent.name
4503 );
4504 return;
4505 }
4506 if let Some(unclaimed) = self.unclaimed_intents.as_mut() {
4507 intent.note_activation_token(ops.take_activation_token());
4508 unclaimed.push(intent);
4509 }
4510 }
4511
4512 /// `intent`, sent in this tree, with this tree's window noted as
4513 /// [the one it was sent in](crate::intent::Intent::origin_window) unless
4514 /// it names one already.
4515 pub(crate) fn sent_here(&self, mut intent: crate::intent::Intent) -> crate::intent::Intent {
4516 intent.note_origin_window(self.window_state.as_ref().map(|state| state.id()));
4517 intent
4518 }
4519
4520 /// Share `scope`, what the application tree takes, with this tree: a
4521 /// shortcut whose intent nothing in this tree takes is kept for the
4522 /// application tree when the scope takes it, and its key falls through
4523 /// to the focused widget otherwise. `None` (the default) offers no
4524 /// shortcut to the application tree. `teksilo-app` sets one scope on
4525 /// every window's tree.
4526 #[doc(hidden)]
4527 pub fn set_application_scope(&mut self, scope: Option<crate::action::ApplicationScope>) {
4528 self.application_scope = scope;
4529 }
4530
4531 /// Fill `scope` with what this tree, as the application tree, takes:
4532 /// the actions an intent [routed](Self::dispatch_routed_intent) here
4533 /// would be offered (on the walk from the focused widget, or from the
4534 /// content root, to the root, then the global actions), as
4535 /// [`can_handle_from`](Self::can_handle_from) would find them. Call it again
4536 /// whenever this tree may have changed its actions or its focus;
4537 /// `teksilo-app` does each time the application tree has run.
4538 #[doc(hidden)]
4539 pub fn publish_application_scope(&self, scope: &crate::action::ApplicationScope) {
4540 let actions = self
4541 .routed_anchor()
4542 .map(|anchor| {
4543 self.actions_on_route(anchor, &[], true)
4544 .into_iter()
4545 .map(|action| {
4546 (
4547 action.intent,
4548 action.enabled_when.clone(),
4549 action.availability(),
4550 action.pass_on(),
4551 )
4552 })
4553 .collect()
4554 })
4555 .unwrap_or_default();
4556 scope.replace(actions);
4557 }
4558
4559 /// Where an intent routed from another tree starts: the focused widget,
4560 /// else the [content root](Self::set_content_root).
4561 fn routed_anchor(&self) -> Option<WidgetId> {
4562 self.focused
4563 .filter(|id| self.arena.is_active(*id))
4564 .or_else(|| self.intent_anchor())
4565 }
4566
4567 /// The actions an intent sent from `source` is offered, in the order
4568 /// [`dispatch_intent`](Self::dispatch_intent) offers them, along its
4569 /// [route](Self::intent_route): on each active, enabled widget of each
4570 /// walk, the first action of each intent name (a second one for the
4571 /// same name on the same widget is never reached), after a walk stopped
4572 /// at an open modal the window-global actions registered inside it, and
4573 /// last the other window-global actions. `past_modals` false asks for an
4574 /// intent an open modal keeps (a shortcut's, a native menu bar row's),
4575 /// which ends at the first one. Enabled or not, available or not: the
4576 /// caller reads
4577 /// [`Action::is_enabled`](crate::action::Action::is_enabled) (a
4578 /// dispatch's question) or `Action::is_available` (a menu row's) when it
4579 /// needs to.
4580 pub(crate) fn actions_on_route(
4581 &self,
4582 source: WidgetId,
4583 crossings: &[OverlayCrossing],
4584 past_modals: bool,
4585 ) -> Vec<&crate::action::Action> {
4586 let mut actions = Vec::new();
4587 let route = self.intent_route(source, crossings, past_modals);
4588 for (leg, IntentLeg { chain, .. }) in route.legs.iter().enumerate() {
4589 for &id in chain {
4590 if !self.arena.is_active(id) || !self.arena.is_enabled(id) {
4591 continue;
4592 }
4593 let Some(node) = self.arena.get(id) else {
4594 continue;
4595 };
4596 for (index, action) in node.actions.iter().enumerate() {
4597 if node.actions[..index]
4598 .iter()
4599 .all(|earlier| earlier.intent != action.intent)
4600 {
4601 actions.push(action);
4602 }
4603 }
4604 }
4605 actions.extend(
4606 self.global_actions
4607 .iter()
4608 .filter(|(owner, _)| self.global_applies_after(*owner, &route, leg))
4609 .map(|(_, action)| action),
4610 );
4611 }
4612 actions
4613 }
4614
4615 /// Whether an intent named `name`, sent from the focused widget, would be
4616 /// handled, by the same lookup a dispatch makes and without running
4617 /// anything: an enabled action on the walk from the logical focus to the
4618 /// root (crossing from a popup to the widget it is attached to, and from
4619 /// an open modal, after its own actions and the window-global ones
4620 /// registered inside it, on to the page), a window-global one, or, for a
4621 /// window with an [application scope](Self::set_application_scope), one
4622 /// of the application tree's. What a menu row asks to grey itself out.
4623 ///
4624 /// The logical focus is where a command chosen in an in-window menu is
4625 /// sent from: the focused widget, except while focus is in an open menu
4626 /// or popup, where it is the widget the outermost menu of that chain
4627 /// names as its command source, else the one it gives focus back to when
4628 /// it closes (the editor under a menu bar's dropdown, whether a click
4629 /// opened it or F10 did: after F10 focus goes back to the bar's title,
4630 /// but the bar names the editor focused before it as the command
4631 /// source, and a chosen command goes there); the focused widget itself
4632 /// when that one is gone; with nothing focused, the content of the
4633 /// topmost open modal overlay, as if focus were in it, else the
4634 /// [content root](Self::set_content_root). To ask from the focused
4635 /// widget as it is, inside a popup included, as the native menu bar
4636 /// sends, pass [`live_command_focus`](Self::live_command_focus) to
4637 /// [`can_handle_from`](Self::can_handle_from).
4638 ///
4639 /// The answer is the one of the action a dispatch would stop at: the
4640 /// first on the route that is enabled (a disabled one is passed by, as
4641 /// a dispatch passes it) and does not
4642 /// [pass the intent on](crate::action::ActionBuilder::passes_on_when)
4643 /// now (a read-only field's Cut). That action handles it when it
4644 /// [has something to act on](crate::action::ActionBuilder::available_when);
4645 /// when it has not (a text field's `edit.copy` with nothing selected),
4646 /// the intent is not handled, though a page's own Copy further up would
4647 /// be: a Copy chosen there stops at the field, which a dispatch would
4648 /// still run. With no such action on the route, the application tree's
4649 /// answer counts. Two answers are approximate, and say "handled": an
4650 /// action built with
4651 /// [`on_invoke_with_response`](crate::action::ActionBuilder::on_invoke_with_response)
4652 /// that may decline when it runs without saying when, and an application
4653 /// action, as the application tree last published it.
4654 #[doc(hidden)]
4655 pub fn can_handle(&self, name: &str) -> bool {
4656 self.command_focus()
4657 .is_some_and(|source| self.can_handle_from(source, name))
4658 }
4659
4660 /// Every intent name [`can_handle_from`](Self::can_handle_from) answers
4661 /// true for from `source`, sorted, each once: one walk, for a caller
4662 /// that would otherwise ask for many names (the native menu bar's rows),
4663 /// and an answer two turns can compare to see that nothing changed.
4664 #[doc(hidden)]
4665 pub fn handled_intents_from(&self, source: WidgetId) -> Vec<&'static str> {
4666 self.handled_intents_on_route(source, true)
4667 }
4668
4669 /// [`handled_intents_from`](Self::handled_intents_from) for an intent an
4670 /// open modal overlay keeps, as it keeps a key's
4671 /// ([`Intent::kept_in_modal`](crate::intent::Intent::kept_in_modal)):
4672 /// with focus in a dialog presented in the window, what the dialog and
4673 /// the application tree take, none of the page's. What the native menu
4674 /// bar's rows ask, which are input as a key is.
4675 #[doc(hidden)]
4676 pub fn handled_intents_kept_in_modal_from(&self, source: WidgetId) -> Vec<&'static str> {
4677 self.handled_intents_on_route(source, false)
4678 }
4679
4680 fn handled_intents_on_route(&self, source: WidgetId, past_modals: bool) -> Vec<&'static str> {
4681 // Each name is decided by the action a dispatch would stop at.
4682 let mut decided: Vec<(&'static str, bool)> = Vec::new();
4683 for action in self.actions_on_route(source, &[], past_modals) {
4684 if !action.passes_on() && decided.iter().all(|(name, _)| *name != action.intent) {
4685 decided.push((action.intent, action.is_available()));
4686 }
4687 }
4688 // The tree's own focus region commands, when no action decided them.
4689 // Either direction has a target exactly when one region in scope has a
4690 // focusable of its own, so one walk answers both.
4691 let undecided: Vec<&'static str> = [
4692 crate::shortcut::NEXT_REGION,
4693 crate::shortcut::PREVIOUS_REGION,
4694 ]
4695 .into_iter()
4696 .filter(|name| decided.iter().all(|(decided, _)| decided != name))
4697 .collect();
4698 if !undecided.is_empty() && self.region_cycle_target_from(Some(source), true).is_some() {
4699 decided.extend(undecided.into_iter().map(|name| (name, true)));
4700 }
4701 let mut names: Vec<&'static str> = decided
4702 .iter()
4703 .filter_map(|(name, available)| available.then_some(*name))
4704 .collect();
4705 if let Some(scope) = &self.application_scope {
4706 names.extend(
4707 scope
4708 .taken()
4709 .into_iter()
4710 .filter(|name| decided.iter().all(|(decided, _)| decided != name)),
4711 );
4712 }
4713 names.sort_unstable();
4714 names.dedup();
4715 names
4716 }
4717
4718 /// Where an intent sent from focus by a handler outside every overlay
4719 /// (an app callback, an item of the native menu bar) starts: the focused
4720 /// widget as it is, inside an open popup included; with nothing focused,
4721 /// the content of the topmost open modal overlay, else the
4722 /// [content root](Self::set_content_root). Pass it to
4723 /// [`can_handle_from`](Self::can_handle_from) to ask what such an intent
4724 /// would find. [`can_handle`](Self::can_handle) asks from the logical
4725 /// focus instead, where a row of an in-window menu sends from.
4726 #[doc(hidden)]
4727 pub fn live_command_focus(&self) -> Option<WidgetId> {
4728 self.focus_or_modal().or_else(|| self.intent_anchor())
4729 }
4730
4731 /// [`can_handle`](Self::can_handle), for an intent sent from `source`.
4732 #[doc(hidden)]
4733 pub fn can_handle_from(&self, source: WidgetId, name: &str) -> bool {
4734 self.can_handle_on_route(source, name, true)
4735 }
4736
4737 /// [`can_handle_from`](Self::can_handle_from) for an intent an open
4738 /// modal overlay keeps, as
4739 /// [`handled_intents_kept_in_modal_from`](Self::handled_intents_kept_in_modal_from)
4740 /// answers.
4741 #[doc(hidden)]
4742 pub fn can_handle_kept_in_modal_from(&self, source: WidgetId, name: &str) -> bool {
4743 self.can_handle_on_route(source, name, false)
4744 }
4745
4746 fn can_handle_on_route(&self, source: WidgetId, name: &str, past_modals: bool) -> bool {
4747 match self
4748 .actions_on_route(source, &[], past_modals)
4749 .into_iter()
4750 .find(|action| action.intent == name && !action.passes_on())
4751 {
4752 Some(action) => action.is_available(),
4753 None => {
4754 crate::shortcut::region_direction(name).is_some_and(|forward| {
4755 self.region_cycle_target_from(Some(source), forward)
4756 .is_some()
4757 }) || self
4758 .application_scope
4759 .as_ref()
4760 .is_some_and(|scope| scope.offers(name))
4761 }
4762 }
4763 }
4764
4765 /// A signal that says whether an intent named `name` would be handled,
4766 /// as [`can_handle`](Self::can_handle) answers, for widget `id`: a menu
4767 /// row that greys out when nothing on its route takes its command.
4768 ///
4769 /// The tree keeps it current at the start of every layout pass while
4770 /// `id` is active, before the bindings are flushed, so a row bound to it
4771 /// is right on the frame it is first drawn and follows focus, the
4772 /// actions on the route and the application scope from then on. While
4773 /// `id` is dormant (a closed menu) the signal keeps its last value.
4774 /// Asked again for the same widget and name, it returns the same signal;
4775 /// it goes with the widget.
4776 #[doc(hidden)]
4777 pub fn command_available_signal(
4778 &mut self,
4779 id: WidgetId,
4780 name: &'static str,
4781 ) -> crate::signal::Signal<bool> {
4782 if let Some((_, _, signal)) = self
4783 .command_watchers
4784 .iter()
4785 .find(|(watcher, intent, _)| *watcher == id && *intent == name)
4786 {
4787 return signal.clone();
4788 }
4789 let signal = crate::signal::Signal::new(self.can_handle(name));
4790 self.command_watchers.push((id, name, signal.clone()));
4791 signal
4792 }
4793
4794 /// Bring every active widget's
4795 /// [`command_available_signal`](Self::command_available_signal) in line
4796 /// with what [`can_handle`](Self::can_handle) answers now, and forget
4797 /// the widgets that are gone. Values are computed first and set
4798 /// afterwards, as `flush_effective_enabled_signals` does: an observer may
4799 /// change the tree.
4800 pub(crate) fn flush_command_availability(&mut self) {
4801 let arena = &self.arena;
4802 self.command_watchers
4803 .retain(|(id, _, _)| arena.get(*id).is_some());
4804 if self.command_watchers.is_empty() {
4805 return;
4806 }
4807 let source = self.command_focus();
4808 let updates: Vec<(crate::signal::Signal<bool>, bool)> = self
4809 .command_watchers
4810 .iter()
4811 .filter(|(id, _, _)| self.arena.is_active(*id))
4812 .filter_map(|(_, name, signal)| {
4813 let now = source.is_some_and(|source| self.can_handle_from(source, name));
4814 (signal.get() != now).then(|| (signal.clone(), now))
4815 })
4816 .collect();
4817 for (signal, value) in updates {
4818 signal.set(value);
4819 }
4820 }
4821
4822 /// The logical focus of [`can_handle`](Self::can_handle): where
4823 /// `send_intent_from_focus` from a menu row would start once the row's
4824 /// menu chain (up to a modal or a host surface such as a menu bar) has
4825 /// closed and given focus back.
4826 fn command_focus(&self) -> Option<WidgetId> {
4827 let Some(focus) = self.focus_or_modal() else {
4828 return self.intent_anchor();
4829 };
4830 let mut outermost = None;
4831 let mut current = self.overlay_ancestor_for_widget(focus);
4832 while let Some(id) = current {
4833 let Some(overlay) = self.overlay_manager.overlay(id) else {
4834 break;
4835 };
4836 if self.overlay_is_host_surface(id) {
4837 break;
4838 }
4839 outermost = Some(overlay);
4840 current = overlay.parent_overlay;
4841 }
4842 Some(
4843 outermost
4844 .and_then(|overlay| {
4845 overlay
4846 .command_source
4847 .filter(|id| self.arena.is_active(*id))
4848 .or(overlay.focus_restore)
4849 })
4850 .filter(|id| self.arena.is_active(*id))
4851 .unwrap_or(focus),
4852 )
4853 }
4854
4855 /// Keep the intents no action takes, for
4856 /// [`take_unclaimed_intents`](Self::take_unclaimed_intents). Off by
4857 /// default, so a tree nobody drains keeps nothing; `teksilo-app` turns
4858 /// it on for every window's tree and the application tree, and offers
4859 /// what one tree leaves to another. Turning it off drops what is kept.
4860 pub fn set_records_unclaimed_intents(&mut self, on: bool) {
4861 self.unclaimed_intents = on.then(Vec::new);
4862 }
4863
4864 /// Whether intents are kept for
4865 /// [`take_unclaimed_intents`](Self::take_unclaimed_intents).
4866 pub fn has_unclaimed_intents(&self) -> bool {
4867 self.unclaimed_intents
4868 .as_ref()
4869 .is_some_and(|kept| !kept.is_empty())
4870 }
4871
4872 /// Take the intents kept since the last call, oldest first: each was
4873 /// sent in this tree, and neither an action on its way to the root nor
4874 /// a global one took it (a shortcut's, only when the
4875 /// [application scope](Self::set_application_scope) takes it). Empty
4876 /// when recording is off.
4877 pub fn take_unclaimed_intents(&mut self) -> Vec<crate::intent::Intent> {
4878 self.unclaimed_intents
4879 .as_mut()
4880 .map(std::mem::take)
4881 .unwrap_or_default()
4882 }
4883
4884 /// Dispatch an intent another tree sent and left unclaimed, as if sent
4885 /// here: from the focused widget to the root, then the global actions;
4886 /// from the [content root](Self::set_content_root) when nothing is
4887 /// focused. Returns whether an action took it.
4888 ///
4889 /// It is not counted again by telemetry, which counted it where it was
4890 /// sent, and it is not kept as unclaimed here: an intent is offered to
4891 /// one other tree at most. An intent its actions send counts this
4892 /// crossing, and one that 64 crossings led to is not kept for another
4893 /// tree, so two trees whose actions answer each
4894 /// other stop. It keeps the
4895 /// [window it was sent in](crate::intent::Intent::origin_window). Its
4896 /// [activation token](crate::intent::Intent::activation_token), if any,
4897 /// is held through `ops` for the first window its actions open or
4898 /// raise, and released once they have run. Intents its handlers send
4899 /// are this tree's own, dispatched before this returns.
4900 pub fn dispatch_routed_intent(
4901 &mut self,
4902 mut intent: crate::intent::Intent,
4903 ops: &mut dyn crate::window::WindowOps,
4904 ) -> bool {
4905 let Some(anchor) = self.routed_anchor() else {
4906 return false;
4907 };
4908 let token = intent.take_activation_token();
4909 let holds = token.is_some();
4910 if let Some(token) = token {
4911 ops.hold_activation_token(token);
4912 }
4913 // What its actions send was led to by one more crossing.
4914 let outer = self.routed_crossings.replace(intent.crossings() + 1);
4915 // Sent in another tree, so not a key of this one: it goes on past the
4916 // modals of this one (no tap).
4917 let consumed = self.dispatch_intent_with(anchor, intent, true, &mut *ops, false, &[]);
4918 self.drain_pending_intents(&mut *ops);
4919 self.routed_crossings = outer;
4920 if holds {
4921 ops.release_activation_token();
4922 }
4923 consumed
4924 }
4925
4926 /// Walk `source → root` invoking any [`Action`](crate::action::Action)
4927 /// whose `intent` name matches, crossing from an overlay's content to
4928 /// the widget the overlay is attached to (see
4929 /// [`intent_walk`](Self::intent_walk)), and from an open modal on to the
4930 /// page behind it once its own actions and the window-global ones
4931 /// registered inside it have passed it by, except for a shortcut's
4932 /// intent and one [kept in a modal](crate::intent::Intent::kept_in_modal),
4933 /// which stay in the modal (see
4934 /// [`intent_route`](Self::intent_route)); then the other window-global
4935 /// actions. The first enabled, `Handled` response stops the walk. A
4936 /// `Propagated` or disabled action (when the shortcut's
4937 /// `propagate_when_disabled` is true) lets the walk continue. A disabled action with
4938 /// `propagate_when_disabled == false` consumes the intent at that
4939 /// level without invoking a handler.
4940 ///
4941 /// Returns whether the intent was consumed: `false` when the walk and the
4942 /// window-global fallback both ran out, which is what lets a shortcut's
4943 /// key reach the focused widget after all.
4944 pub(crate) fn dispatch_intent(
4945 &mut self,
4946 source: WidgetId,
4947 intent: crate::intent::Intent,
4948 propagate_when_disabled: bool,
4949 ops: &mut dyn crate::window::WindowOps,
4950 ) -> bool {
4951 self.dispatch_intent_with(source, intent, propagate_when_disabled, ops, true, &[])
4952 }
4953
4954 /// [`dispatch_intent`](Self::dispatch_intent), telemetry tap optional,
4955 /// crossing the overlays `crossings` recorded when the intent was sent.
4956 /// An intent with the tap is this tree's own, and a shortcut's among
4957 /// them, or one [kept in a modal](crate::intent::Intent::kept_in_modal),
4958 /// stops at the first open modal on its way: it is offered the
4959 /// actions inside it and the window-global ones registered inside it
4960 /// only. One without is [routed](Self::dispatch_routed_intent) from
4961 /// another tree, which counted it: no key of this one, it goes on past
4962 /// every modal.
4963 fn dispatch_intent_with(
4964 &mut self,
4965 source: WidgetId,
4966 intent: crate::intent::Intent,
4967 propagate_when_disabled: bool,
4968 ops: &mut dyn crate::window::WindowOps,
4969 tap: bool,
4970 crossings: &[OverlayCrossing],
4971 ) -> bool {
4972 // Telemetry tap. Single insertion point catches every intent
4973 // (shortcut-driven, programmatic via `send_intent`, etc.)
4974 // because every dispatch funnels through here, once, in the
4975 // tree that sent it. A no-op when no `TelemetryContext` is
4976 // registered.
4977 if tap {
4978 self.tap_intent_dispatched(&intent);
4979 }
4980 let intent = if tap { self.sent_here(intent) } else { intent };
4981
4982 // Pre-compute the route so the walk doesn't need to hold any arena
4983 // borrow while invoking handlers. A modal on the way goes first only
4984 // while it is open, so it is read now; a key stays in it.
4985 let is_key = tap && intent.stays_in_modal();
4986 let route = self.intent_route(source, crossings, !is_key);
4987
4988 for leg in 0..route.legs.len() {
4989 if let Some(consumed) =
4990 self.offer_leg(&route, leg, &intent, propagate_when_disabled, &mut *ops)
4991 {
4992 return consumed;
4993 }
4994 }
4995 // F6 / Shift+F6, from a key, a menu row, the palette or a handler:
4996 // no action took it, so the tree moves between its focus regions,
4997 // before the application tree is offered it. With no region to go
4998 // to, it is not consumed.
4999 if tap && let Some(forward) = crate::shortcut::region_direction(intent.name) {
5000 return self.cycle_focus_region(Some(source), forward, ops);
5001 }
5002 false
5003 }
5004
5005 /// Offer `intent` to the actions of the walk `leg` of `route`, then to
5006 /// the window-global actions that follow it
5007 /// ([`global_applies_after`](Self::global_applies_after)). `Some` with
5008 /// whether it was consumed when the offer ends there, `None` when it
5009 /// goes on.
5010 fn offer_leg(
5011 &mut self,
5012 route: &IntentRoute,
5013 leg: usize,
5014 intent: &crate::intent::Intent,
5015 propagate_when_disabled: bool,
5016 ops: &mut dyn crate::window::WindowOps,
5017 ) -> Option<bool> {
5018 for &id in &route.legs[leg].chain {
5019 if !self.arena.is_active(id) || !self.arena.is_enabled(id) {
5020 continue;
5021 }
5022
5023 // Take out the first matching action by intent name so
5024 // we can invoke its FnMut handler without holding an
5025 // arena-wide borrow. The action is reinserted at its
5026 // original position so declaration order is preserved
5027 // for any follow-on dispatch.
5028 let Some((mut action, idx, enabled)) = self.arena.get_mut(id).and_then(|node| {
5029 let idx = node.actions.iter().position(|a| a.intent == intent.name)?;
5030 let enabled = node.actions[idx].is_enabled();
5031 Some((node.actions.remove(idx), idx, enabled))
5032 }) else {
5033 continue;
5034 };
5035
5036 if !enabled {
5037 // Return the action untouched.
5038 if let Some(node) = self.arena.get_mut(id) {
5039 node.actions.insert(idx, action);
5040 }
5041 if propagate_when_disabled {
5042 continue;
5043 }
5044 return Some(true);
5045 }
5046
5047 let mut ctx = self.make_event_context(&mut *ops);
5048 ctx.handling_intent = Some(intent.name);
5049 let response = (action.handler)(intent, &mut ctx);
5050 if let Some(node) = self.arena.get_mut(id) {
5051 node.actions.insert(idx, action);
5052 }
5053 self.collect_from_ctx(ctx, id);
5054
5055 match response {
5056 crate::intent::IntentResponse::Handled => return Some(true),
5057 crate::intent::IntentResponse::Propagated => continue,
5058 }
5059 }
5060
5061 // Fallback: window-global actions (registered via
5062 // `register_action_global`). The walk found no consuming node
5063 // action, so consult the window's commands, reachable wherever in
5064 // the window the intent originated (menu-bar overlay, content,
5065 // shortcut): after a walk that stopped at a modal, those registered
5066 // inside it; after the last walk, the others.
5067 let mut i = 0;
5068 while i < self.global_actions.len() {
5069 let matches = {
5070 let (owner, action) = &self.global_actions[i];
5071 action.intent == intent.name
5072 && action.is_enabled()
5073 && self.global_applies_after(*owner, route, leg)
5074 };
5075 if !matches {
5076 i += 1;
5077 continue;
5078 }
5079 // Take the action out so the FnMut handler can run without holding a
5080 // borrow on `self`; reinsert at its slot afterwards.
5081 let (owner, mut action) = self.global_actions.remove(i);
5082 let mut ctx = self.make_event_context(&mut *ops);
5083 ctx.handling_intent = Some(intent.name);
5084 let response = (action.handler)(intent, &mut ctx);
5085 self.global_actions.insert(i, (owner, action));
5086 self.collect_from_ctx(ctx, owner);
5087 match response {
5088 crate::intent::IntentResponse::Handled => return Some(true),
5089 crate::intent::IntentResponse::Propagated => {
5090 i += 1;
5091 continue;
5092 }
5093 }
5094 }
5095 None
5096 }
5097
5098 /// Register a window-global [`Action`](crate::action::Action) owned by
5099 /// `owner`. Consulted as a dispatch fallback (see [`Self::dispatch_intent`]);
5100 /// torn down when `owner` rebuilds or is destroyed. Backs
5101 /// [`BuildContext::register_action_global`](crate::BuildContext::register_action_global).
5102 pub(crate) fn push_global_action(&mut self, owner: WidgetId, action: crate::action::Action) {
5103 self.global_actions.push((owner, action));
5104 }
5105
5106 // --- Window-close request (drained by the app loop) ---
5107
5108 /// Drain the "close this window" flag set by
5109 /// [`EventContext::close_window`] during dispatch. A *guarded* close
5110 /// — the app routes it through the window's close guard.
5111 pub fn take_close_window_request(&mut self) -> bool {
5112 std::mem::replace(&mut self.close_window_requested, false)
5113 }
5114
5115 /// Drain the "close this window, no questions asked" flag set by
5116 /// [`EventContext::close_window_forced`] during dispatch. An
5117 /// *unconditional* close that bypasses the window's close guard.
5118 pub fn take_force_close_request(&mut self) -> bool {
5119 std::mem::replace(&mut self.force_close_requested, false)
5120 }
5121
5122 /// Drain the pending locale switch raised by
5123 /// [`EventContext::set_locale`] during dispatch. The app layer
5124 /// (`WindowManager::drain_pending_locale_requests`) parses the
5125 /// result and routes it through `WindowManager::set_locale` so the
5126 /// `I18nManager`'s active locale, version signal, and layout
5127 /// direction all stay in sync with the tree.
5128 pub fn take_pending_locale_request(&mut self) -> Option<String> {
5129 self.pending_locale_request.take()
5130 }
5131
5132 /// Drain the pending theme switch raised by
5133 /// [`EventContext::set_theme`] during dispatch. The app layer
5134 /// (`WindowManager::drain_pending_theme_requests`) routes it through
5135 /// `WindowManager::set_theme` so the new theme is applied to every
5136 /// window, not just the one whose handler requested it.
5137 pub fn take_pending_theme_request(&mut self) -> Option<crate::styles::Theme> {
5138 self.pending_theme_request.take()
5139 }
5140
5141 /// Drain the pending "follow OS theme" request raised by
5142 /// [`EventContext::follow_system_theme`] during dispatch. The app layer
5143 /// (`WindowManager::drain_pending_follow_system_requests`) switches to
5144 /// `ThemeMode::Native` and recomputes the theme from the OS for every
5145 /// window. Returns `true` if a request was pending.
5146 pub fn take_pending_follow_system_request(&mut self) -> bool {
5147 std::mem::take(&mut self.pending_follow_system_request)
5148 }
5149
5150 /// Drain the pending text-scale change raised by
5151 /// [`EventContext::set_text_scale`] during dispatch. The app layer
5152 /// (`WindowManager::drain_pending_text_scale_requests`) routes it through
5153 /// `WindowManager::set_text_scale` so the new factor is applied to every
5154 /// window, not just the one whose handler requested it.
5155 pub fn take_pending_text_scale_request(&mut self) -> Option<f32> {
5156 self.pending_text_scale_request.take()
5157 }
5158
5159 /// Drain all pending modal requests recorded during event handling.
5160 ///
5161 /// Each request includes the originating widget so higher layers can
5162 /// resolve routing and focus behavior relative to the source tree.
5163 pub fn drain_pending_modal_requests(&mut self) -> Vec<crate::modal::QueuedModalRequest> {
5164 std::mem::take(&mut self.pending_modal_requests)
5165 }
5166
5167 /// Drain whether the current native modal window should be dismissed.
5168 pub fn drain_pending_modal_dismissal(&mut self) -> bool {
5169 std::mem::replace(&mut self.pending_modal_dismissal, false)
5170 }
5171
5172 // --- Widget insertion ---
5173
5174 /// Walk `Widget::declare_shortcuts` for an already-inserted widget
5175 /// and register every returned shortcut with the registry, owned
5176 /// by `id`. Called at insertion AND at rebuild so the declared
5177 /// metadata survives across rebuilds (which `unregister_all_for_owner`
5178 /// would otherwise wipe). Build-time `ctx.register_shortcut` calls
5179 /// upsert handlers on top; the registry is idempotent on id.
5180 pub(crate) fn apply_declared_shortcuts(&mut self, id: WidgetId) {
5181 let declared = self
5182 .arena
5183 .get(id)
5184 .map(|n| n.widget.declare_shortcuts())
5185 .unwrap_or_default();
5186 for shortcut in declared {
5187 self.shortcut_registry.register_owned(shortcut, id);
5188 }
5189 }
5190
5191 /// Internal: insert a widget, call build(), wire children, register clips.
5192 fn insert_widget(&mut self, widget: Box<dyn Widget>) -> WidgetId {
5193 let id = self.arena.insert(widget);
5194
5195 {
5196 if let Some(mut widget_box) = self.arena.take_widget(id) {
5197 if let Some(handler_set) = widget_box.take_handler_set() {
5198 self.arena.restore_widget(id, widget_box);
5199 if handler_set.focus_region.is_some() {
5200 self.arena.focus_regions_seen = true;
5201 }
5202 if let Some(node) = self.arena.get_mut(id) {
5203 // Handlers attached at the widget's creation site
5204 // are external from its own perspective — keep
5205 // them out of the rebuild-cleared `handlers`
5206 // slot so they survive data-driven rebuilds.
5207 node.external_handlers = handler_set.handlers;
5208 node.node_focusable = handler_set.focusable;
5209 node.node_tab_index = handler_set.tab_index;
5210 node.node_cursor = handler_set.cursor;
5211 // `clips_children` and `event_pass_through` are
5212 // node-level flags on `WidgetNode` — they must
5213 // be mirrored here too. Without this an
5214 // `Inner::new().event_pass_through(true)` chain
5215 // silently no-ops (the flag stays at default
5216 // `false`), and any widget wrapped with it
5217 // catches every pointer event in its bounds.
5218 if let Some(clips) = handler_set.clips_children {
5219 node.clips_children = clips;
5220 }
5221 if let Some(pass_through) = handler_set.event_pass_through {
5222 node.event_pass_through = pass_through;
5223 }
5224 if let Some(dead_zone) = handler_set.gesture_dead_zone {
5225 node.gesture_dead_zone = dead_zone;
5226 }
5227 if let Some(chrome) = handler_set.window_chrome {
5228 node.window_chrome = chrome;
5229 }
5230 if let Some(chrome) = handler_set.scroll_chrome {
5231 node.scroll_chrome = chrome;
5232 }
5233 if let Some(focus_on_click) = handler_set.focus_on_click {
5234 node.focus_on_click = focus_on_click;
5235 }
5236 if let Some(role) = handler_set.long_press_role {
5237 node.long_press_role = role;
5238 }
5239 if let Some(action) = handler_set.touch_action {
5240 node.touch_action = action;
5241 }
5242 if let Some(claim) = handler_set.pan_claim {
5243 node.pan_claim = Some(claim);
5244 }
5245 if let Some(behavior) = handler_set.overscroll_behavior {
5246 node.overscroll_behavior = behavior;
5247 }
5248 if let Some(activation) = handler_set.drag_activation {
5249 node.drag_activation = activation;
5250 }
5251 if let Some(policy) = handler_set.multi_contact {
5252 node.multi_contact = policy;
5253 }
5254 if let Some(keyboard_capture) = handler_set.keyboard_capture {
5255 node.keyboard_capture = keyboard_capture;
5256 }
5257 if let Some(name) = handler_set.focus_region {
5258 node.focus_region = Some(name);
5259 }
5260 if let Some(hit_transparent) = handler_set.hit_transparent {
5261 node.hit_transparent = hit_transparent;
5262 }
5263 if let Some(slop) = handler_set.hit_slop {
5264 node.hit_slop = Some(slop);
5265 }
5266 if let Some(no_slop) = handler_set.no_hit_slop {
5267 node.no_hit_slop = no_slop;
5268 }
5269 if handler_set.context_menu_factory.is_some() {
5270 node.context_menu_factory = handler_set.context_menu_factory;
5271 }
5272 if handler_set.context_menu_contribution.is_some() {
5273 node.context_menu_contribution = handler_set.context_menu_contribution;
5274 }
5275 if let Some(sig) = handler_set.focus_within {
5276 node.focus_within_signal = Some(sig);
5277 }
5278 if let Some(sig) = handler_set.hover_within {
5279 node.hover_within_signal = Some(sig);
5280 }
5281 // Builder-chained `visible_when: prop`. Mirror of
5282 // `WidgetTree::visible_when`: register a bound prop at
5283 // Relayout, then store it on the node. (Disjoint field
5284 // borrow, like `access_hidden` below.)
5285 if let Some(prop) = handler_set.visible_when {
5286 prop.register_if_bound(
5287 id,
5288 &self.binding_registry,
5289 crate::binding::BindingLevel::Relayout,
5290 );
5291 node.visible_state = Some(prop);
5292 }
5293 // Builder-level accessibility overrides + subtree
5294 // mode. Mirrored here because this insertion path
5295 // bypasses `apply_handler_set`.
5296 if handler_set.access.is_some() {
5297 // Register any bound access_hidden/label/description/
5298 // value Props at AccessibilityOnly so the AT tree
5299 // re-walks when they flip. (Disjoint field borrow:
5300 // `node` borrows `self.arena`, this reads
5301 // `self.binding_registry`.)
5302 if let Some(access) = handler_set.access.as_ref() {
5303 Self::register_access_prop_bindings(
5304 access,
5305 id,
5306 &self.binding_registry,
5307 );
5308 }
5309 // Merged, not assigned: a node can already carry a
5310 // block from its builder chain, and replacing it
5311 // drops everything in it (see
5312 // `AccessibilityOverrides::merge_from`).
5313 match (&mut node.access_overrides, handler_set.access) {
5314 (Some(existing), Some(incoming)) => existing.merge_from(*incoming),
5315 (slot, incoming) => *slot = incoming,
5316 }
5317 }
5318 if let Some(mode) = handler_set.access_subtree {
5319 node.access_subtree = mode;
5320 }
5321 }
5322 } else {
5323 self.arena.restore_widget(id, widget_box);
5324 }
5325 }
5326 }
5327
5328 // Walk Widget::declare_shortcuts before build() so the
5329 // declared metadata lands in the registry first; if build()
5330 // also registers the same id with a real on_activate, the
5331 // registry upserts (preserving any user override).
5332 self.apply_declared_shortcuts(id);
5333
5334 {
5335 let mut widget_box = match self.arena.take_widget(id) {
5336 Some(widget) => widget,
5337 None => return id,
5338 };
5339 let mut build_ctx = crate::build_context::BuildContext {
5340 tree: self,
5341 composite_id: Some(id),
5342 effect_handles: Vec::new(),
5343 subscription_handles: Vec::new(),
5344 // A first mount has no previous build to inherit ids from.
5345 reusable_sub_ids: Vec::new(),
5346 };
5347 let built_children = widget_box.build(&mut build_ctx);
5348 let effect_handles = std::mem::take(&mut build_ctx.effect_handles);
5349 let subscription_handles = std::mem::take(&mut build_ctx.subscription_handles);
5350
5351 self.arena.restore_widget(id, widget_box);
5352
5353 // Transfer per-widget handles to the node. Both lists are
5354 // stored unconditionally — a leaf widget that registers an
5355 // effect in its build() still needs its ObserverHandle to
5356 // persist (otherwise the effect unregisters the moment
5357 // BuildContext drops).
5358 if let Some(node) = self.arena.get_mut(id) {
5359 node.subscription_handles = subscription_handles;
5360 node.effect_handles = effect_handles;
5361 }
5362
5363 if !built_children.is_empty() {
5364 for &child_id in &built_children {
5365 if let Some(child_node) = self.arena.get_mut(child_id) {
5366 child_node.parent = Some(id);
5367 }
5368 }
5369 if let Some(node) = self.arena.get_mut(id) {
5370 node.children = built_children;
5371 }
5372 }
5373 }
5374
5375 let clips = self
5376 .arena
5377 .get(id)
5378 .is_some_and(|node| node.widget.clips_children());
5379 if clips {
5380 self.arena.set_clips_children(id, true);
5381 }
5382
5383 id
5384 }
5385
5386 /// Add a widget to the tree.
5387 pub fn add(&mut self, widget: impl Widget + 'static) -> WidgetId {
5388 self.insert_widget(Box::new(widget))
5389 }
5390
5391 /// Add a pre-boxed widget to the tree.
5392 pub fn add_boxed(&mut self, widget: Box<dyn Widget>) -> WidgetId {
5393 self.insert_widget(widget)
5394 }
5395
5396 /// The widget that paints `id`'s title, when it has one.
5397 ///
5398 /// See [`Widget::accessible_title_node`].
5399 pub fn widget_accessible_title_node(&self, id: WidgetId) -> Option<WidgetId> {
5400 self.arena.get(id)?.widget.accessible_title_node()
5401 }
5402
5403 /// Add a widget as a child of another widget.
5404 pub fn add_child(&mut self, parent: WidgetId, widget: impl Widget + 'static) -> WidgetId {
5405 let boxed: Box<dyn Widget> = Box::new(widget);
5406
5407 let id = self.arena.insert_child(parent, boxed);
5408
5409 {
5410 if let Some(mut widget_box) = self.arena.take_widget(id) {
5411 if let Some(handler_set) = widget_box.take_handler_set() {
5412 self.arena.restore_widget(id, widget_box);
5413 if handler_set.focus_region.is_some() {
5414 self.arena.focus_regions_seen = true;
5415 }
5416 if let Some(node) = self.arena.get_mut(id) {
5417 // Creation-site handlers are external (persist
5418 // across the widget's own rebuilds) — see the
5419 // matching block in `insert_widget`.
5420 node.external_handlers = handler_set.handlers;
5421 node.node_focusable = handler_set.focusable;
5422 node.node_tab_index = handler_set.tab_index;
5423 node.node_cursor = handler_set.cursor;
5424 if let Some(clips) = handler_set.clips_children {
5425 node.clips_children = clips;
5426 }
5427 if let Some(pass_through) = handler_set.event_pass_through {
5428 node.event_pass_through = pass_through;
5429 }
5430 if let Some(dead_zone) = handler_set.gesture_dead_zone {
5431 node.gesture_dead_zone = dead_zone;
5432 }
5433 if let Some(chrome) = handler_set.window_chrome {
5434 node.window_chrome = chrome;
5435 }
5436 if let Some(chrome) = handler_set.scroll_chrome {
5437 node.scroll_chrome = chrome;
5438 }
5439 if let Some(focus_on_click) = handler_set.focus_on_click {
5440 node.focus_on_click = focus_on_click;
5441 }
5442 if let Some(role) = handler_set.long_press_role {
5443 node.long_press_role = role;
5444 }
5445 if let Some(action) = handler_set.touch_action {
5446 node.touch_action = action;
5447 }
5448 if let Some(claim) = handler_set.pan_claim {
5449 node.pan_claim = Some(claim);
5450 }
5451 if let Some(behavior) = handler_set.overscroll_behavior {
5452 node.overscroll_behavior = behavior;
5453 }
5454 if let Some(activation) = handler_set.drag_activation {
5455 node.drag_activation = activation;
5456 }
5457 if let Some(policy) = handler_set.multi_contact {
5458 node.multi_contact = policy;
5459 }
5460 if let Some(keyboard_capture) = handler_set.keyboard_capture {
5461 node.keyboard_capture = keyboard_capture;
5462 }
5463 if let Some(name) = handler_set.focus_region {
5464 node.focus_region = Some(name);
5465 }
5466 if let Some(hit_transparent) = handler_set.hit_transparent {
5467 node.hit_transparent = hit_transparent;
5468 }
5469 if let Some(slop) = handler_set.hit_slop {
5470 node.hit_slop = Some(slop);
5471 }
5472 if let Some(no_slop) = handler_set.no_hit_slop {
5473 node.no_hit_slop = no_slop;
5474 }
5475 if handler_set.context_menu_factory.is_some() {
5476 node.context_menu_factory = handler_set.context_menu_factory;
5477 }
5478 if handler_set.context_menu_contribution.is_some() {
5479 node.context_menu_contribution = handler_set.context_menu_contribution;
5480 }
5481 if let Some(sig) = handler_set.focus_within {
5482 node.focus_within_signal = Some(sig);
5483 }
5484 if let Some(sig) = handler_set.hover_within {
5485 node.hover_within_signal = Some(sig);
5486 }
5487 // Builder-chained `visible_when: prop`. Same as in
5488 // `insert_widget`.
5489 if let Some(prop) = handler_set.visible_when {
5490 prop.register_if_bound(
5491 id,
5492 &self.binding_registry,
5493 crate::binding::BindingLevel::Relayout,
5494 );
5495 node.visible_state = Some(prop);
5496 }
5497 // Builder-level accessibility overrides + subtree
5498 // mode. Same rationale as in `insert_widget`.
5499 if handler_set.access.is_some() {
5500 // Register any bound access_hidden/label/description/
5501 // value Props at AccessibilityOnly so the AT tree
5502 // re-walks when they flip. (Disjoint field borrow:
5503 // `node` borrows `self.arena`, this reads
5504 // `self.binding_registry`.)
5505 if let Some(access) = handler_set.access.as_ref() {
5506 Self::register_access_prop_bindings(
5507 access,
5508 id,
5509 &self.binding_registry,
5510 );
5511 }
5512 // Merged, not assigned: a node can already carry a
5513 // block from its builder chain, and replacing it
5514 // drops everything in it (see
5515 // `AccessibilityOverrides::merge_from`).
5516 match (&mut node.access_overrides, handler_set.access) {
5517 (Some(existing), Some(incoming)) => existing.merge_from(*incoming),
5518 (slot, incoming) => *slot = incoming,
5519 }
5520 }
5521 if let Some(mode) = handler_set.access_subtree {
5522 node.access_subtree = mode;
5523 }
5524 }
5525 } else {
5526 self.arena.restore_widget(id, widget_box);
5527 }
5528 }
5529 }
5530
5531 // Same shortcut-declaration walk as `insert_widget` — keeps
5532 // metadata visible from the moment the child mounts, before
5533 // build() runs.
5534 self.apply_declared_shortcuts(id);
5535
5536 {
5537 if let Some(mut widget_box) = self.arena.take_widget(id) {
5538 let mut build_ctx = crate::build_context::BuildContext {
5539 tree: self,
5540 composite_id: Some(id),
5541 effect_handles: Vec::new(),
5542 subscription_handles: Vec::new(),
5543 // A first mount has no previous build to inherit ids from.
5544 reusable_sub_ids: Vec::new(),
5545 };
5546 let built_children = widget_box.build(&mut build_ctx);
5547 let effect_handles = std::mem::take(&mut build_ctx.effect_handles);
5548 let subscription_handles = std::mem::take(&mut build_ctx.subscription_handles);
5549
5550 self.arena.restore_widget(id, widget_box);
5551
5552 // Transfer per-widget handles to the node. See the
5553 // matching block in `insert_widget` — effect and
5554 // subscription handles must persist for leaf widgets
5555 // too, not only composite ones.
5556 if let Some(node) = self.arena.get_mut(id) {
5557 node.subscription_handles = subscription_handles;
5558 node.effect_handles = effect_handles;
5559 }
5560
5561 if !built_children.is_empty() {
5562 for &child_id in &built_children {
5563 if let Some(child_node) = self.arena.get_mut(child_id) {
5564 child_node.parent = Some(id);
5565 }
5566 }
5567 if let Some(node) = self.arena.get_mut(id) {
5568 node.children = built_children;
5569 }
5570 }
5571 }
5572 }
5573
5574 let clips = self
5575 .arena
5576 .get(id)
5577 .is_some_and(|node| node.widget.clips_children());
5578 if clips {
5579 self.arena.set_clips_children(id, true);
5580 }
5581
5582 id
5583 }
5584
5585 // --- Property bindings ---
5586
5587 /// Bind a widget's visibility to a boolean prop.
5588 /// When false, the widget is set dormant; when true, it is activated.
5589 /// Accepts `Signal<bool>`, `Prop<bool>`, or plain `bool`.
5590 pub fn visible_when(&mut self, id: WidgetId, state: impl Into<crate::signal::Prop<bool>>) {
5591 let prop = state.into();
5592 prop.register_if_bound(
5593 id,
5594 &self.binding_registry,
5595 crate::binding::BindingLevel::Relayout,
5596 );
5597 if let Some(node) = self.arena.get_mut(id) {
5598 node.visible_state = Some(prop);
5599 }
5600 }
5601
5602 /// Set a widget subtree as dormant.
5603 ///
5604 /// Goes through the tree's cancel-aware parking door, so a pointer working
5605 /// inside the subtree is cancelled rather than stranded on a widget the
5606 /// dispatcher will no longer reach.
5607 pub fn set_dormant(&mut self, id: WidgetId) {
5608 self.park_subtree(id);
5609 self.arena.mark_ancestors_need_layout(id);
5610 self.cached_frame = None;
5611 self.a11y_dirty = true;
5612 }
5613
5614 /// Activate a dormant widget subtree.
5615 pub fn activate(&mut self, id: WidgetId) {
5616 self.arena.activate(id);
5617 self.arena.mark_ancestors_need_layout(id);
5618 self.cached_frame = None;
5619 self.a11y_dirty = true;
5620 }
5621
5622 /// Install (or reuse) the activation signal on a node and return a
5623 /// handle to it. The framework sets it to `false` when the node is
5624 /// parked dormant (`Switcher` / `visible_when`) and `true` when it is
5625 /// re-activated — see [`crate::arena::WidgetArena::set_dormant`] /
5626 /// [`activate`](crate::arena::WidgetArena::activate). The returned
5627 /// signal is initialised to the node's current active state. Used by
5628 /// widgets owning a resource outside the paint pass (a native subview)
5629 /// that must hide/show it in lockstep with framework activation.
5630 pub fn activation_signal(&mut self, id: WidgetId) -> crate::signal::Signal<bool> {
5631 if let Some(node) = self.arena.get_mut(id) {
5632 if let Some(existing) = node.activation_signal.clone() {
5633 return existing;
5634 }
5635 let active = node.activation == crate::arena::ActivationState::Active;
5636 let sig = crate::signal::Signal::new(active);
5637 node.activation_signal = Some(sig.clone());
5638 sig
5639 } else {
5640 // Node missing (shouldn't happen in build) — hand back a
5641 // detached signal so the caller still gets a valid handle.
5642 crate::signal::Signal::new(true)
5643 }
5644 }
5645
5646 // -----------------------------------------------------------------
5647 // In-node target geometry
5648 // -----------------------------------------------------------------
5649
5650 /// The interactive sub-regions the widget at `id` paints inside its own
5651 /// single node, in absolute arena coordinates.
5652 ///
5653 /// The read side of [`Widget::target_regions`]:
5654 /// a scroll bar's thumb, a slider's knob, a header cell's filter
5655 /// affordance. Empty for the overwhelming majority of widgets, whose node
5656 /// *is* their target and which therefore have nothing to add.
5657 ///
5658 /// Reporting only — reading this changes nothing. It exists so a
5659 /// conformance audit, and a test of one, can see geometry that no layout
5660 /// ever produced.
5661 pub fn widget_target_regions(&self, id: WidgetId) -> Vec<crate::partition::TargetRegion> {
5662 let Some(node) = self.arena.get(id) else {
5663 return Vec::new();
5664 };
5665 node.widget.target_regions(self.arena.bounds(id))
5666 }
5667
5668 /// The hit outset the **mounted** widget at `id` declares for `kind`,
5669 /// against the tree's live input tokens.
5670 ///
5671 /// The read side of [`Widget::hit_outset`], and the companion of
5672 /// [`widget_target_regions`](Self::widget_target_regions): both let a
5673 /// conformance audit — and a test of one — see target geometry that no
5674 /// layout ever produced.
5675 ///
5676 /// It has to read the mounted node rather than a freshly-built widget,
5677 /// because an outset is usually derived from what the widget *painted*,
5678 /// and an unmounted one has painted nothing. That is also what makes the
5679 /// **gates** assertable: a decorative avatar, an inert twist arrow, a
5680 /// disabled swatch and a breadcrumb's current crumb all take no press, so
5681 /// each must declare `EdgeInsets::ZERO` — a widened node that then refuses
5682 /// the press is a hole punched in whatever is behind it.
5683 ///
5684 /// The tokens are the **effective** theme's, not `theme`'s, because that
5685 /// is what the hit path itself reads:
5686 /// `hit_test_for_excluding` builds its `HitContext` from
5687 /// `effective_theme.input`, as do the pointer profile and the touch-enabled
5688 /// gate in `pointer_state.rs`. The two themes agree only for as long as
5689 /// nothing between them touches `input` — `recompute_effective_theme`
5690 /// currently projects typography alone — and an accessor that describes a
5691 /// path has to read that path's source rather than one that happens to
5692 /// match it.
5693 ///
5694 /// Reporting only — reading this changes nothing.
5695 pub fn widget_hit_outset(
5696 &self,
5697 id: WidgetId,
5698 kind: teksilo_tokens::PointerKind,
5699 ) -> teksilo_canvas::EdgeInsets {
5700 let Some(node) = self.arena.get(id) else {
5701 return teksilo_canvas::EdgeInsets::ZERO;
5702 };
5703 node.widget.hit_outset(kind, &self.effective_theme.input)
5704 }
5705
5706 // -----------------------------------------------------------------
5707 // Press state
5708 // -----------------------------------------------------------------
5709
5710 /// Install (or reuse) the framework press signal on a node and return a
5711 /// handle to it.
5712 ///
5713 /// `true` while the node holds a pointer press whose visual is showing:
5714 /// between press and release, `false` once the pointer leaves the press's
5715 /// tap boundary and `true` again on re-entry, cleared on a cancel or when
5716 /// a peer wins the arbitration. See `docs/touch-and-pen.md` §7.
5717 pub fn pressed_signal(&mut self, id: WidgetId) -> crate::signal::Signal<bool> {
5718 let showing = self.is_pressed(id);
5719 let Some(node) = self.arena.get_mut(id) else {
5720 // Node missing (should not happen during build) — hand back a
5721 // detached signal so the caller still gets a valid handle.
5722 return crate::signal::Signal::new(false);
5723 };
5724 if let Some(existing) = node.pressed_signal.clone() {
5725 return existing;
5726 }
5727 let sig = crate::signal::Signal::new(showing);
5728 node.pressed_signal = Some(sig.clone());
5729 sig
5730 }
5731
5732 /// The press held by the pointer being dispatched, as `(inside, pending)`,
5733 /// for [`EventContext`]'s per-dispatch
5734 /// snapshot. `None` when that pointer holds no press.
5735 pub(crate) fn current_press_snapshot(&self) -> Option<(bool, bool)> {
5736 self.presses
5737 .get(self.current_pointer_id())
5738 .map(|p| (p.inside, p.pending()))
5739 }
5740
5741 /// The contact holding `id`'s press, whether or not its visual is showing.
5742 ///
5743 /// `None` for a node nothing is pressing. A node held by a finger whose
5744 /// press-feedback delay has not elapsed still answers with that finger:
5745 /// the press is real, only its visual is waiting.
5746 pub fn pressed_by(&self, id: WidgetId) -> Option<crate::pointer::PointerId> {
5747 self.presses.owner_of(id)
5748 }
5749
5750 /// Whether `id`'s press visual is showing — held, inside its tap boundary,
5751 /// and past any press-feedback delay. What the node's
5752 /// [`pressed_signal`](Self::pressed_signal) mirrors.
5753 pub fn is_pressed(&self, id: WidgetId) -> bool {
5754 self.presses
5755 .for_node(id)
5756 .is_some_and(crate::press::Press::showing)
5757 }
5758
5759 /// Whether `id` is held and the pointer has not left the press's tap
5760 /// boundary. True during a press-feedback delay, unlike
5761 /// [`is_pressed`](Self::is_pressed).
5762 pub fn press_is_inside(&self, id: WidgetId) -> bool {
5763 self.presses.for_node(id).is_some_and(|p| p.inside)
5764 }
5765
5766 /// Whether `id` is held but its press-feedback delay has not elapsed, so
5767 /// the visual is deliberately withheld.
5768 pub fn press_pending(&self, id: WidgetId) -> bool {
5769 self.presses
5770 .for_node(id)
5771 .is_some_and(crate::press::Press::pending)
5772 }
5773
5774 /// Publish `id`'s press signal from the table. The one place a press
5775 /// signal is written, so "the table changed" and "the recipe was told"
5776 /// cannot drift apart.
5777 pub(crate) fn publish_pressed(&mut self, id: WidgetId) {
5778 let showing = self.is_pressed(id);
5779 if let Some(node) = self.arena.get(id)
5780 && let Some(sig) = node.pressed_signal.clone()
5781 && sig.get() != showing
5782 {
5783 sig.set(showing);
5784 }
5785 }
5786
5787 /// Fire the `activation_signal` of every node that transitioned
5788 /// Active↔Dormant since the last flush. Called at a well-defined tree-level
5789 /// point (the end of `process_state_changes`), never from inside the arena
5790 /// recursion — so an observer (e.g. a `WebView` calling the engine's
5791 /// `set_visible`) runs after the visibility pass has fully committed,
5792 /// matching the `focus_within` / `hover_within` update discipline.
5793 pub(crate) fn flush_activation_signals(&mut self) {
5794 let changes = self.arena.take_activation_changes();
5795 for (id, _recorded) in changes {
5796 // Re-read the node at flush time; it still exists (the transition
5797 // was recorded in the same synchronous operation).
5798 let Some(node) = self.arena.get(id) else {
5799 continue;
5800 };
5801 let Some(sig) = node.activation_signal.clone() else {
5802 continue;
5803 };
5804 // Fire the node's **current** state, not the value recorded at the
5805 // transition, and only when it differs from what observers last
5806 // saw. `pending_activation_changes` is an append-only queue: a
5807 // node parked and re-activated inside one batch records both
5808 // edges, and replaying them in order hands observers a `false`
5809 // that was never observable — the node is already Active by the
5810 // time anyone is told anything.
5811 //
5812 // The in-tree modal path does exactly that on every open: build
5813 // the content, `set_dormant` it, mount the scrim, `activate` it,
5814 // then move focus in. Both edges land in one batch and flush
5815 // *after* the focus dispatch, so the stale `false` arrives last
5816 // and observers act on a state that has already been superseded.
5817 // For a text editor that meant its dormancy handler wiped the
5818 // `has_focus` it had just been granted, and the dialog opened with
5819 // no caret; a `WebView` would have taken a real `set_visible(false)`
5820 // OS call for a subview that never left the screen.
5821 //
5822 // Collapsing to the final state also makes the flush idempotent
5823 // over duplicate ids: the first iteration syncs the signal, the
5824 // rest find it already equal and skip. `Signal::set` notifies
5825 // unconditionally, so the equality guard is what stops the
5826 // redundant fanout.
5827 let active = node.activation == crate::arena::ActivationState::Active;
5828 if sig.get() != active {
5829 sig.set(active);
5830 }
5831 }
5832 }
5833
5834 /// Bind an opacity multiplier (0..1) to a widget. The render walker
5835 /// emits `SetOpacity(value)` before painting the widget's subtree
5836 /// and `RestoreOpacity` afterwards, so the multiplier composes
5837 /// correctly with ancestor opacity scopes via the canvas's stacked
5838 /// opacity model. Bound at `Repaint` level: opacity changes never
5839 /// trigger relayout. Pass any `Prop<f32>` or `Signal<f32>` source
5840 /// (typically an animated signal driven by a `Fade` wrapper).
5841 pub fn set_opacity(&mut self, id: WidgetId, opacity: impl Into<crate::signal::Prop<f32>>) {
5842 let prop = opacity.into();
5843 prop.register_if_bound(
5844 id,
5845 &self.binding_registry,
5846 crate::binding::BindingLevel::RepaintOnly,
5847 );
5848 if let Some(node) = self.arena.get_mut(id) {
5849 node.opacity_prop = Some(prop);
5850 }
5851 }
5852
5853 /// Bind a 2D affine transform to a widget. The render walker emits
5854 /// `PushTransform(value)` before painting the widget's subtree and
5855 /// `PopTransform` afterwards; the renderer composes the transform
5856 /// onto its stack so nested wrappers and widget-internal canvas
5857 /// transforms compose correctly. Bound at `Repaint` level: visual-
5858 /// only transforms never trigger relayout. Wrappers that want the
5859 /// transform's *value change* to also drive layout (e.g.
5860 /// `Scale::reflow(true)`) must additionally bind the *driver*
5861 /// signal to themselves at `Relayout` level — the transform prop
5862 /// itself stays at Repaint. Pass a `Transform2D`, `Signal<Transform2D>`,
5863 /// or `Prop<Transform2D>`.
5864 pub fn set_transform(
5865 &mut self,
5866 id: WidgetId,
5867 transform: impl Into<crate::signal::Prop<teksilo_canvas::Transform2D>>,
5868 ) {
5869 let prop = transform.into();
5870 prop.register_if_bound(
5871 id,
5872 &self.binding_registry,
5873 crate::binding::BindingLevel::RepaintOnly,
5874 );
5875 if let Some(node) = self.arena.get_mut(id) {
5876 node.transform_prop = Some(prop);
5877 // A plain transform is a *self* transform — clear any prior
5878 // content-transform marker so the flag can never go stale if a
5879 // node switches from `set_content_transform` to `set_transform`.
5880 node.content_transform = false;
5881 }
5882 }
5883
5884 /// Like [`set_transform`](Self::set_transform), but marks the transform as
5885 /// a **content** transform: it positions the node's content within a fixed
5886 /// parent-space viewport (the node's bounds) rather than transforming the
5887 /// node itself. Hit-testing then keeps the whole viewport interactive at
5888 /// any pan / zoom. Used by `SceneView`; see
5889 /// `WidgetNode::content_transform`.
5890 pub fn set_content_transform(
5891 &mut self,
5892 id: WidgetId,
5893 transform: impl Into<crate::signal::Prop<teksilo_canvas::Transform2D>>,
5894 ) {
5895 let prop = transform.into();
5896 prop.register_if_bound(
5897 id,
5898 &self.binding_registry,
5899 crate::binding::BindingLevel::RepaintOnly,
5900 );
5901 if let Some(node) = self.arena.get_mut(id) {
5902 node.transform_prop = Some(prop);
5903 node.content_transform = true;
5904 }
5905 }
5906
5907 /// Bind a Gaussian-equivalent blur radius to a widget. The render
5908 /// walker emits `BeginBlurredSubtree { bounds, radius }` before
5909 /// painting the widget's subtree and `EndBlurredSubtree` afterwards;
5910 /// the renderer redirects drawing into an intermediate texture, runs
5911 /// a dual-Kawase blur chain at the requested radius, and composites
5912 /// the blurred result back into the parent pass. Bound at `Repaint`
5913 /// level: blur radius changes never trigger relayout. Sub-perceptual
5914 /// radii (< 0.5) skip the Begin/End pair entirely so animated
5915 /// enable/disable patterns have zero per-frame cost when fully off.
5916 /// Pass any `Prop<f32>` or `Signal<f32>` source.
5917 pub fn set_blur(&mut self, id: WidgetId, radius: impl Into<crate::signal::Prop<f32>>) {
5918 let prop = radius.into();
5919 prop.register_if_bound(
5920 id,
5921 &self.binding_registry,
5922 crate::binding::BindingLevel::RepaintOnly,
5923 );
5924 if let Some(node) = self.arena.get_mut(id) {
5925 node.blur_prop = Some(prop);
5926 }
5927 }
5928
5929 /// Bind a widget's enabled state to a boolean prop or compatibility state binding.
5930 /// When false, the widget and its entire subtree ignore all events but remain
5931 /// visible. Focus traversal skips disabled subtrees and AccessKit marks their
5932 /// nodes as disabled. Accepts `Signal<bool>`, `Prop<bool>`, compatibility state
5933 /// bindings, or plain `bool`.
5934 ///
5935 /// The bound signal registers at `BindingLevel::SubtreeRepaint`: when
5936 /// it flips, the entire subtree rooted at `id` is marked for repaint
5937 /// (not relayout — geometry doesn't change). Leaves like
5938 /// `IconWidget` then re-resolve their role color
5939 /// using the new `PaintContext::effective_enabled` value, so a
5940 /// disabled subtree's icons and text dim automatically.
5941 pub fn enabled_when(&mut self, id: WidgetId, state: impl Into<crate::signal::Prop<bool>>) {
5942 let prop = state.into();
5943 // SubtreeRepaint propagates the visual dirty mark through the
5944 // disabled subtree so leaves re-resolve their role colors.
5945 prop.register_if_bound(
5946 id,
5947 &self.binding_registry,
5948 crate::binding::BindingLevel::SubtreeRepaint,
5949 );
5950 // AccessibilityOnly is orthogonal — it flips `a11y_dirty` so
5951 // AccessKit's `disabled` flag refreshes on the next a11y sync
5952 // (the accessibility walker reads `arena.is_enabled(id)`,
5953 // which is already correct via the prop, but the tree needs
5954 // to be told to rebuild).
5955 prop.register_if_bound(
5956 id,
5957 &self.binding_registry,
5958 crate::binding::BindingLevel::AccessibilityOnly,
5959 );
5960 if let Some(node) = self.arena.get_mut(id) {
5961 node.enabled_state = Some(prop);
5962 }
5963 }
5964
5965 /// Reactive view of "is this widget effectively enabled?" — the AND
5966 /// of the widget's own `enabled_state` and every ancestor's.
5967 /// [`Self::is_enabled`] is the non-reactive equivalent; this method
5968 /// gives composite widgets a `Signal<bool>` for derived state.
5969 ///
5970 /// Leaves (`IconWidget`, `TextWidget`, `RectWidget`) do NOT need this
5971 /// — they receive the resolved bool via
5972 /// [`crate::widget::PaintContext::effective_enabled`] at paint time.
5973 /// This method is for composites that want to derive cursor / custom
5974 /// paint roles / etc. reactively.
5975 ///
5976 /// Install-or-reuse, exactly like [`Self::activation_signal`]: the signal
5977 /// lives on the node and the framework refreshes it from the live arena
5978 /// once per state-change pass (`flush_effective_enabled_signals`).
5979 ///
5980 /// It is deliberately NOT a signal derived by walking the ancestor chain
5981 /// here. A widget's `parent` is still `None` while its own `build()` runs
5982 /// — `insert_widget` inserts the node parentless and wires the parent link
5983 /// only after `build()` returns — so an ancestor walk performed from
5984 /// inside `build()` (which is how every caller uses this) sees an empty
5985 /// chain and would capture the widget's OWN `enabled` prop as the whole
5986 /// answer, permanently. That was a real bug: a Button inside a disabled
5987 /// form stayed painted as if enabled.
5988 ///
5989 /// The value is seeded from the live arena and corrected on the next
5990 /// flush, so a first-`build()` caller (parent not yet wired) and a
5991 /// rebuild caller (parent wired) both converge before anything paints.
5992 pub fn effective_enabled_signal(&mut self, id: WidgetId) -> crate::signal::Signal<bool> {
5993 if let Some(existing) = self
5994 .arena
5995 .get(id)
5996 .and_then(|n| n.effective_enabled_signal.clone())
5997 {
5998 return existing;
5999 }
6000 // Seed from the live tree. Mid-`build()` the parent is not wired yet,
6001 // so this is the widget's own state only; `flush_effective_enabled_signals`
6002 // corrects it against the fully-wired tree before the first paint.
6003 let seed = self.arena.is_enabled(id);
6004 let sig = crate::signal::Signal::new(seed);
6005 let Some(node) = self.arena.get_mut(id) else {
6006 // Node missing (shouldn't happen in build) — hand back a detached
6007 // handle so the caller still gets a valid signal.
6008 return crate::signal::Signal::new(true);
6009 };
6010 node.effective_enabled_signal = Some(sig.clone());
6011 self.arena.watch_effective_enabled(id);
6012 sig
6013 }
6014
6015 /// Refresh every node-resident `effective_enabled_signal` against the live
6016 /// arena, firing observers only where the value actually changed.
6017 ///
6018 /// Unlike [`Self::flush_activation_signals`] this cannot be driven off a
6019 /// change queue: a node's `enabled_state` is a `Prop<bool>` that may be
6020 /// bound to an app `Signal` which flips without the arena being notified,
6021 /// so there is no mutation site at which to record a transition. Instead
6022 /// this recomputes the (cheap, `O(depth)`) ancestor AND for each opted-in
6023 /// node and diffs. Only nodes that called
6024 /// [`Self::effective_enabled_signal`] are visited, so a tree with no
6025 /// interactive widgets pays nothing.
6026 ///
6027 /// Values are collected first and set afterwards: a `Signal::set` observer
6028 /// may mutate the tree, and must not run while the arena is being walked —
6029 /// the same discipline as `flush_activation_signals` and the
6030 /// `focus_within` / `hover_within` updates.
6031 pub(crate) fn flush_effective_enabled_signals(&mut self) {
6032 self.arena.prune_effective_enabled_watchers();
6033 let mut updates: Vec<(crate::signal::Signal<bool>, bool)> = Vec::new();
6034 for id in self.arena.effective_enabled_watchers() {
6035 let Some(sig) = self
6036 .arena
6037 .get(id)
6038 .and_then(|n| n.effective_enabled_signal.clone())
6039 else {
6040 continue;
6041 };
6042 let now = self.arena.is_enabled(id);
6043 if sig.get() != now {
6044 updates.push((sig, now));
6045 }
6046 }
6047 for (sig, value) in updates {
6048 sig.set(value);
6049 }
6050 }
6051
6052 /// Whether a widget is effectively enabled. Returns `false` if the widget
6053 /// itself or any ancestor has `enabled_state` bound to `false`.
6054 pub fn is_enabled(&self, id: WidgetId) -> bool {
6055 self.arena.is_enabled(id)
6056 }
6057
6058 /// Bind a widget's Tab-key participation to a boolean prop or
6059 /// compatibility state binding. When false, the widget is removed
6060 /// from Tab / Shift+Tab traversal (`cycle_focus`) but remains
6061 /// reachable via `request_focus` and arrow-key navigation that
6062 /// calls `request_focus`. Implements the ARIA roving-tabindex
6063 /// pattern (HTML `tabindex="-1"` semantics). Accepts
6064 /// `Signal<bool>`, `Prop<bool>`, or plain `bool`.
6065 /// Publish what a data view's `Space` should do when the row containing
6066 /// `id` holds the keyboard cursor. See
6067 /// [`WidgetNode::keyboard_toggle`](crate::arena::WidgetNode).
6068 pub fn set_keyboard_toggle(
6069 &mut self,
6070 id: WidgetId,
6071 f: std::rc::Rc<dyn Fn(&mut crate::widget::EventContext)>,
6072 ) {
6073 if let Some(node) = self.arena.get_mut(id) {
6074 node.keyboard_toggle = Some(f);
6075 }
6076 }
6077
6078 /// The first keyboard-toggle action published in `root`'s subtree, in
6079 /// traversal order.
6080 ///
6081 /// Searched per keypress rather than cached: a data view rebuilds its rows
6082 /// as they realize, so an id recorded at build time would outlive the
6083 /// widget it named.
6084 pub fn keyboard_toggle_in(
6085 &self,
6086 root: WidgetId,
6087 ) -> Option<std::rc::Rc<dyn Fn(&mut crate::widget::EventContext)>> {
6088 if let Some(f) = self.arena.get(root).and_then(|n| n.keyboard_toggle.clone()) {
6089 return Some(f);
6090 }
6091 for &child in self.arena.children(root) {
6092 if let Some(found) = self.keyboard_toggle_in(child) {
6093 return Some(found);
6094 }
6095 }
6096 None
6097 }
6098
6099 pub fn set_tab_stop(&mut self, id: WidgetId, state: impl Into<crate::signal::Prop<bool>>) {
6100 let prop = state.into();
6101 // Bind at the lightest level — tab-stop changes never affect
6102 // layout or paint; cycle_focus reads the current value on
6103 // each Tab keypress.
6104 prop.register_if_bound(
6105 id,
6106 &self.binding_registry,
6107 crate::binding::BindingLevel::RepaintOnly,
6108 );
6109 if let Some(node) = self.arena.get_mut(id) {
6110 node.tab_stop = Some(prop);
6111 }
6112 }
6113
6114 /// Gate Tab traversal over the whole subtree of `id`: while `gate` reads
6115 /// `false`, Tab and `first_focusable_descendant` find nothing in it,
6116 /// whatever Tab-stop props its nodes carry, so a roving group inside it
6117 /// (a toolbar's current item) is held out too. The subtree stays active,
6118 /// focusable by a direct request, and present to assistive technology.
6119 ///
6120 /// For a container that keeps a part of itself out of the Tab order until
6121 /// the user steps into it (a `ListView` row in action mode).
6122 #[doc(hidden)]
6123 pub fn set_tab_gate(&mut self, id: WidgetId, gate: impl Into<crate::signal::Prop<bool>>) {
6124 let prop = gate.into();
6125 // Read on each Tab press, like `tab_stop`.
6126 prop.register_if_bound(
6127 id,
6128 &self.binding_registry,
6129 crate::binding::BindingLevel::RepaintOnly,
6130 );
6131 if let Some(node) = self.arena.get_mut(id) {
6132 node.tab_gate = Some(prop);
6133 }
6134 }
6135
6136 /// Current Tab-key participation for a widget. Returns the value
6137 /// of the `tab_stop` prop if bound, or `true` (the default) when
6138 /// no binding is present. Mirrors the filter used by
6139 /// `cycle_focus` — primarily for tests asserting the
6140 /// roving-tabindex contract.
6141 pub fn tab_stop(&self, id: WidgetId) -> bool {
6142 self.arena
6143 .get(id)
6144 .and_then(|node| node.tab_stop.as_ref())
6145 .map(|prop| prop.get())
6146 .unwrap_or(true)
6147 }
6148
6149 /// Declare `id` as a **traversal-scope boundary** with the given policy.
6150 /// `cycle_focus` then treats the node's subtree as an independent Tab
6151 /// group: `tab_index` values inside it are scoped (they never collide
6152 /// with sibling scopes) and `policy` governs Tab at the scope's ends.
6153 ///
6154 /// The scope node is forced non-focusable — it is a transparent boundary,
6155 /// never itself a Tab stop. Called from `BuildContext::set_traversal_scope`
6156 /// (which the `FocusScope` wrapper widget invokes during `build`), and
6157 /// directly usable from tests with no dependency on the widgets crate.
6158 pub fn set_traversal_scope(
6159 &mut self,
6160 id: WidgetId,
6161 policy: crate::focus::TraversalScopePolicy,
6162 ) {
6163 if let Some(node) = self.arena.get_mut(id) {
6164 node.node_traversal_scope = Some(policy);
6165 node.node_focusable = Some(false);
6166 }
6167 }
6168
6169 /// Remove a previously set traversal-scope marker from `id` (rebuild
6170 /// paths where a `FocusScope` is replaced by a non-scope widget). Leaves
6171 /// `node_focusable` untouched — a later handler-set application resets it.
6172 pub fn clear_traversal_scope(&mut self, id: WidgetId) {
6173 if let Some(node) = self.arena.get_mut(id) {
6174 node.node_traversal_scope = None;
6175 }
6176 }
6177
6178 /// Current traversal-scope policy on `id`, if any. For tests asserting
6179 /// the scope marker contract.
6180 pub fn traversal_scope(&self, id: WidgetId) -> Option<crate::focus::TraversalScopePolicy> {
6181 self.arena
6182 .get(id)
6183 .and_then(|node| node.node_traversal_scope)
6184 }
6185
6186 // --- Theme override ---
6187
6188 /// Set a theme override on a widget. All descendants of this widget
6189 /// will see the modified theme during layout and paint.
6190 /// The override function receives a mutable `Theme` to modify.
6191 ///
6192 /// ```
6193 /// # use teksilo_core::{Widget, LayoutResponse, LayoutContext, widget_tree::WidgetTree};
6194 /// # use teksilo_canvas::{Size, SizeProposal};
6195 /// # use teksilo_tokens::ColorTokens;
6196 /// # #[derive(Debug)] struct MinWidget;
6197 /// # impl Widget for MinWidget {
6198 /// # fn layout_response(&self, _: SizeProposal, _: &LayoutContext) -> LayoutResponse {
6199 /// # Size::new(0.0, 0.0).into()
6200 /// # }
6201 /// # }
6202 /// # let mut tree = WidgetTree::new();
6203 /// # let panel_id = tree.add(MinWidget);
6204 /// tree.set_theme_override(panel_id, |theme| {
6205 /// theme.colors = ColorTokens::dark_default();
6206 /// });
6207 /// ```
6208 pub fn set_theme_override(
6209 &mut self,
6210 id: WidgetId,
6211 f: impl Fn(&mut crate::styles::Theme) + 'static,
6212 ) {
6213 let had_override = self
6214 .arena
6215 .get(id)
6216 .is_some_and(|n| n.theme_override.is_some());
6217 if let Some(node) = self.arena.get_mut(id) {
6218 node.theme_override = Some(crate::environment::ThemeOverride { func: Box::new(f) });
6219 node.dirty.needs_layout = true;
6220 node.dirty.needs_paint = true;
6221 }
6222 if !had_override {
6223 self.arena.theme_override_count += 1;
6224 }
6225 }
6226
6227 /// Get the resolved theme for a specific widget (applying ancestor overrides).
6228 pub fn resolved_theme(&self, id: WidgetId) -> crate::styles::Theme {
6229 self.arena.resolve_theme(id, &self.theme).into_owned()
6230 }
6231}
6232
6233impl Default for WidgetTree {
6234 fn default() -> Self {
6235 Self::new()
6236 }
6237}
6238
6239#[cfg(test)]
6240mod activation_signal_tests {
6241 use super::*;
6242 use crate::build_context::BuildContext;
6243 use crate::signal::Signal;
6244 use crate::widget::{LayoutContext, LayoutResponse, Widget};
6245 use teksilo_canvas::SizeProposal;
6246
6247 /// A leaf that, on build, opts into its activation signal and mirrors it
6248 /// into an out-of-band signal the test can read.
6249 #[derive(Debug)]
6250 struct ActivationProbe {
6251 log: Signal<Vec<bool>>,
6252 }
6253
6254 impl Widget for ActivationProbe {
6255 fn build(&mut self, ctx: &mut BuildContext) -> Vec<WidgetId> {
6256 let id = ctx.self_id();
6257 let vis = ctx.activation_signal(id);
6258 let log = self.log.clone();
6259 ctx.effect(&vis, move |active| {
6260 let mut v = log.get();
6261 v.push(*active);
6262 log.set(v);
6263 });
6264 Vec::new()
6265 }
6266
6267 fn layout_response(&self, proposal: SizeProposal, _ctx: &LayoutContext) -> LayoutResponse {
6268 proposal.resolve(10.0, 10.0).into()
6269 }
6270 }
6271
6272 /// A widget that enqueues a post-mount action via `run_after_mount` has it
6273 /// run exactly once, with a real `EventContext`, when the tree drains
6274 /// (`run_mount_actions`) — and `has_pending_mount_actions` reflects the
6275 /// queue state.
6276 #[derive(Debug)]
6277 struct MountActionProbe {
6278 ran: Signal<u32>,
6279 }
6280
6281 impl Widget for MountActionProbe {
6282 fn build(&mut self, ctx: &mut BuildContext) -> Vec<WidgetId> {
6283 let ran = self.ran.clone();
6284 ctx.run_after_mount(move |_ectx| ran.set(ran.get() + 1));
6285 Vec::new()
6286 }
6287
6288 fn layout_response(&self, proposal: SizeProposal, _ctx: &LayoutContext) -> LayoutResponse {
6289 proposal.resolve(10.0, 10.0).into()
6290 }
6291 }
6292
6293 #[test]
6294 fn run_after_mount_runs_once_on_drain() {
6295 let mut tree = WidgetTree::new();
6296 let ran = Signal::new(0_u32);
6297 tree.add(MountActionProbe { ran: ran.clone() });
6298 tree.layout(SizeProposal::exact(100.0, 100.0));
6299
6300 // Queued during build, not yet run.
6301 assert!(tree.has_pending_mount_actions());
6302 assert_eq!(ran.get(), 0);
6303
6304 // Drain with a Noop sink (as headless callers do).
6305 tree.run_mount_actions(&mut crate::window::NoopWindowOps);
6306 assert_eq!(ran.get(), 1);
6307 assert!(!tree.has_pending_mount_actions());
6308
6309 // Draining again is a no-op (the queue is empty).
6310 tree.run_mount_actions(&mut crate::window::NoopWindowOps);
6311 assert_eq!(ran.get(), 1);
6312 }
6313
6314 #[test]
6315 fn activation_signal_fires_on_dormant_and_reactivate() {
6316 let mut tree = WidgetTree::new();
6317 let log = Signal::new(Vec::<bool>::new());
6318 let probe = tree.add(ActivationProbe { log: log.clone() });
6319
6320 // Gate the probe's visibility on a signal.
6321 let visible = Signal::new(true);
6322 tree.visible_when(probe, visible.clone());
6323 tree.layout(SizeProposal::exact(100.0, 100.0));
6324
6325 // Initially active: effect registration alone fires nothing.
6326 assert_eq!(log.get(), Vec::<bool>::new());
6327
6328 // Hide → dormant → activation signal false.
6329 visible.set(false);
6330 tree.layout(SizeProposal::exact(100.0, 100.0));
6331 assert_eq!(log.get(), vec![false]);
6332
6333 // Show → active → activation signal true.
6334 visible.set(true);
6335 tree.layout(SizeProposal::exact(100.0, 100.0));
6336 assert_eq!(log.get(), vec![false, true]);
6337
6338 // Redundant relayout while active fires nothing new.
6339 tree.layout(SizeProposal::exact(100.0, 100.0));
6340 assert_eq!(log.get(), vec![false, true]);
6341 }
6342
6343 /// **A node parked and re-woken before the flush never looks dormant.**
6344 ///
6345 /// `pending_activation_changes` is an append-only queue, so this records
6346 /// two edges; replaying them in order would hand observers a `false` that
6347 /// was already superseded — for a state signal that is a lie, not a
6348 /// history. `present_in_tree_modal_request` takes exactly this route on
6349 /// every dialog (build the content, park it, mount the scrim, wake it,
6350 /// *then* move focus in), and the stale `false` landed after the focus
6351 /// dispatch: a text editor's dormancy handler wiped the focus it had just
6352 /// been granted and the dialog opened with no caret.
6353 #[test]
6354 fn a_park_and_wake_inside_one_batch_fires_nothing() {
6355 let mut tree = WidgetTree::new();
6356 let log = Signal::new(Vec::<bool>::new());
6357 let probe = tree.add(ActivationProbe { log: log.clone() });
6358 tree.layout(SizeProposal::exact(100.0, 100.0));
6359 assert_eq!(log.get(), Vec::<bool>::new());
6360
6361 tree.set_dormant(probe);
6362 tree.activate(probe);
6363 tree.layout(SizeProposal::exact(100.0, 100.0));
6364 assert_eq!(
6365 log.get(),
6366 Vec::<bool>::new(),
6367 "a node that ends the batch where it started never observably \
6368 changed — firing the intermediate `false` makes observers act on \
6369 a state that was never visible",
6370 );
6371
6372 // The converse still reports: a batch with a *net* transition fires
6373 // once, with the state the node actually ended in.
6374 tree.activate(probe);
6375 tree.set_dormant(probe);
6376 tree.layout(SizeProposal::exact(100.0, 100.0));
6377 assert_eq!(
6378 log.get(),
6379 vec![false],
6380 "a net Active→Dormant batch must still report, exactly once",
6381 );
6382
6383 tree.activate(probe);
6384 tree.layout(SizeProposal::exact(100.0, 100.0));
6385 assert_eq!(log.get(), vec![false, true]);
6386 }
6387}
6388
6389#[cfg(test)]
6390mod visible_when_builder_tests {
6391 use super::*;
6392 use crate::signal::{Prop, Signal};
6393 use crate::widget_builder::WidgetBuilder;
6394
6395 /// `.visible_when(signal)` on any widget builder threads a *bound*
6396 /// visibility prop onto the inserted node — so `teksu!`'s property form
6397 /// (`Widget { visible_when: sig }`) reaches the same `node.visible_state`
6398 /// slot as the imperative `ctx.visible_when(id, sig)`.
6399 #[test]
6400 fn visible_when_builder_binds_node_visibility() {
6401 let mut tree = WidgetTree::new();
6402 let shown = Signal::new(false);
6403 let id = tree.add(crate::test_widgets::FillWidget::new().visible_when(shown.clone()));
6404
6405 let node = tree.arena.get(id).expect("node exists");
6406 assert!(
6407 matches!(node.visible_state, Some(Prop::Bound(_))),
6408 "`.visible_when(Signal)` must store a bound visibility prop"
6409 );
6410 }
6411
6412 /// A static `bool` is accepted too (`Prop::Static`), matching
6413 /// `ctx.visible_when` / `access_hidden` semantics.
6414 #[test]
6415 fn visible_when_builder_accepts_static_bool() {
6416 let mut tree = WidgetTree::new();
6417 let id = tree.add(crate::test_widgets::FillWidget::new().visible_when(false));
6418
6419 let node = tree.arena.get(id).expect("node exists");
6420 assert!(matches!(node.visible_state, Some(Prop::Static(false))));
6421 }
6422}
6423
6424#[cfg(test)]
6425mod text_scale_tests {
6426 use super::*;
6427
6428 #[test]
6429 fn effective_theme_starts_equal_to_theme() {
6430 let tree = WidgetTree::new();
6431 assert_eq!(
6432 tree.effective_theme.typography.body.size,
6433 tree.theme.typography.body.size
6434 );
6435 assert_eq!(tree.user_text_scale(), 1.0);
6436 }
6437
6438 #[test]
6439 fn effective_text_scale_and_signal_track_the_combined_factor() {
6440 let mut tree = WidgetTree::new();
6441 assert_eq!(tree.effective_text_scale(), 1.0);
6442 assert_eq!(tree.text_scale_signal().get(), 1.0);
6443
6444 tree.set_user_text_scale(1.5);
6445 assert!((tree.effective_text_scale() - 1.5).abs() < 0.001);
6446 assert!((tree.text_scale_signal().get() - 1.5).abs() < 0.001);
6447
6448 // OS preference multiplies in.
6449 tree.set_accessibility_preferences(false, false, 2.0);
6450 assert!((tree.effective_text_scale() - 3.0).abs() < 0.01);
6451 assert!((tree.text_scale_signal().get() - 3.0).abs() < 0.01);
6452 }
6453
6454 #[test]
6455 fn set_user_text_scale_scales_effective_typography() {
6456 let mut tree = WidgetTree::new();
6457 let base = tree.theme.typography.body.size;
6458 tree.set_user_text_scale(1.5);
6459 assert!((tree.effective_theme.typography.body.size - base * 1.5).abs() < 0.001);
6460 // The unscaled base theme is untouched.
6461 assert_eq!(tree.theme.typography.body.size, base);
6462 }
6463
6464 #[test]
6465 fn set_theme_preserves_existing_user_scale() {
6466 let mut tree = WidgetTree::new();
6467 tree.set_user_text_scale(2.0);
6468 let dark = crate::presets::intui::dark();
6469 let dark_base = dark.typography.body.size;
6470 tree.set_theme(dark);
6471 assert!((tree.effective_theme.typography.body.size - dark_base * 2.0).abs() < 0.001);
6472 }
6473
6474 #[test]
6475 fn os_text_scale_multiplies_with_user_scale() {
6476 let mut tree = WidgetTree::new();
6477 let base = tree.theme.typography.body.size;
6478 tree.set_user_text_scale(1.5);
6479 // OS preference reports 1.2 → combined 1.8.
6480 tree.set_accessibility_preferences(false, false, 1.2);
6481 assert!((tree.effective_theme.typography.body.size - base * 1.8).abs() < 0.01);
6482 }
6483
6484 #[test]
6485 fn same_scale_is_a_noop_and_factor_is_clamped() {
6486 let mut tree = WidgetTree::new();
6487 tree.set_user_text_scale(1.5);
6488 // Re-setting the same value should not panic / change anything.
6489 tree.set_user_text_scale(1.5);
6490 assert_eq!(tree.user_text_scale(), 1.5);
6491 // Out-of-range clamps into [0.25, 8.0].
6492 tree.set_user_text_scale(100.0);
6493 assert_eq!(tree.user_text_scale(), 8.0);
6494 }
6495}
6496
6497/// Covers the `WidgetTree`-level facts
6498/// `teksilo_app::WindowManager::request_redraw_needing_render` (the
6499/// targeted cross-window redraw added for shared-`Signal` dispatch
6500/// fan-out) relies on: `needs_reconcile()`, `reconcile()` and
6501/// `needs_render()`, in isolation. The sweep's per-window step is tested in
6502/// `teksilo_app`'s `cross_window` module, over these same trees.
6503#[cfg(test)]
6504mod cross_window_redraw_signal_tests {
6505 use super::*;
6506 use crate::signal::Signal;
6507 use crate::test_widgets::{FillWidget, StackWidget};
6508 use teksilo_canvas::SizeProposal;
6509
6510 /// The premise the fix acts on, AND the trap a naive fix would fall
6511 /// into. A `Signal` shared by two independent trees (standing in for
6512 /// two windows) is supposed to dirty both when mutated, even though
6513 /// only one of them is the tree whose dispatch made the mutation —
6514 /// but `Signal::set` only flips a dirty flag on the signal itself and
6515 /// in the `BindingRegistry`; nothing walks that into a tree's
6516 /// `needs_layout` / `needs_paint` bits (what `needs_render()` reads)
6517 /// except that tree's OWN reconcile, run by its `reconcile()` or at
6518 /// the top of its OWN `layout()`. So immediately after the mutation,
6519 /// with neither tree having reconciled, BOTH read clean: a naive
6520 /// "just check `needs_render()`" cross-window redraw would see
6521 /// nothing to do and stay a permanent no-op. Once tree B reconciles,
6522 /// the same mutation is finally visible there. This test reconciles
6523 /// through `layout()`, the frame's path;
6524 /// `reconcile_makes_a_shared_write_visible_without_laying_out` does it
6525 /// through `reconcile()`, the sweep's.
6526 ///
6527 /// Each tree wraps its gated leaf in a `StackWidget` parent (rather
6528 /// than gating a bare root leaf) so the fact under test — an ACTIVE
6529 /// widget ending up dirty — is unambiguous: `any_needs_layout()` /
6530 /// `any_needs_paint()` only ever look at `Active` nodes, and a leaf
6531 /// that itself goes dormant is deliberately excluded from both (a
6532 /// hidden widget has nothing to paint). What must go dirty here is
6533 /// the STILL-ACTIVE stack, via `mark_ancestors_need_layout` — the
6534 /// same mechanism that makes a real window's content re-flow around
6535 /// a child that just appeared or disappeared.
6536 #[test]
6537 fn a_shared_signal_mutation_only_shows_up_after_that_trees_own_layout_reconciles_it() {
6538 let shared = Signal::new(true);
6539
6540 let mut tree_a = WidgetTree::new();
6541 let stack_a = tree_a.add(StackWidget::new());
6542 let id_a = tree_a.add_child(stack_a, FillWidget::new());
6543 tree_a.visible_when(id_a, shared.clone());
6544
6545 let mut tree_b = WidgetTree::new();
6546 let stack_b = tree_b.add(StackWidget::new());
6547 let id_b = tree_b.add_child(stack_b, FillWidget::new());
6548 tree_b.visible_when(id_b, shared.clone());
6549
6550 let proposal = SizeProposal::exact(100.0, 100.0);
6551
6552 // Bring both to the same clean baseline a real event loop reaches
6553 // after its initial layout + paint.
6554 tree_a.layout(proposal);
6555 tree_a.render();
6556 tree_b.layout(proposal);
6557 tree_b.render();
6558 assert!(!tree_a.needs_render(), "precondition: tree A starts clean");
6559 assert!(!tree_b.needs_render(), "precondition: tree B starts clean");
6560
6561 // Simulate a handler mutating the shared Signal during tree A's
6562 // dispatch. Neither tree re-runs layout() here yet.
6563 shared.set(false);
6564
6565 assert!(
6566 !tree_a.needs_render(),
6567 "the mutation alone does not retroactively dirty tree A either — \
6568 a Signal write cannot poke an arena directly, only the next \
6569 process_state_changes (inside layout()) can"
6570 );
6571 assert!(
6572 !tree_b.needs_render(),
6573 "and tree B reads exactly as clean as tree A does at this point — \
6574 checking needs_render() without reconciling first cannot tell them apart"
6575 );
6576
6577 // ...but they are NOT indistinguishable to `needs_reconcile()`,
6578 // which is what `request_redraw_needing_render` actually gates
6579 // its reconcile on. Both trees observe the shared Signal, so
6580 // both report pending reactive work here — and asking is
6581 // read-only, so asking tree A first does not answer for tree B.
6582 assert!(
6583 tree_a.needs_reconcile() && tree_b.needs_reconcile(),
6584 "both trees must report pending reactive work from the shared write"
6585 );
6586
6587 // Tree B's own frame: its layout reconciles first, which is what
6588 // walks a pending Signal-driven change into the arena.
6589 tree_b.layout(proposal);
6590
6591 assert!(
6592 tree_b.needs_render(),
6593 "tree B, which merely OBSERVES the shared Signal, is now dirty — \
6594 this is the cross-tree fan-out request_redraw_needing_render \
6595 exists to notice (via its own reconcile-then-check) and repaint"
6596 );
6597 assert!(
6598 !tree_b.needs_reconcile(),
6599 "and having reconciled, tree B's gate closes again"
6600 );
6601 assert!(
6602 tree_a.needs_reconcile(),
6603 "while tree A — which has NOT reconciled — is still waiting; one \
6604 window's reconcile must never close another's gate"
6605 );
6606 }
6607
6608 /// The gate `request_redraw_needing_render` asks must stay SHUT for
6609 /// a window with nothing reactive pending: that method runs after
6610 /// every dispatched event, for every open window, and an open gate
6611 /// costs a reconcile, or a tick for a window that draws nothing.
6612 #[test]
6613 fn needs_reconcile_is_false_for_an_idle_tree() {
6614 let shared = Signal::new(true);
6615 let mut idle = WidgetTree::new();
6616 let stack = idle.add(StackWidget::new());
6617 let leaf = idle.add_child(stack, FillWidget::new());
6618 idle.visible_when(leaf, shared.clone());
6619 idle.layout(SizeProposal::exact(100.0, 100.0));
6620 idle.render();
6621
6622 assert!(!idle.needs_reconcile(), "nothing written — gate shut");
6623 assert!(!idle.needs_reconcile(), "and asking does not open it");
6624
6625 shared.set(false);
6626 assert!(idle.needs_reconcile(), "a write opens it");
6627 idle.layout(SizeProposal::exact(100.0, 100.0));
6628 assert!(!idle.needs_reconcile(), "reconciling closes it again");
6629 }
6630
6631 /// A *pending* `animate_to` contributes no scheduler deadline until
6632 /// `process_pending_animations` promotes it, so `next_timer_deadline`
6633 /// (and therefore `request_redraw_due`) cannot see it. The gate must,
6634 /// or arming an animation from another window's handler would leave
6635 /// it parked until something unrelated woke the window.
6636 #[test]
6637 fn needs_reconcile_sees_an_animation_armed_but_not_yet_started() {
6638 let mut tree = WidgetTree::new();
6639 let id = tree.add(FillWidget::new());
6640 tree.layout(SizeProposal::exact(50.0, 50.0));
6641 tree.render();
6642
6643 // Registered but deliberately NOT bound to any widget, so the
6644 // binding-registry term cannot be what notices it.
6645 let anim = Signal::new_animated(0.0_f32);
6646 tree.register_animated_signal(&anim, id);
6647 assert!(!tree.needs_reconcile(), "precondition: nothing armed yet");
6648
6649 anim.animate_to(
6650 1.0,
6651 std::time::Duration::from_millis(200),
6652 teksilo_tokens::Easing::Linear,
6653 );
6654 assert!(
6655 tree.needs_reconcile(),
6656 "an armed-but-unstarted animation is reactive work only layout() can pick up"
6657 );
6658 assert!(
6659 anim.has_pending_animation(),
6660 "and asking must not have consumed the request"
6661 );
6662
6663 tree.layout(SizeProposal::exact(50.0, 50.0));
6664 assert!(
6665 !anim.has_pending_animation(),
6666 "the reconcile promoted it into the scheduler"
6667 );
6668 }
6669
6670 /// An animation armed *after* the wall clock has overtaken the simulated one
6671 /// must still run.
6672 ///
6673 /// `layout` promotes a pending `animate_to` into the scheduler; once
6674 /// `tick_animations` is driving the tree, the scheduler is only ever ticked at
6675 /// `sim_clock`. Stamping the promotion with `Instant::now()` therefore put the
6676 /// start in the scheduler's *future* the moment a test's real time outran the
6677 /// simulated time it had asked for — and a start in the future does not run
6678 /// slow, it does not run at all. That made animated headless tests a function
6679 /// of machine load: green run alone, frozen once a full suite filled the cores
6680 /// and stretched each test's wall-clock time past its simulated budget.
6681 ///
6682 /// The two clocks below are the shape of that: 90 ms simulated against at
6683 /// least 100 ms real, so simulated time never catches up. Under the old
6684 /// behaviour the animation stays pinned at its start value forever.
6685 #[test]
6686 fn an_animation_armed_after_real_time_outran_the_sim_clock_still_runs() {
6687 let mut tree = WidgetTree::new();
6688 let id = tree.add(FillWidget::new());
6689 tree.layout(SizeProposal::exact(50.0, 50.0));
6690
6691 // Put the tree in simulated time, then let the wall clock get ahead of it.
6692 tree.tick_animations(std::time::Duration::from_millis(10));
6693 std::thread::sleep(std::time::Duration::from_millis(100));
6694
6695 let anim = Signal::new_animated(0.0_f32);
6696 tree.register_animated_signal(&anim, id);
6697 anim.animate_to(
6698 1.0,
6699 std::time::Duration::from_millis(50),
6700 teksilo_tokens::Easing::Linear,
6701 );
6702 tree.layout(SizeProposal::exact(50.0, 50.0));
6703
6704 // 80 ms of simulated time against a 50 ms animation: comfortably finished
6705 // on the only clock the scheduler is ever ticked with, and still short of
6706 // the ~100 ms of real time that has passed.
6707 tree.tick_animations(std::time::Duration::from_millis(80));
6708
6709 assert_eq!(
6710 anim.get(),
6711 1.0,
6712 "the animation must be measured against the clock it is ticked with, \
6713 not the wall clock that has already run past it"
6714 );
6715 assert!(
6716 !tree.has_active_animations(),
6717 "and having reached its target it must be off the scheduler"
6718 );
6719 }
6720
6721 /// A layout pass on a simulated tree advances no animation.
6722 ///
6723 /// The mirror image of the test above, and the other half of the same
6724 /// contract: `layout` both **promotes** a pending `animate_to` and
6725 /// **ticks** the scheduler, and it has to do both against the same clock.
6726 /// Promoting at `sim_clock` while ticking at `Instant::now()` hands the
6727 /// freshly promoted animation an elapsed time equal to the tree's entire
6728 /// wall-clock age — so it finishes inside the very layout pass that started
6729 /// it, and how much of it a test ever observes depends on how long that
6730 /// test took to get there.
6731 ///
6732 /// The 120 ms slept below is what the wall clock would contribute; the
6733 /// tween is 100 ms, so under the old behaviour it is already over before
6734 /// the caller advances anything.
6735 #[test]
6736 fn a_layout_pass_on_a_simulated_tree_advances_no_animation() {
6737 let mut tree = WidgetTree::new();
6738 let id = tree.add(FillWidget::new());
6739 tree.layout(SizeProposal::exact(50.0, 50.0));
6740
6741 // Put the tree on the simulated clock, then let real time run past the
6742 // whole duration of the animation that is about to be armed.
6743 tree.advance_time(std::time::Duration::from_millis(1));
6744 std::thread::sleep(std::time::Duration::from_millis(120));
6745
6746 let anim = Signal::new_animated(0.0_f32);
6747 tree.register_animated_signal(&anim, id);
6748 anim.animate_to(
6749 100.0,
6750 std::time::Duration::from_millis(100),
6751 teksilo_tokens::Easing::Linear,
6752 );
6753 tree.layout(SizeProposal::exact(50.0, 50.0));
6754
6755 assert_eq!(
6756 anim.get(),
6757 0.0,
6758 "a layout pass promotes the animation; it does not also age it by \
6759 however long the tree has been alive"
6760 );
6761
6762 // It moves when, and only when, the clock is advanced.
6763 tree.advance_time(std::time::Duration::from_millis(50));
6764 assert!(
6765 (anim.get() - 50.0).abs() < 2.0,
6766 "half of a 100 ms linear tween: {}",
6767 anim.get()
6768 );
6769 }
6770
6771 /// `needs_render()` (paint/layout dirt only) must stay `false` while a
6772 /// per-frame `Signal<f32>` animation is merely *running*, with nothing
6773 /// new to paint. `request_redraw_needing_render` filters on
6774 /// `needs_render()`, not the broader `needs_redraw()`, precisely so a
6775 /// window with a live animation isn't forced into an extra immediate
6776 /// redraw on every sibling-window event — that would defeat the 60 Hz
6777 /// `WaitUntil` pacing those animations already get elsewhere and
6778 /// reintroduce the uncapped free-running redraw bug that pacing was
6779 /// written to remove.
6780 #[test]
6781 fn needs_render_excludes_a_running_animation_with_no_dirty_paint() {
6782 let mut tree = WidgetTree::new();
6783 let id = tree.add(FillWidget::new());
6784 tree.layout(SizeProposal::exact(50.0, 50.0));
6785 tree.render();
6786 assert!(!tree.needs_render(), "precondition: tree starts clean");
6787 assert!(!tree.needs_redraw(), "precondition: nothing running yet");
6788
6789 let anim = Signal::new_animated(0.0_f32);
6790 tree.register_animated_signal(&anim, id);
6791 anim.animate_to(
6792 1.0,
6793 std::time::Duration::from_millis(200),
6794 teksilo_tokens::Easing::Linear,
6795 );
6796 // `process_pending_animations` (which picks up the pending
6797 // `animate_to` and starts it on the scheduler) runs inside `layout`.
6798 tree.layout(SizeProposal::exact(50.0, 50.0));
6799
6800 assert!(
6801 tree.needs_redraw(),
6802 "an animation just started, so needs_redraw() (has_running()) must be true"
6803 );
6804 assert!(
6805 !tree.needs_render(),
6806 "but nothing is actually dirty for paint/layout — needs_render() must stay false, \
6807 which is the whole point of using it (not needs_redraw()) as the cross-window filter"
6808 );
6809 }
6810
6811 /// `reconcile()` answers the sweep's question without a layout: the tree
6812 /// that only observes a shared write comes out of it needing a render,
6813 /// and no layout pass has run. The write flips a `visible_when` gate, so
6814 /// it also reports a structural layout, and the layout that follows finds
6815 /// the marks and parks the leaf.
6816 #[test]
6817 fn reconcile_makes_a_shared_write_visible_without_laying_out() {
6818 let shared = Signal::new(true);
6819
6820 let mut tree_a = WidgetTree::new();
6821 let stack_a = tree_a.add(StackWidget::new());
6822 let id_a = tree_a.add_child(stack_a, FillWidget::new());
6823 tree_a.visible_when(id_a, shared.clone());
6824
6825 let mut tree_b = WidgetTree::new();
6826 let stack_b = tree_b.add(StackWidget::new());
6827 let id_b = tree_b.add_child(stack_b, FillWidget::new());
6828 tree_b.visible_when(id_b, shared.clone());
6829
6830 let proposal = SizeProposal::exact(100.0, 100.0);
6831 for tree in [&mut tree_a, &mut tree_b] {
6832 tree.layout(proposal);
6833 tree.render();
6834 }
6835 let passes_a = tree_a.layout_passes();
6836 let passes_b = tree_b.layout_passes();
6837
6838 shared.set(false);
6839 tree_b.reconcile();
6840
6841 assert!(tree_b.needs_render(), "the observer must be redrawn");
6842 assert!(!tree_b.needs_reconcile(), "and its reconcile is done");
6843 assert_eq!(tree_b.layout_passes(), passes_b, "without a layout pass");
6844 assert!(
6845 tree_b.is_active(id_b),
6846 "nothing parked by the reconcile itself"
6847 );
6848 assert!(
6849 tree_b.needs_structural_layout(),
6850 "but the gate to apply is reported, so the sweep lays B out"
6851 );
6852 assert!(
6853 tree_a.needs_reconcile(),
6854 "one tree's reconcile leaves the other tree's pending"
6855 );
6856 assert_eq!(tree_a.layout_passes(), passes_a);
6857
6858 // The frame: what the marks asked for is laid out and drawn.
6859 tree_b.layout(proposal);
6860 assert!(!tree_b.is_active(id_b), "the layout parks the hidden leaf");
6861 assert!(!tree_b.needs_structural_layout());
6862 tree_b.render();
6863 assert!(!tree_b.needs_render());
6864 }
6865
6866 /// A data-driven rebuild is marked by the reconcile, reported as
6867 /// structural, and carried out by a layout. Rebuilding in the reconcile
6868 /// would put fresh children with no bounds under the pointer until a
6869 /// layout gave them some.
6870 #[test]
6871 fn reconcile_marks_a_rebuild_and_leaves_it_to_the_layout() {
6872 #[derive(Debug)]
6873 struct Rebuilt {
6874 data: Signal<u32>,
6875 builds: std::rc::Rc<std::cell::Cell<u32>>,
6876 }
6877 impl crate::widget::Widget for Rebuilt {
6878 fn build(&mut self, ctx: &mut crate::build_context::BuildContext) -> Vec<WidgetId> {
6879 self.data.bind_to(
6880 ctx.self_id(),
6881 ctx.binding_registry(),
6882 crate::binding::BindingLevel::Rebuild,
6883 );
6884 self.builds.set(self.builds.get() + 1);
6885 vec![ctx.add(FillWidget::new())]
6886 }
6887 fn layout_response(
6888 &self,
6889 proposal: SizeProposal,
6890 _ctx: &crate::widget::LayoutContext,
6891 ) -> crate::widget::LayoutResponse {
6892 proposal.resolve(10.0, 10.0).into()
6893 }
6894 }
6895
6896 let data = Signal::new(0_u32);
6897 let builds = std::rc::Rc::new(std::cell::Cell::new(0));
6898 let mut tree = WidgetTree::new();
6899 let stack = tree.add(StackWidget::new());
6900 let rebuilt = tree.add_child(
6901 stack,
6902 Rebuilt {
6903 data: data.clone(),
6904 builds: builds.clone(),
6905 },
6906 );
6907 let proposal = SizeProposal::exact(100.0, 100.0);
6908 tree.layout(proposal);
6909 tree.render();
6910 let children_before = tree.children(rebuilt);
6911 let built = builds.get();
6912 let passes = tree.layout_passes();
6913
6914 data.set(1);
6915 tree.reconcile();
6916
6917 assert!(
6918 tree.needs_render(),
6919 "the rebuild shows, so the window is poked"
6920 );
6921 assert_eq!(builds.get(), built, "but nothing is rebuilt yet");
6922 assert_eq!(tree.children(rebuilt), children_before);
6923 assert_eq!(tree.layout_passes(), passes);
6924 assert!(
6925 tree.needs_structural_layout(),
6926 "the rebuild is reported, so the sweep lays the window out"
6927 );
6928
6929 tree.layout(proposal);
6930 assert_eq!(builds.get(), built + 1, "the layout rebuilds it");
6931 assert_ne!(tree.children(rebuilt), children_before);
6932 assert!(!tree.needs_structural_layout());
6933 }
6934
6935 /// What a drag or a selection writes on every move, a repaint or a
6936 /// relayout of a widget that stays where it is, is not structural: the
6937 /// sweep leaves it to the frame.
6938 #[test]
6939 fn paint_and_relayout_marks_need_no_structural_layout() {
6940 let paint = Signal::new(0_u32);
6941 let relayout = Signal::new(0_u32);
6942 let mut tree = WidgetTree::new();
6943 let stack = tree.add(StackWidget::new());
6944 let painted = tree.add_child(stack, FillWidget::new());
6945 let relaid = tree.add_child(stack, FillWidget::new());
6946 paint.bind_to(
6947 painted,
6948 tree.binding_registry(),
6949 crate::binding::BindingLevel::RepaintOnly,
6950 );
6951 relayout.bind_to(
6952 relaid,
6953 tree.binding_registry(),
6954 crate::binding::BindingLevel::Relayout,
6955 );
6956 tree.layout(SizeProposal::exact(100.0, 100.0));
6957 tree.render();
6958
6959 paint.set(1);
6960 relayout.set(1);
6961 tree.reconcile();
6962
6963 assert!(tree.needs_render());
6964 assert!(!tree.needs_structural_layout());
6965 }
6966
6967 /// A focus request for a dormant node waits for a layout to wake it, and
6968 /// the next key must find it there: structural.
6969 #[test]
6970 fn a_focus_request_for_a_dormant_node_needs_a_structural_layout() {
6971 let shown = Signal::new(false);
6972 let mut tree = WidgetTree::new();
6973 let stack = tree.add(StackWidget::new());
6974 let field = tree.add_child(stack, FillWidget::new());
6975 tree.visible_when(field, shown.clone());
6976 let proposal = SizeProposal::exact(100.0, 100.0);
6977 tree.layout(proposal);
6978 assert!(!tree.needs_structural_layout(), "precondition: settled");
6979
6980 tree.focus(field);
6981 assert!(tree.needs_structural_layout(), "the request waits");
6982 shown.set(true);
6983 tree.layout(proposal);
6984 assert_eq!(tree.focused(), Some(field), "the layout lands it");
6985 assert!(!tree.needs_structural_layout());
6986 }
6987
6988 /// A rebuild marked on a dormant node waits for the pass that wakes it,
6989 /// and no event reaches its structure meanwhile: not structural.
6990 #[test]
6991 fn a_rebuild_mark_on_a_dormant_node_needs_no_structural_layout() {
6992 let mut tree = WidgetTree::new();
6993 let stack = tree.add(StackWidget::new());
6994 let parked = tree.add_child(stack, FillWidget::new());
6995 tree.visible_when(parked, false);
6996 tree.layout(SizeProposal::exact(100.0, 100.0));
6997 assert!(!tree.is_active(parked), "precondition: parked");
6998
6999 tree.arena_mark_needs_rebuild_for_testing(parked);
7000 assert!(!tree.needs_structural_layout());
7001 tree.arena_mark_needs_rebuild_for_testing(stack);
7002 assert!(tree.needs_structural_layout(), "an active one is");
7003 }
7004
7005 /// A rebuild written while a press holds its capture is left undone by
7006 /// the pass, which still counts its mark as laid out. Held, it asks for
7007 /// no layout per event; once the release ends the capture, it is
7008 /// structural again, so the sweep lays the window out before the next
7009 /// event reaches the old children.
7010 #[test]
7011 fn a_rebuild_held_back_for_a_capture_is_structural_once_released() {
7012 #[derive(Debug)]
7013 struct Rebuilt {
7014 data: Signal<u32>,
7015 builds: std::rc::Rc<std::cell::Cell<u32>>,
7016 }
7017 impl crate::widget::Widget for Rebuilt {
7018 fn build(&mut self, ctx: &mut crate::build_context::BuildContext) -> Vec<WidgetId> {
7019 self.data.bind_to(
7020 ctx.self_id(),
7021 ctx.binding_registry(),
7022 crate::binding::BindingLevel::Rebuild,
7023 );
7024 self.builds.set(self.builds.get() + 1);
7025 use crate::widget_builder::WidgetBuilder;
7026 vec![ctx.add(FillWidget::new().on_tap(|_event, _ctx| {}))]
7027 }
7028 fn layout_response(
7029 &self,
7030 proposal: SizeProposal,
7031 _ctx: &crate::widget::LayoutContext,
7032 ) -> crate::widget::LayoutResponse {
7033 proposal.resolve(100.0, 100.0).into()
7034 }
7035 }
7036
7037 let data = Signal::new(0_u32);
7038 let builds = std::rc::Rc::new(std::cell::Cell::new(0));
7039 let mut tree = WidgetTree::new();
7040 tree.add(Rebuilt {
7041 data: data.clone(),
7042 builds: builds.clone(),
7043 });
7044 let proposal = SizeProposal::exact(100.0, 100.0);
7045 tree.layout(proposal);
7046 tree.render();
7047 let built = builds.get();
7048 let at = teksilo_canvas::Point::new(10.0, 10.0);
7049 tree.enter_simulated_mode();
7050
7051 tree.pointer_down_button(at, crate::event::PointerButton::Primary);
7052 assert!(
7053 tree.captures_defer_rebuilds(),
7054 "precondition: the press captures"
7055 );
7056 data.set(1);
7057 tree.reconcile();
7058 assert!(tree.needs_structural_layout(), "a new mark");
7059 tree.layout(proposal);
7060 assert_eq!(builds.get(), built, "held back for the capture");
7061 assert!(
7062 !tree.needs_structural_layout(),
7063 "and no layout per event while it is held"
7064 );
7065
7066 tree.pointer_up_button(at, crate::event::PointerButton::Primary);
7067 assert!(!tree.captures_defer_rebuilds());
7068 assert!(
7069 tree.needs_structural_layout(),
7070 "the release lets it go ahead"
7071 );
7072 tree.layout(proposal);
7073 assert_eq!(builds.get(), built + 1, "the layout rebuilds it");
7074 assert!(!tree.needs_structural_layout());
7075 }
7076
7077 /// An `animate_to` armed from another window's handler is started by the
7078 /// reconcile, so its deadline wakes this window, with no layout run.
7079 #[test]
7080 fn reconcile_starts_a_pending_animation() {
7081 let mut tree = WidgetTree::new();
7082 let id = tree.add(FillWidget::new());
7083 tree.layout(SizeProposal::exact(50.0, 50.0));
7084 tree.render();
7085 let passes = tree.layout_passes();
7086
7087 let anim = Signal::new_animated(0.0_f32);
7088 tree.register_animated_signal(&anim, id);
7089 anim.animate_to(
7090 1.0,
7091 std::time::Duration::from_millis(200),
7092 teksilo_tokens::Easing::Linear,
7093 );
7094 assert!(tree.next_timer_deadline().is_none(), "not started yet");
7095
7096 tree.reconcile();
7097
7098 assert!(!anim.has_pending_animation(), "promoted to the scheduler");
7099 assert!(
7100 tree.next_timer_deadline().is_some(),
7101 "its deadline now wakes the window"
7102 );
7103 assert!(!tree.needs_reconcile());
7104 assert_eq!(tree.layout_passes(), passes);
7105 }
7106}
7107
7108#[cfg(test)]
7109mod effective_enabled_signal_tests {
7110 use super::*;
7111 use crate::build_context::BuildContext;
7112 use crate::signal::Signal;
7113 use crate::widget::{LayoutContext, LayoutResponse, Widget};
7114 use std::cell::RefCell;
7115 use std::rc::Rc;
7116 use teksilo_canvas::SizeProposal;
7117
7118 type SignalSlot = Rc<RefCell<Option<Signal<bool>>>>;
7119
7120 /// A leaf that opts into `effective_enabled_signal` from inside its own
7121 /// `build()` — the only way real widgets use it, and the case that was
7122 /// broken. It publishes the handle so the test can read the live value.
7123 #[derive(Debug)]
7124 struct EnabledProbe {
7125 out: SignalSlot,
7126 }
7127
7128 impl Widget for EnabledProbe {
7129 fn build(&mut self, ctx: &mut BuildContext) -> Vec<WidgetId> {
7130 let id = ctx.self_id();
7131 let sig = ctx.effective_enabled_signal(id);
7132 // Also pins that the signal is *mutable*: the previous derived
7133 // implementation panicked here with "observe() is only supported
7134 // on mutable signals", which is why widgets could not use
7135 // `ctx.effect` to react to being disabled.
7136 ctx.effect(&sig, |_| {});
7137 *self.out.borrow_mut() = Some(sig);
7138 Vec::new()
7139 }
7140
7141 fn layout_response(&self, proposal: SizeProposal, _ctx: &LayoutContext) -> LayoutResponse {
7142 proposal.resolve(10.0, 10.0).into()
7143 }
7144 }
7145
7146 /// A composite that adds the probe through the ordinary `ctx.add` idiom, so
7147 /// the child is inserted PARENTLESS and builds before its parent link is
7148 /// wired — the exact situation that defeated the old
7149 /// walk-the-ancestors-at-call-time implementation.
7150 #[derive(Debug)]
7151 struct Form {
7152 enabled: Signal<bool>,
7153 out: SignalSlot,
7154 }
7155
7156 impl Widget for Form {
7157 fn build(&mut self, ctx: &mut BuildContext) -> Vec<WidgetId> {
7158 let id = ctx.self_id();
7159 ctx.enabled_when(id, self.enabled.clone());
7160 vec![ctx.add(EnabledProbe {
7161 out: self.out.clone(),
7162 })]
7163 }
7164
7165 fn layout_response(&self, proposal: SizeProposal, _ctx: &LayoutContext) -> LayoutResponse {
7166 proposal.resolve(10.0, 10.0).into()
7167 }
7168 }
7169
7170 fn mount_form(enabled: Signal<bool>) -> (WidgetTree, WidgetId, Signal<bool>) {
7171 let out: SignalSlot = Rc::new(RefCell::new(None));
7172 let mut tree = WidgetTree::new();
7173 let form = tree.add(Form {
7174 enabled,
7175 out: out.clone(),
7176 });
7177 tree.layout(SizeProposal::exact(100.0, 100.0));
7178 let sig = out.borrow().clone().expect("probe published its signal");
7179 (tree, form, sig)
7180 }
7181
7182 /// THE REGRESSION. A widget whose own `enabled` is untouched must still
7183 /// report disabled when an ANCESTOR is disabled. This failed before the
7184 /// signal became node-resident: `insert_widget` inserts the node with
7185 /// `parent: None` and wires the parent only after `build()` returns, so an
7186 /// ancestor walk done during `build()` saw an empty chain and captured
7187 /// "enabled" for the widget's whole life.
7188 #[test]
7189 fn tracks_an_ancestor_disabled_before_mount() {
7190 let (_tree, _form, sig) = mount_form(Signal::new(false));
7191 assert!(
7192 !sig.get(),
7193 "a child of a disabled ancestor must report effectively-disabled"
7194 );
7195 }
7196
7197 /// The live case: the ancestor's bound signal flips after mount. The child
7198 /// must follow, in both directions, with no rebuild.
7199 #[test]
7200 fn follows_an_ancestor_flipping_after_mount() {
7201 let enabled = Signal::new(true);
7202 let (mut tree, _form, sig) = mount_form(enabled.clone());
7203 assert!(sig.get(), "starts enabled");
7204
7205 enabled.set(false);
7206 tree.layout(SizeProposal::exact(100.0, 100.0));
7207 assert!(!sig.get(), "child follows the ancestor going disabled");
7208
7209 enabled.set(true);
7210 tree.layout(SizeProposal::exact(100.0, 100.0));
7211 assert!(sig.get(), "and follows it coming back");
7212 }
7213
7214 /// A widget's own `enabled_state` still works on its own.
7215 #[test]
7216 fn honours_the_widgets_own_state() {
7217 let out: SignalSlot = Rc::new(RefCell::new(None));
7218 let mut tree = WidgetTree::new();
7219 let probe = tree.add(EnabledProbe { out: out.clone() });
7220 tree.enabled_when(probe, false);
7221 tree.layout(SizeProposal::exact(100.0, 100.0));
7222 let sig = out.borrow().clone().unwrap();
7223 assert!(!sig.get(), "own enabled_state alone disables");
7224 }
7225
7226 /// The signal must agree with the paint-time bool the render walker
7227 /// computes. If they disagreed, role-driven chrome (which dims from
7228 /// `PaintContext::effective_enabled`) and signal-driven chrome (which dims
7229 /// from this signal) would grey out at different moments.
7230 #[test]
7231 fn agrees_with_the_paint_time_effective_enabled() {
7232 let enabled = Signal::new(true);
7233 let (mut tree, form, sig) = mount_form(enabled.clone());
7234 let probe = tree.children(form)[0];
7235
7236 for value in [false, true, false] {
7237 enabled.set(value);
7238 tree.layout(SizeProposal::exact(100.0, 100.0));
7239 assert_eq!(
7240 sig.get(),
7241 tree.is_enabled(probe),
7242 "signal and the arena's live is_enabled must agree (enabled={value})"
7243 );
7244 }
7245 }
7246
7247 /// Install-or-reuse: asking twice hands back the same signal.
7248 #[test]
7249 fn is_install_or_reuse() {
7250 let out: SignalSlot = Rc::new(RefCell::new(None));
7251 let mut tree = WidgetTree::new();
7252 let id = tree.add(EnabledProbe { out });
7253 let a = tree.effective_enabled_signal(id);
7254 let b = tree.effective_enabled_signal(id);
7255 assert!(
7256 Signal::same(&a, &b),
7257 "must hand back the same signal handle"
7258 );
7259 }
7260}
7261
7262#[cfg(test)]
7263mod density_tests {
7264 use super::*;
7265 use teksilo_tokens::{DensityPolicy, TargetDensity};
7266
7267 /// A fresh tree is Compact — today's behaviour — and reports it.
7268 #[test]
7269 fn a_fresh_tree_is_compact() {
7270 let tree = WidgetTree::new();
7271 assert_eq!(tree.input_density(), TargetDensity::Compact);
7272 assert_eq!(tree.theme().input, teksilo_tokens::InputTokens::default());
7273 assert!(tree.touch_enabled());
7274 assert_eq!(
7275 tree.density_policy(),
7276 DensityPolicy::Fixed(TargetDensity::Compact)
7277 );
7278 }
7279
7280 /// A density switch changes what the tree reports **and** dirties it at the
7281 /// rebuild level — a target size is baked in `build()`, so layout+paint
7282 /// alone cannot re-bake it.
7283 #[test]
7284 fn switching_density_reports_and_dirties_at_rebuild_level() {
7285 let mut tree = WidgetTree::new();
7286 let root = tree.add(crate::test_widgets::FillWidget::new());
7287 tree.layout(SizeProposal::exact(400.0, 300.0));
7288 assert!(
7289 tree.arena.collect_needs_rebuild().is_empty(),
7290 "a laid-out tree starts clean"
7291 );
7292
7293 tree.set_input_density(TargetDensity::Touch);
7294
7295 assert_eq!(tree.input_density(), TargetDensity::Touch);
7296 assert_eq!(tree.theme().input.target_size, 44.0);
7297 assert_eq!(tree.theme().input.grab_size, 16.0);
7298 assert!(
7299 tree.arena.collect_needs_rebuild().contains(&root),
7300 "the root must be marked for rebuild, not merely relayout"
7301 );
7302 }
7303
7304 /// Re-setting the same density must not throw away every widget id in the
7305 /// tree for nothing.
7306 #[test]
7307 fn re_setting_the_same_density_is_a_no_op() {
7308 let mut tree = WidgetTree::new();
7309 let _root = tree.add(crate::test_widgets::FillWidget::new());
7310 tree.layout(SizeProposal::exact(400.0, 300.0));
7311
7312 tree.set_input_density(TargetDensity::Compact);
7313
7314 assert!(tree.arena.collect_needs_rebuild().is_empty());
7315 }
7316
7317 /// The theme signal follows a density switch, so a `theme_signal`-bound
7318 /// widget re-resolves without its own wiring.
7319 #[test]
7320 fn the_theme_signal_follows_a_density_switch() {
7321 let mut tree = WidgetTree::new();
7322 tree.set_input_density(TargetDensity::Comfortable);
7323 assert_eq!(
7324 tree.theme_signal().get().input.density,
7325 TargetDensity::Comfortable
7326 );
7327 assert_eq!(tree.theme_signal().get().input.target_size, 32.0);
7328 }
7329
7330 /// The kill switch is state on the theme, reachable both ways, and does
7331 /// not rebuild — it changes which events are accepted, not a dimension.
7332 #[test]
7333 fn the_touch_kill_switch_round_trips_without_a_rebuild() {
7334 let mut tree = WidgetTree::new();
7335 let _root = tree.add(crate::test_widgets::FillWidget::new());
7336 tree.layout(SizeProposal::exact(400.0, 300.0));
7337
7338 tree.set_touch_enabled(false);
7339
7340 assert!(!tree.touch_enabled());
7341 assert!(!tree.theme().input.touch_enabled);
7342 assert!(!tree.theme_signal().get().input.touch_enabled);
7343 assert!(tree.arena.collect_needs_rebuild().is_empty());
7344
7345 tree.set_touch_enabled(true);
7346 assert!(tree.touch_enabled());
7347 }
7348
7349 /// The policy is stored verbatim and does not itself move the density.
7350 #[test]
7351 fn setting_a_policy_does_not_switch_the_density() {
7352 let mut tree = WidgetTree::new();
7353 let policy = DensityPolicy::FollowLastPointer {
7354 coarse: TargetDensity::Touch,
7355 fine: TargetDensity::Compact,
7356 hysteresis: std::time::Duration::from_secs(1),
7357 };
7358 tree.set_density_policy(policy);
7359
7360 assert_eq!(tree.density_policy(), policy);
7361 assert_eq!(tree.input_density(), TargetDensity::Compact);
7362 }
7363}
7364
7365#[cfg(test)]
7366mod app_callback_intent_tests {
7367 use super::*;
7368 use crate::{Action, BuildContext, Intent, LayoutContext, LayoutResponse, Widget};
7369 use std::cell::{Cell, RefCell};
7370 use std::rc::Rc;
7371 use teksilo_canvas::{Size, SizeProposal};
7372
7373 #[derive(Debug)]
7374 struct QuitActions {
7375 callback_returned: Rc<Cell<bool>>,
7376 calls: Rc<RefCell<Vec<&'static str>>>,
7377 }
7378
7379 impl Widget for QuitActions {
7380 fn build(&mut self, ctx: &mut BuildContext) -> Vec<WidgetId> {
7381 let returned = self.callback_returned.clone();
7382 let calls = self.calls.clone();
7383 ctx.register_action_global(Action::new("test.quit").on_invoke(move |_, ctx| {
7384 assert!(
7385 returned.get(),
7386 "dispatch must wait until the callback returns"
7387 );
7388 calls.borrow_mut().push("quit");
7389 ctx.send_intent(Intent::new("test.confirm"));
7390 }));
7391 let calls = self.calls.clone();
7392 ctx.register_action_global(Action::new("test.confirm").on_invoke(move |_, _| {
7393 calls.borrow_mut().push("confirm");
7394 }));
7395 vec![]
7396 }
7397
7398 fn layout_response(&self, _: SizeProposal, _: &LayoutContext) -> LayoutResponse {
7399 Size::new(0.0, 0.0).into()
7400 }
7401 }
7402
7403 #[test]
7404 fn app_callback_dispatches_quit_and_followup_without_an_input_event() {
7405 let mut tree = WidgetTree::new();
7406 let returned = Rc::new(Cell::new(false));
7407 let calls = Rc::new(RefCell::new(Vec::new()));
7408 tree.add(QuitActions {
7409 callback_returned: returned.clone(),
7410 calls: calls.clone(),
7411 });
7412 let mut ops = crate::window::NoopWindowOps;
7413 // This is the entry point WindowManager uses to evaluate a close guard.
7414 tree.run_with_event_context(&mut ops, |ctx| {
7415 ctx.send_intent(Intent::new("test.quit"));
7416 assert!(calls.borrow().is_empty());
7417 returned.set(true);
7418 });
7419 assert_eq!(&*calls.borrow(), &["quit", "confirm"]);
7420 assert!(tree.pending_intents.is_empty());
7421 tree.run_with_event_context(&mut ops, |_| {});
7422 assert_eq!(
7423 &*calls.borrow(),
7424 &["quit", "confirm"],
7425 "dispatch exactly once"
7426 );
7427 }
7428
7429 /// Answers `test.copy` by recording `name`; with `field`, also builds a
7430 /// focusable child answering it as "field", and reports the child's id.
7431 #[derive(Debug)]
7432 struct Copier {
7433 name: &'static str,
7434 calls: Rc<RefCell<Vec<&'static str>>>,
7435 field: Option<Rc<Cell<Option<WidgetId>>>>,
7436 }
7437
7438 impl Widget for Copier {
7439 fn build(&mut self, ctx: &mut BuildContext) -> Vec<WidgetId> {
7440 let (name, calls) = (self.name, self.calls.clone());
7441 ctx.register_action(Action::new("test.copy").on_invoke(move |_, _| {
7442 calls.borrow_mut().push(name);
7443 }));
7444 ctx.apply_self_handlers(
7445 crate::widget_builder::HandlerSet::new().focusable(self.field.is_none()),
7446 );
7447 let Some(field) = &self.field else {
7448 return vec![];
7449 };
7450 let id = ctx.add(Copier {
7451 name: "field",
7452 calls: self.calls.clone(),
7453 field: None,
7454 });
7455 field.set(Some(id));
7456 vec![id]
7457 }
7458
7459 fn layout_response(&self, _: SizeProposal, _: &LayoutContext) -> LayoutResponse {
7460 Size::new(0.0, 0.0).into()
7461 }
7462 }
7463
7464 /// A window's tree as `teksilo-app` builds it with a post-root hook: the
7465 /// app's root (answering `test.copy`, holding a focusable field that
7466 /// answers it too) inside a wrapper. Returns the tree, the app's root
7467 /// and the field.
7468 fn wrapped(calls: &Rc<RefCell<Vec<&'static str>>>) -> (WidgetTree, WidgetId, WidgetId) {
7469 let mut tree = WidgetTree::new();
7470 let field = Rc::new(Cell::new(None));
7471 let content = tree.add(Copier {
7472 name: "root",
7473 calls: calls.clone(),
7474 field: Some(field.clone()),
7475 });
7476 tree.add(crate::test_widgets::StackWidget::new().child(content));
7477 tree.layout(SizeProposal::exact(400.0, 300.0));
7478 assert_ne!(
7479 tree.roots().first(),
7480 Some(&content),
7481 "the wrapper is the first root"
7482 );
7483 (tree, content, field.get().expect("the field was built"))
7484 }
7485
7486 fn send_copy(ctx: &mut crate::widget::EventContext) {
7487 ctx.send_intent(Intent::new("test.copy"));
7488 }
7489
7490 #[test]
7491 fn an_app_callback_reaches_an_action_on_the_app_root_under_a_wrapper() {
7492 let calls = Rc::new(RefCell::new(Vec::new()));
7493 let (mut tree, content, _) = wrapped(&calls);
7494 let mut ops = crate::window::NoopWindowOps;
7495
7496 // Without the content root, the walk starts at the wrapper and
7497 // misses the action below it: the bug this pins.
7498 tree.run_with_event_context(&mut ops, send_copy);
7499 assert!(calls.borrow().is_empty());
7500
7501 tree.set_content_root(content);
7502 assert_eq!(tree.intent_anchor(), Some(content));
7503 tree.run_with_event_context(&mut ops, send_copy);
7504 assert_eq!(&*calls.borrow(), &["root"]);
7505 }
7506
7507 fn send_copy_from_focus(ctx: &mut crate::widget::EventContext) {
7508 ctx.send_intent_from_focus(Intent::new("test.copy"));
7509 }
7510
7511 #[test]
7512 fn a_command_from_focus_reaches_the_focused_widget_first() {
7513 let calls = Rc::new(RefCell::new(Vec::new()));
7514 let (mut tree, content, field) = wrapped(&calls);
7515 tree.set_content_root(content);
7516 let mut ops = crate::window::NoopWindowOps;
7517
7518 // Nothing focused: it starts at the app's root.
7519 tree.run_with_event_context(&mut ops, send_copy_from_focus);
7520 assert_eq!(&*calls.borrow(), &["root"]);
7521
7522 // The focused field answers before the root does.
7523 tree.focus(field);
7524 tree.run_with_event_context(&mut ops, send_copy_from_focus);
7525 assert_eq!(&*calls.borrow(), &["root", "field"]);
7526
7527 // An app callback still starts at the root, whatever has focus.
7528 tree.run_with_event_context(&mut ops, send_copy);
7529 assert_eq!(&*calls.borrow(), &["root", "field", "root"]);
7530 }
7531
7532 #[test]
7533 fn callback_on_empty_tree_does_not_leave_an_unanchored_intent() {
7534 let mut tree = WidgetTree::new();
7535 tree.run_with_event_context(&mut crate::window::NoopWindowOps, |ctx| {
7536 ctx.send_intent(Intent::new("test.quit"));
7537 });
7538 assert!(tree.pending_intents.is_empty());
7539 }
7540}