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_description_impl;
16#[cfg(test)]
17mod accessibility_description_tests;
18mod accessibility_emit_impl;
19mod accessibility_impl;
20#[cfg(test)]
21mod accessibility_proxy_tests;
22#[cfg(test)]
23mod adapter_ids_tests;
24#[cfg(test)]
25mod announcement_ring_tests;
26#[cfg(test)]
27mod announcer_tests;
28mod drag_drop_impl;
29mod focus_impl;
30mod gesture_dispatch_impl;
31#[cfg(test)]
32mod hit_targeting_tests;
33mod layout_impl;
34#[cfg(test)]
35mod modal_tests;
36mod overlay_impl;
37pub mod pan_arbiter;
38mod pointer_cancel;
39mod pointer_router;
40mod pointer_state;
41mod query_impl;
42mod rendering_impl;
43mod test_api;
44pub mod touch_route;
45#[cfg(test)]
46mod window_name_tests;
47
48struct AnimatedRegistration {
49 weak: crate::signal::WeakAnimatedSignal,
50 owner: WidgetId,
51}
52
53impl AnimatedRegistration {
54 fn same_signal(&self, signal: &crate::signal::Signal<f32>) -> bool {
55 self.weak.same_signal(signal)
56 }
57
58 fn is_alive(&self) -> bool {
59 self.weak.upgrade().is_some()
60 }
61
62 fn take_pending_animation(
63 &self,
64 ) -> Option<(
65 crate::signal::Signal<f32>,
66 crate::animation::AnimationRequest,
67 WidgetId,
68 )> {
69 let signal = self.weak.upgrade()?;
70 let request = signal.take_pending_animation()?;
71 Some((signal, request, self.owner))
72 }
73
74 /// Non-consuming counterpart to [`take_pending_animation`](Self::take_pending_animation),
75 /// for [`WidgetTree::needs_reconcile`] — which must be able to ask
76 /// "is there work here?" without doing any.
77 fn has_pending_animation(&self) -> bool {
78 self.weak
79 .upgrade()
80 .is_some_and(|signal| signal.has_pending_animation())
81 }
82}
83
84// (line 33, above `struct AnimatedRegistration`) — remove entirely
85// (line 71, above `#[allow(clippy::type_complexity)]` / `pub struct WidgetTree`)
86/// The main widget tree orchestrating arena, layout, events, accessibility, and paint.
87/// Provides both the runtime API and the headless test API.
88#[allow(clippy::type_complexity)]
89pub struct WidgetTree {
90 pub(crate) arena: WidgetArena,
91 /// Current theme value cached for `&Theme` accessors used by layout/paint
92 /// contexts and by widgets that need an immediate read. The reactive source
93 /// of truth is `theme_signal`; both are updated in lockstep by `set_theme`.
94 theme: Theme,
95 /// Reactive theme signal. Widgets that want their visual or derived state
96 /// to track theme changes bind to this signal or build derived signals via
97 /// `zip`/`map`. `set_theme` updates the signal (firing observers) without
98 /// rebuilding the widget tree, so interaction state (focus, scroll, expanded
99 /// panels, …) survives theme switches.
100 theme_signal: crate::signal::Signal<Theme>,
101 /// How the active [`TargetDensity`](teksilo_tokens::TargetDensity) is chosen. `Fixed(Compact)` by default,
102 /// so nothing switches density unless the app asks.
103 ///
104 /// `FollowLastPointer` is **stored and read by nobody**. The pointer
105 /// ingress it was written for exists — the app event loop routes contacts
106 /// into `dispatch_pointer_with_ops` — but honouring the policy means
107 /// deciding what a stray tap costs (a density switch discards every widget
108 /// id in the tree), whether a pen counts as coarse, and how the hysteresis
109 /// commits when the user simply stops touching. None of that is settled, so
110 /// the policy is a declaration the framework does not yet act on.
111 density_policy: teksilo_tokens::DensityPolicy,
112 /// User-controlled global text-scale factor (`1.0` = 100 %). Layered on top
113 /// of the OS `text_scale_factor`: the two multiply. Set via
114 /// `set_user_text_scale`; persisted by the application through
115 /// `teksilo_settings::TEXT_SCALE_KEY`.
116 user_text_scale: f32,
117 /// Cached projection of `theme` whose `typography` is scaled by
118 /// `user_text_scale * text_scale_factor`. Recomputed by
119 /// `recompute_effective_theme` whenever the theme or either scale factor
120 /// changes; the layout and paint walkers read this instead of `theme` so
121 /// all text grows uniformly. Equal to `theme` when the combined factor is 1.
122 effective_theme: Theme,
123 /// The combined `user_text_scale * text_scale_factor`, cached so the
124 /// layout/paint context construction sites don't recompute it. The single
125 /// scalar published to widgets that size from a source *other* than
126 /// `Theme.typography` (icons, the rich-text engine, calendar constants,
127 /// scene text). Written alongside `effective_theme` in
128 /// `recompute_effective_theme`.
129 effective_text_scale: f32,
130 /// Reactive mirror of `effective_text_scale`, for build-time binders that
131 /// must react to a scale change without a rebuild path of their own (e.g.
132 /// `Calendar` binds this at `Rebuild` level). Fired by
133 /// `recompute_effective_theme`.
134 text_scale_signal: crate::signal::Signal<f32>,
135 /// Reactive window-active state (`focused AND not occluded`), the
136 /// occlusion-aware companion to `WindowState::focused` (which is raw OS
137 /// focus only). The single source of truth for "is this window active",
138 /// read by `is_window_active()` and published to widgets via
139 /// `window_active_signal()` / `BuildContext::window_active*` /
140 /// `PaintContext::window_active`. Drives caret hiding, selection
141 /// desaturation and `DimWhenInactive`. Starts `true` — winit may not send
142 /// `Focused(true)` for the first window, so a window must not be born
143 /// inactive. Mutated only by `set_window_active`.
144 window_active_signal: crate::signal::Signal<bool>,
145 text_backend: Option<Rc<RefCell<dyn teksilo_canvas::TextBackend>>>,
146 focused: Option<WidgetId>,
147 /// Reactive mirror of `focused`. Same pattern as `hovered_signal`
148 /// — kept in sync via `set_focused`. Drives the inspector's Focus
149 /// tab without polling.
150 focused_signal: crate::signal::Signal<Option<WidgetId>>,
151 /// Every pointer the tree currently knows about, plus the primary and
152 /// hover-owner elections.
153 ///
154 /// Replaces the singular `hovered` / `last_pointer_position` /
155 /// `pointer_captured_by` this tree used to carry. Hover lives on the
156 /// **hover owner**'s entry (a contact never hovers), position and the
157 /// legacy singular accessors read the **primary**, and capture is per
158 /// pointer — two contacts hold independent captures, each released only by
159 /// its own Up or Cancel. See [`crate::pointer::table`].
160 pointers: crate::pointer::table::PointerTable,
161 /// Reactive mirror of the hover owner's hovered widget. Set whenever it
162 /// changes during dispatch / hit-test recovery so external observers
163 /// (notably the debug inspector's hover tooltip) can react without
164 /// polling. Held by handle so the field is a cheap clone.
165 hovered_signal: crate::signal::Signal<Option<WidgetId>>,
166 /// Reactive mirror of the kind of the pointer that most recently produced
167 /// a sample. Lets a widget switch an affordance between the mouse and the
168 /// touch form without a rebuild, and without every widget having to
169 /// remember an `on_pointer_event` of its own just to learn the modality.
170 last_pointer_kind_signal: crate::signal::Signal<teksilo_tokens::PointerKind>,
171 /// The pointer position *before* the move currently being
172 /// dispatched — i.e. the last sample that was still over the
173 /// previously-hovered widget. Read when arming an overlay's safe
174 /// triangle: the apex belongs at the point the pointer left the
175 /// anchor, not at the first sample past it (they coincide for a
176 /// real mouse, but the distinction is what keeps the cone from
177 /// degenerating to "the apex is wherever I am, so I am always
178 /// inside it").
179 previous_pointer_position: Option<teksilo_canvas::Point>,
180 /// A rebuild destroyed the focused widget: the ancestors it had inside the
181 /// subtree that owned focus, innermost first, remembered so the end of the
182 /// layout pass can land focus back inside the innermost one still alive.
183 ///
184 /// A rebuild allocates fresh `WidgetId`s for its children, so the focused
185 /// node dies and `revalidate_interaction_state` drops focus to `None`.
186 /// Leaving it there kicks the user out of the widget they were in — most
187 /// visibly, a popover that refreshes its content when it opens would throw
188 /// away the very row the popover had just focused, so the menu comes up with
189 /// no keyboard focus at all. Focus is re-entered *after* the layout walk
190 /// (see the tail of `layout_with_ops`), once the fresh children have real
191 /// bounds for the focus-driven scroll-into-view — the same shape as the
192 /// post-layout hover refresh next to it.
193 ///
194 /// The innermost survivor, not the rebuilt root: a reconciling rebuild
195 /// keeps the children it re-attaches, so the group that held focus is often
196 /// still there, and the root's first focusable descendant is the *first*
197 /// group, whichever one the user was in.
198 pending_focus_restore: Vec<WidgetId>,
199 /// The interaction anchors as of the last layout walk — the focused node,
200 /// each live pointer's captor, and an in-flight drag's source.
201 ///
202 /// A `culls_children` parent is told to keep what the user is in the
203 /// middle of, and it is only asked during layout. So the anchor set is an
204 /// *input* to that decision, and when it changes the decision is stale —
205 /// even though nothing moved and nothing resized, which is what the
206 /// idle-pass early-return keys off. Kept here so the pass can notice the
207 /// change and re-ask the culling parents it affects; see
208 /// `invalidate_culls_for_moved_interaction`.
209 last_interaction_anchors: Vec<WidgetId>,
210 last_proposal: SizeProposal,
211 pending_modal_requests: Vec<crate::modal::QueuedModalRequest>,
212 pending_modal_dismissal: bool,
213 shortcut_registry: crate::shortcut::ShortcutRegistry,
214 /// Queue of intents awaiting dispatch. Populated either by the
215 /// keystroke interception path (`dispatch_event` for KeyDown) or
216 /// by handlers calling `ctx.send_intent(...)`. Drained between
217 /// event-handler calls by [`WidgetTree::drain_pending_intents`].
218 /// The tuple carries the source widget (dispatch anchor), the
219 /// intent itself, and the firing shortcut's
220 /// `propagate_when_disabled` policy.
221 pending_intents: Vec<(WidgetId, crate::intent::Intent, bool)>,
222 /// Window-global actions registered via
223 /// [`BuildContext::register_action_global`](crate::BuildContext::register_action_global).
224 /// Consulted as a fallback at the end of every intent dispatch — *after* the
225 /// source→root walk finds no consuming node action — so an app-global command
226 /// is reachable no matter where the intent originated (a menu-bar dropdown
227 /// overlay, deep content, a global shortcut anchored at the root). Each entry
228 /// is owned by the registering widget and torn down on its rebuild/destroy,
229 /// mirroring `register_shortcut_global`.
230 global_actions: Vec<(WidgetId, crate::action::Action)>,
231 /// The widgets that edit text, registered via
232 /// [`BuildContext::register_text_surface`](crate::BuildContext::register_text_surface).
233 ///
234 /// Owned by the registering widget and torn down on its rebuild/destroy,
235 /// exactly like `global_actions` above. Read through
236 /// [`WidgetTree::focused_text_surface`] by a host that has taken a text
237 /// chord — `Ctrl+Z`, `Ctrl+C` — for itself and owes every text widget in the
238 /// tree an answer about what happens to it. See
239 /// [`crate::text_surface`] for why the framework is the only place that
240 /// question can be answered completely.
241 text_surfaces: crate::text_surface::TextSurfaces,
242 /// Currently-armed key-capture slot. `Some` when
243 /// [`WidgetTree::begin_key_capture`] has been called and the
244 /// returned [`CaptureHandle`](crate::shortcut::CaptureHandle)
245 /// is still alive. The slot is shared (via `Rc`) with the handle
246 /// so dropping the handle cancels the capture, and calling
247 /// `begin_key_capture` again creates a fresh slot without
248 /// touching the previous one (whose handle, if dropped later,
249 /// only clears its own orphaned slot).
250 key_capture: Option<crate::shortcut::KeyCaptureSlot>,
251 binding_registry: crate::binding::BindingRegistry,
252 idle_queue: crate::idle::IdleQueue,
253 /// Simulated clock for deterministic time-dependent testing.
254 ///
255 /// Its initial value is the tree's **epoch**, and [`Self::input_clock`] is
256 /// seeded from the very same `Instant` — so `EventTime::ZERO` and this
257 /// field's starting value name one moment, and the input timeline and the
258 /// animation timeline are one axis. See
259 /// [`crate::pointer::clock`] for why that matters.
260 sim_clock: std::time::Instant,
261 /// The one source of [`EventTime`](crate::pointer::EventTime)s for this
262 /// tree. A [`MonotonicClock`](crate::pointer::clock::MonotonicClock)
263 /// anchored at the tree epoch by default; a test swaps in a
264 /// [`ManualClock`](crate::pointer::clock::ManualClock) via
265 /// [`set_input_clock`](Self::set_input_clock).
266 input_clock: std::rc::Rc<dyn crate::pointer::clock::InputClock>,
267 /// What is known about the sample currently being dispatched, snapshotted
268 /// onto every [`EventContext`] built while it
269 /// runs. Holds its default — a mouse at the epoch — outside a pointer or
270 /// scroll dispatch.
271 current_input: crate::pointer::InputSnapshot,
272 /// Whether simulated time is *currently* what this tree measures against —
273 /// i.e. whether [`Self::sim_clock`], rather than the wall clock, is what
274 /// [`Self::animation_clock`] answers with and what freezes the input
275 /// timeline.
276 ///
277 /// Set by `enter_simulated_mode`, which
278 /// [`advance_time`](Self::advance_time) calls before it moves anything, and
279 /// cleared by [`resume_real_time`](Self::resume_real_time). Both axes turn
280 /// on this one flag, so the tree has one notion of "is time simulated right
281 /// now" rather than two that can disagree.
282 ///
283 /// It is not a latch. A headless test never hands the clock back, so for a
284 /// test it behaves like one: an animation may then only progress by
285 /// advancing the clock, never by the test taking a long time. A host
286 /// sharing a live tree with a real event loop — the debug automation bridge
287 /// — hands it back after every operation, and real time drives the tree
288 /// again until the next advance.
289 ///
290 /// What each axis does across the two transitions differs, because the two
291 /// carry different state. The animation scheduler holds absolute instants,
292 /// so switching axes **rebases** them (`AnimationScheduler::rebase`) and the
293 /// reading itself is simply whichever clock is in charge. The input axis
294 /// holds none, so it is the *reading* that is carried: see
295 /// [`Self::sim_input_origin`] and [`Self::sim_input_offset`].
296 sim_time_frozen: bool,
297 /// Where the input timeline stood when this tree entered simulated mode,
298 /// as `(the reading then, the `sim_clock` then)`.
299 ///
300 /// The input axis cannot simply become `sim_clock - epoch`: samples
301 /// dispatched *before* the switch were stamped from the wall clock, which
302 /// by then is ahead of `sim_clock`, so every one of them would sit in the
303 /// virtual future and no interval measured from them would ever elapse.
304 /// Continuing the axis from where it stood instead makes every stamp taken
305 /// before the switch lie in the past and every interval after it exactly
306 /// the duration advanced.
307 ///
308 /// `None` while the tree runs on real time, and also under a clock that has
309 /// no wall-clock anchor — a
310 /// [`ManualClock`](crate::pointer::clock::ManualClock) *is* the virtual
311 /// axis already, and is moved directly by `advance_time`.
312 ///
313 /// Cleared by [`resume_real_time`](Self::resume_real_time), which hands the
314 /// axis back to the wall clock with what was advanced carried forward in
315 /// [`Self::sim_input_offset`].
316 sim_input_origin: Option<(crate::pointer::EventTime, std::time::Instant)>,
317 /// How far ahead of the raw input clock this tree's input timeline runs,
318 /// having been advanced and then handed back to real time.
319 ///
320 /// Added to every reading of the clock, and **re-measured** (not
321 /// accumulated) at each hand-back as `frozen reading − raw reading`, floored
322 /// at zero. That is what makes the axis monotone across the hand-back: the
323 /// reading at the instant of
324 /// [`resume_real_time`](Self::resume_real_time) is the later of the frozen
325 /// reading it had and the raw one, and it moves with the wall clock from
326 /// there. Without it
327 /// the axis would jump *backwards* by everything that was advanced, and a
328 /// monotone [`EventTime`](crate::pointer::EventTime) is a platform
329 /// conformance invariant.
330 ///
331 /// So it is not monotone in itself: a tree that spent longer on the wall
332 /// clock than it was ever advanced is already ahead of its frozen reading
333 /// and the right offset is then zero, which is what the floor is for. It is
334 /// also dropped outright by
335 /// [`set_input_clock`](Self::set_input_clock) — it is a distance measured
336 /// against one clock's readings and means nothing against another's.
337 ///
338 /// It is also what keeps a deadline schedulable: `instant_for` subtracts it
339 /// again, so a long press armed after an advance is reported to the event
340 /// loop at a *future* `Instant` rather than one in the past that can never
341 /// ripen.
342 sim_input_offset: std::time::Duration,
343 /// Overlay manager for tooltips, menus, popovers.
344 pub(crate) overlay_manager: crate::overlay::OverlayManager,
345 /// Re-entrancy guard for the dismissal-callback drain. A callback may
346 /// dismiss another overlay, whose teardown drains again; the inner drain
347 /// returns at once and the outer loop picks up whatever it parked, so the
348 /// recursion is one level deep by construction rather than by luck.
349 pub(crate) draining_dismiss: std::cell::Cell<bool>,
350 /// Tooltip attachments, one per anchor. See [`TooltipEntry`].
351 tooltips: Vec<TooltipEntry>,
352 /// Simulated-clock end of the tooltip "reshow session". While any tip is
353 /// visible, or until this instant after the last tip dismissed, subsequent
354 /// anchors use `MotionTokens::tooltip_reshow_delay` instead of the full
355 /// initial delay (Windows `TTDT_RESHOW` behaviour).
356 tooltip_session_until_sim: Option<std::time::Instant>,
357 /// Real-clock counterpart of [`Self::tooltip_session_until_sim`].
358 tooltip_session_until_real: Option<std::time::Instant>,
359 /// The tooltip currently surfaced by keyboard menu navigation
360 /// (`show_highlight_tooltip`): `(overlay_id, content_id)`. At most one
361 /// is shown at a time; moving the highlight or closing the menu clears
362 /// it. Distinct from the hover/focus tooltip paths — this one is a
363 /// `Manual`-dismiss child of the menu overlay so a single Escape closes
364 /// the menu (and cascades the tooltip) rather than only the tooltip.
365 highlight_tooltip: Option<(crate::overlay::OverlayId, WidgetId)>,
366 /// How the currently focused widget gained focus.
367 focus_origin: Option<crate::focus::FocusOrigin>,
368 /// Every live pointer press, keyed by the node whose gesture arena took it.
369 /// The framework's press visual — see [`crate::press`] for the four things
370 /// a widget's own `PointerDown`/`PointerUp` bookkeeping cannot see.
371 presses: crate::press::PressTable,
372 /// Input-modality "focus-visible" state: `true` after keyboard input,
373 /// `false` after pointer input. Focus rings (e.g. `StandardItem`'s current
374 /// row) show only while this is `true`, the standard `:focus-visible`
375 /// behaviour — so a mouse click selects without a ring, and keyboard
376 /// navigation reveals it.
377 focus_visible: crate::signal::Signal<bool>,
378 /// Active focus-scope stack during build. A data view pushes its scope
379 /// (`begin_view_focus`) around its row loop so each row reads *its view's*
380 /// focus deterministically — independent of arena parenting, which may not
381 /// be wired yet while rows build (docked / virtualized content). Drives
382 /// focus-aware selection + focus rings in `StandardItem`.
383 view_focus_stack: Vec<crate::signal::Signal<bool>>,
384 /// Layout direction for RTL/LTR support.
385 pub(crate) layout_direction: crate::environment::LayoutDirection,
386 /// Animation scheduler for smooth animated state and signal transitions.
387 animation_scheduler: crate::animation::AnimationScheduler,
388 /// Weakly tracked animated values from both state and signal APIs.
389 animated_values: Vec<AnimatedRegistration>,
390 /// Registry of shader-driven animated quads (opt-in alternative to
391 /// `Signal<f32>::animate_looping` for decorative motion — progress
392 /// sweeps, sprite-atlas frame cycling, future pulse/shimmer). The
393 /// scheduler-style signal path stays for everything else. Per-slot
394 /// `AnimParams` are ticked and attached to every `RenderFrame`
395 /// produced by `render()` — the renderer reads them from there.
396 animated_quads: crate::animated_quad::AnimatedQuadRegistry,
397 /// Per-frame-effect scheduler. Owns the registry of widgets that
398 /// asked for a frame-tick subscription (Pulse, Cycle, …). Sits
399 /// alongside `animation_scheduler` and `animated_quads` as the
400 /// third visibility-aware motion source — they all consult the
401 /// same [`motion_visibility`](crate::motion_visibility) helpers.
402 /// After every `render()` the tree calls
403 /// `FrameTickScheduler::should_arm_frame_tick` and re-arms
404 /// `frame_tick_armed_by_subscribers` if any subscriber's owner was
405 /// painted this frame.
406 pub(crate) frame_tick_scheduler: crate::frame_tick_scheduler::FrameTickScheduler,
407 /// Live pans, live coasts, the window's pinch, and the palm watches — the
408 /// whole touch-motion layer, in one field. See
409 /// [`pan_arbiter`].
410 touch_motion: pan_arbiter::TouchMotion,
411 /// The claimant chain the next synthesised scroll is to walk.
412 ///
413 /// Armed immediately before that scroll is pushed through
414 /// [`dispatch_scroll`](Self::dispatch_scroll) and taken by the router arm
415 /// that routes it, because the two producers know different things: a pan
416 /// has a live session to read, a coast has only the chain it was launched
417 /// with. `None` for every scroll from a backend, which derives its own
418 /// chain from the sample's position.
419 armed_chain: Option<Vec<(WidgetId, crate::pointer::touch_action::PanClaim)>>,
420 /// Monotonic counter bumped at the start of each `render()` call.
421 /// Each widget's `last_painted_epoch` is set to this value whenever
422 /// the paint pass (or the cache-hit early-out) confirms the widget
423 /// intersects the window viewport. The animation scheduler uses it
424 /// to detect and pause animations for widgets that have scrolled
425 /// off-screen. Starts at `0`, which serves as the "never painted"
426 /// sentinel; tests that only call `layout()` see the gate bypass.
427 paint_epoch: u64,
428 /// Cached accessibility tree update, rebuilt only when something that
429 /// changes the AT tree has happened, not on every layout.
430 cached_a11y: Option<accesskit::TreeUpdate>,
431 /// Whether the accessibility tree needs rebuilding. Set by focus moves,
432 /// overlay changes, widget rebuilds, active↔dormant transitions,
433 /// `AccessibilityOnly` binding flips and `request_accessibility_update()`;
434 /// a plain relayout does not set it.
435 a11y_dirty: bool,
436 /// Snapshot of `shortcut_registry.version()` at the last
437 /// `sync_accessibility` call. When the live version differs the
438 /// AT cache is dirtied, so widgets that bound their announced
439 /// shortcut via `access_shortcut_id(id)` track user rebinds
440 /// without any explicit signaling from the settings UI.
441 last_synced_shortcut_version: u64,
442 /// Snapshot of `locale_signal` at the last `sync_accessibility`
443 /// call. When the locale differs the AT cache is dirtied, so
444 /// `access_label(tr!(...))` (stored as a locale-bound
445 /// `Prop<String>`) re-resolves into the announced node — even on a
446 /// same-direction switch that doesn't rebuild the composite.
447 last_synced_locale: Option<String>,
448 /// The window title the last accessibility walk named the root after.
449 /// A new title re-walks the tree, as a locale switch does, so the
450 /// window's name follows it. See `accessibility_emit_impl`.
451 last_synced_window_title: Option<String>,
452 /// Reverse map from synthetic (widget-emitted) AccessKit NodeIds
453 /// to the WidgetId that owns them. Rebuilt on every full
454 /// accessibility walk. `handle_accessibility_actions` uses this
455 /// to route an `ActionRequest` targeting a TextRun child back
456 /// to the owning rich-text editor, since synthetic NodeIds
457 /// can't be decoded back to a WidgetId by value alone.
458 pub(crate) synthetic_parent_map: std::collections::HashMap<accesskit::NodeId, WidgetId>,
459 /// Where each synthetic child sits inside its owner, for the ones that
460 /// declared their bounds in the owner's own space (a label's line
461 /// boxes, an editor's rows). A pure translation re-places them from
462 /// here; a synthetic node absent from this map — a scene item under a
463 /// view transform, which reports absolute rects — is moved by the
464 /// owner's delta instead.
465 pub(crate) synthetic_local_bounds:
466 std::collections::HashMap<accesskit::NodeId, teksilo_canvas::Rect>,
467 /// Monotonic count of accessibility walks. A consumer that has not
468 /// seen the latest one is holding a tree whose *shape* may be stale,
469 /// not merely its geometry.
470 pub(crate) a11y_walk_generation: u64,
471 /// Cached full render frame — reused when no widget needs painting.
472 /// `Rc<RenderFrame>` rather than `RenderFrame` so cache-hit frames
473 /// cost an atomic refcount bump instead of a deep clone of every
474 /// draw-command Vec. `render()` uses `Rc::make_mut` to update
475 /// `anim_params` in place when the tree is the sole owner (the
476 /// common case — the caller usually drops the previous frame
477 /// before calling render() again).
478 cached_frame: Option<std::rc::Rc<RenderFrame>>,
479 /// Dispatches that arrived while another dispatch was in flight, replayed
480 /// once the outer one completes.
481 ///
482 /// A handler that dispatches (a synthetic click, an AT action re-entering
483 /// the door) must not observe half-updated pointer state, and must not be
484 /// able to unwind the sample the outer dispatch is still standing on. So a
485 /// nested dispatch is queued here rather than run inline, and drained —
486 /// faithfully, event *and* input snapshot — after the outer sample
487 /// completes. From the caller's side nothing changes: the queue is empty
488 /// again before the top-level `dispatch_*` call returns.
489 pending_dispatch: std::collections::VecDeque<pointer_router::QueuedDispatch>,
490 /// How many dispatches are on the stack. Non-zero means "queue, do not
491 /// re-enter"; see [`Self::pending_dispatch`].
492 dispatch_depth: u32,
493 /// Pointers whose current press was cancelled and which have not pressed
494 /// again since.
495 ///
496 /// `PointerCancel` is terminal: the interaction was taken away, so an `Up`
497 /// arriving for the same press afterwards must not complete it. A platform
498 /// can genuinely send both (Windows delivers a `WM_POINTERUP` after a
499 /// capture loss), so the `Up` is swallowed rather than asserted against.
500 /// An entry is dropped by that swallowed `Up`, or by the pointer's next
501 /// press — a fresh press is a fresh interaction. Bounded by the contact
502 /// cap plus the mouse.
503 cancelled_pointers: Vec<crate::pointer::PointerId>,
504 /// Current cursor selected by hover/interaction routing.
505 current_cursor: crate::widget::CursorIcon,
506 /// What the **node-declared** cursor mechanism last resolved for the
507 /// hovered chain — the value `PointerEnter` wrote, or `Default` after the
508 /// `PointerLeave` that undid it.
509 ///
510 /// Kept so a handler can hand the cursor back
511 /// ([`EventContext::release_cursor`]) after having overridden it, without
512 /// having to re-derive the chain's declaration and risk disagreeing with
513 /// the walk that produced it. It is exactly as fresh as `current_cursor`:
514 /// both move only when the enter/leave pair fires, so a node whose
515 /// `.cursor(..)` changes under a stationary pointer is stale in the same
516 /// way, and by the same mechanism.
517 ///
518 /// [`EventContext::release_cursor`]: crate::widget::EventContext::release_cursor
519 node_declared_cursor: crate::widget::CursorIcon,
520 /// Delayed overlay requests (e.g., submenu hover-open delay).
521 pending_delayed_overlays: Vec<PendingDelayedOverlay>,
522 /// Reusable scratch buffer for active-id snapshots taken on hot
523 /// paths that mutate per-widget state inside the loop
524 /// (`tick_gestures_with_ops`, post-render dirty-bit clear,
525 /// post-layout `needs_layout` clear). Cleared and refilled on
526 /// every use via `WidgetArena::fill_active_ids`. Previously these
527 /// sites called the allocating `arena.active_ids()` per frame,
528 /// which `perf record` ranked at ~13 % of CPU on the
529 /// `widget_catalog --tab animations` scene.
530 active_ids_scratch: Vec<WidgetId>,
531 /// Widgets currently carrying a non-`None` `EventHandlers::gesture_arena`.
532 /// Updated on attach (`ensure_gesture_arena` install) and on
533 /// teardown (rebuild / destroy / handler-clear). Every per-frame
534 /// gesture pass (`tick_gestures_with_ops`, `next_gesture_deadline`)
535 /// iterates this set instead of every active widget — most active
536 /// widgets have `gesture_arena = None`, so the savings come from
537 /// not even visiting them. Filtered by `arena.is_active(id)` at
538 /// iteration time so dormant entries don't fire (a widget can be
539 /// dormant while still holding its handlers).
540 gesture_owners: std::collections::HashSet<WidgetId>,
541 /// OS-level accessibility preferences (high contrast, reduced motion, text scale).
542 prefers_high_contrast: bool,
543 prefers_reduced_motion: bool,
544 text_scale_factor: f64,
545 /// Whether an assistive technology is reading the tree, as reported by the
546 /// *operating system* — not by AccessKit. See
547 /// [`Self::set_screen_reader_state`] for why the distinction matters.
548 screen_reader: crate::environment::ScreenReaderState,
549 /// The app's explore-by-touch policy. See [`Self::set_explore_by_touch`].
550 explore_by_touch: crate::environment::ExploreByTouch,
551 /// Whether an AccessKit client is currently attached to this window's
552 /// adapter. Written by `teksilo-app` from the platform adapter's
553 /// activation / deactivation handlers.
554 at_client_attached: bool,
555 /// How a density switch should be worded to a screen reader, if the
556 /// application wants one announced. See
557 /// [`Self::set_density_announcement`].
558 density_announcement: Option<std::rc::Rc<dyn Fn(teksilo_tokens::TargetDensity) -> String>>,
559 /// How "a context menu opened" should be worded to a screen reader when a
560 /// **hold** opened it, if the application wants one announced. See
561 /// [`Self::set_context_menu_announcement`].
562 context_menu_announcement: Option<std::rc::Rc<dyn Fn() -> String>>,
563 /// The tree-owned long press the router is waiting out, if any. One at a
564 /// time: two fingers holding two different controls is not a gesture any
565 /// desktop idiom assigns a meaning to, and the second contact's arrival
566 /// replaces the first's route rather than racing it. See
567 /// [`touch_route`].
568 pending_touch_route: Option<touch_route::PendingTouchRoute>,
569 /// Host window HiDPI device scale (physical px per logical px), fed by
570 /// `teksilo-app` before each layout. Surfaced to widgets via
571 /// `LayoutContext::scale_factor`. The widget tree is otherwise fully
572 /// logical (the renderer applies this scale at the vertex stage); this is
573 /// the escape hatch for widgets that must size a device-pixel OS resource
574 /// (e.g. a `WebView`'s native subview). 1.0 in headless / test contexts.
575 device_scale_factor: f32,
576 /// Platform safe-area insets for the host window — a notch, a rounded
577 /// corner, a home indicator — in logical pixels, fed by `teksilo-app`
578 /// after every window resize. Reaches overlay placement through
579 /// [`OverlayViewport::safe_area`](crate::overlay::OverlayViewport::safe_area).
580 /// `ZERO` on every platform that reports nothing, which is every desktop
581 /// platform but macOS.
582 safe_area: teksilo_canvas::EdgeInsets,
583 /// A rectangle of the window currently covered by something outside the
584 /// tree — a soft keyboard, a platform IME candidate window — in
585 /// window-logical pixels. Reaches overlay placement through
586 /// [`OverlayViewport::occluded`](crate::overlay::OverlayViewport::occluded).
587 /// `None` on every frame where nothing is covering the window.
588 occluded_inset: Option<Rect>,
589 /// A pending `EventContext::request_soft_keyboard` call, taken by the app
590 /// layer once per dispatch. `Some(true)` asks for the keyboard,
591 /// `Some(false)` asks it to go away.
592 soft_keyboard_request: Option<bool>,
593 /// Active drag-and-drop session, if any.
594 pub(crate) active_drag: Option<crate::drag_state::DragSession>,
595 /// Source widget of an in-flight OS (outbound) drag that escalated past
596 /// the window boundary. Set only on the window that *started* the drag.
597 /// The in-app `active_drag` session is torn down at escalation (the OS owns
598 /// the pointer); this remembers who started it so the eventual `DragEnded`
599 /// can fire the source's `on_drag_ended`.
600 pub(crate) outbound_drag_source: Option<WidgetId>,
601 /// True while *this* window currently holds the re-entered internal session
602 /// for an in-flight app-originated OS drag (the OS drag wandered back over
603 /// this window — possibly a different window than the source — and we
604 /// restored the original typed payload). Distinguishes that session from a
605 /// plain internal drag so leaving again re-stashes instead of starting a
606 /// second OS drag, and dropping doesn't double-fire `on_drag_ended`.
607 pub(crate) os_drag_reentered: bool,
608 /// The accept state last pushed to the platform for an inbound OS drag, so
609 /// the same answer is not re-sent on every motion sample.
610 ///
611 /// `None` outside an OS drag, and reset when one ends — a fresh drag must
612 /// push its first verdict even if it happens to match the last drag's.
613 pub(crate) os_drop_accepted: Option<bool>,
614 /// Optional platform host for custom window chrome (set when the
615 /// application opts in via `WindowConfig::custom_chrome(true)`). Stored
616 /// here so that the root-builder closure has access during widget
617 /// construction; the same `Rc` is also held by `WindowManager` so it
618 /// outlives the widget tree if needed.
619 title_bar_host: Option<Rc<dyn crate::PlatformTitleBarHost>>,
620 /// App-level subscription state: registered event source adapter,
621 /// proxy poster, UI-side subscription callbacks. Default is empty;
622 /// teksilo-app installs a populated context when an event source is
623 /// registered on the builder.
624 pub(crate) app_context: Rc<crate::event_source::TreeAppContext>,
625 /// Active locale identifier. Cached for `Option<&str>` accessors; the
626 /// reactive source of truth is `locale_signal`. Both are updated in
627 /// lockstep by `set_locale`.
628 pub(crate) locale: Option<String>,
629 /// Reactive locale signal. Widgets and `LocalizedString` adapters bind to
630 /// this signal to react to locale changes; `set_locale` updates the signal
631 /// without rebuilding the widget tree.
632 pub(crate) locale_signal: crate::signal::Signal<Option<String>>,
633 /// Per-frame delta-seconds signal, advanced by `layout()` **only when
634 /// a frame was asked for**: through `request_frame()`, or by the
635 /// render-end re-arm for a painted frame-tick subscriber. This
636 /// preserves Teksilo's draw-when-needed model: idle trees stay idle
637 /// even if widgets have registered observers on this signal.
638 pub(crate) frame_tick: crate::signal::Signal<f32>,
639 /// Set by `request_frame()`; consumed by `advance_frame_tick()` on
640 /// the next `layout()`. Observers that need another tick after the
641 /// current one must re-request. Stored as `Rc<Cell>` so observers
642 /// fired from inside the layout pass (`ctx.effect` closures on
643 /// `frame_tick`) can chain-request without needing &mut access
644 /// to the tree — see [`frame_request_handle`](Self::frame_request_handle).
645 pub(crate) frame_tick_requested: std::rc::Rc<std::cell::Cell<bool>>,
646 /// Set after a render in which a frame-tick subscriber's owner was
647 /// painted; consumed alongside `frame_tick_requested` by
648 /// `advance_frame_tick()`.
649 ///
650 /// A flag of its own so that [`frame_tick_deadline`](Self::frame_tick_deadline)
651 /// knows *why* a frame is wanted. A throttled subscriber may stretch the
652 /// wait for its own tick to its interval; a frame asked for through
653 /// `frame_tick_requested` (the announcer's follow-up syncs, a caret, a
654 /// drag auto-scroll) is due at 60 Hz whatever is on screen. When both
655 /// reasons shared one flag they could not be told apart, and a
656 /// once-a-minute clock anywhere in the window made every requested frame
657 /// wait a minute.
658 pub(crate) frame_tick_armed_by_subscribers: bool,
659 /// Debug-only re-entrancy flag: `true` while a focus-change dispatch
660 /// (`FocusGained` / `FocusLost` handlers) is running. Threaded into each
661 /// `EventContext` so `open_window` / `focus_window` can warn if a handler
662 /// changes context merely because a control gained focus (WCAG 3.2.1). A
663 /// shared `Rc<Cell<bool>>` (like `frame_tick_requested`) so the flag is
664 /// readable from an `EventContext` that holds no `&mut` to the tree.
665 pub(crate) in_focus_dispatch: std::rc::Rc<std::cell::Cell<bool>>,
666 /// Shared "accessibility re-walk requested" flag. Set via
667 /// [`request_accessibility_update`](Self::request_accessibility_update)
668 /// (or its `BuildContext` / `EventContext` wrappers) and drained at the
669 /// top of [`sync_accessibility`](Self::sync_accessibility) into
670 /// `a11y_dirty`. A relayout no longer re-walks the AT tree on its own, so
671 /// widgets that restructure their subtree in an AT-affecting way (e.g.
672 /// `SceneView` materialising / destroying scene widgets) need this lever.
673 /// `Rc<Cell>` so the shared `&self` paths can toggle it like
674 /// `frame_tick_requested`.
675 pub(crate) a11y_update_requested: std::rc::Rc<std::cell::Cell<bool>>,
676 /// Delayed frame wake-up deadline. Widgets that need to schedule
677 /// a future frame without pumping at full framerate (caret blink,
678 /// etc.) store the target instant here via
679 /// [`wake_at_handle`](Self::wake_at_handle). `next_timer_deadline`
680 /// rolls it into the event loop's WaitUntil; when reached, the
681 /// next `layout()` automatically re-arms `frame_tick_requested`
682 /// so the frame-tick effects run on the wake-up pass.
683 pub(crate) pending_wake_at: std::rc::Rc<std::cell::Cell<Option<std::time::Instant>>>,
684 /// One-shot post-mount actions enqueued during `build()` via
685 /// [`BuildContext::run_after_mount`](crate::BuildContext::run_after_mount), drained by the app loop (and by
686 /// tests) through [`WidgetTree::run_mount_actions`] with a real
687 /// [`EventContext`] — the only place a widget
688 /// can read the OS parent handle / app-state / poster together after it is
689 /// mounted. Used by widgets that own a native resource needing a window
690 /// handle to initialise (a `WebView`'s engine subview).
691 pub(crate) pending_mount_actions: Vec<Box<dyn FnOnce(&mut crate::widget::EventContext)>>,
692 /// Wall-clock time of the previous `layout()` call (for delta computation).
693 pub(crate) last_frame_time: Option<std::time::Instant>,
694 /// Set by [`EventContext::close_window`] during dispatch; drained
695 /// by the application event loop after each event via
696 /// [`WidgetTree::take_close_window_request`]. A *guarded* close
697 /// request — the app routes it through the window's close guard.
698 pub(crate) close_window_requested: bool,
699 /// Set by [`EventContext::close_window_forced`] during dispatch;
700 /// drained via [`WidgetTree::take_force_close_request`]. An
701 /// *unconditional* close request that bypasses the window's close
702 /// guard.
703 pub(crate) force_close_requested: bool,
704 /// Raised by [`EventContext::set_locale`] during dispatch; drained by
705 /// the application event loop (see
706 /// `WindowManager::drain_pending_locale_requests`) so the switch can be
707 /// routed through the `I18nManager` (active locale + version signal +
708 /// RTL direction). `WidgetTree::set_locale` alone would only update the
709 /// tree's local locale signal — the i18n thread-local would stay put
710 /// and `tr!` lookups would not re-resolve.
711 pub(crate) pending_locale_request: Option<String>,
712 /// Raised by [`EventContext::set_theme`] during dispatch; drained by
713 /// the application event loop (see
714 /// `WindowManager::drain_pending_theme_requests`) so the switch is
715 /// routed through `WindowManager::set_theme`, which fans the new theme
716 /// out to *every* window. Applying via `WidgetTree::set_theme` inline
717 /// would only re-theme the originating window — the rest of the app
718 /// would stay on the old theme. Mirrors `pending_locale_request`.
719 pub(crate) pending_theme_request: Option<crate::styles::Theme>,
720 /// Raised by [`EventContext::follow_system_theme`] during dispatch;
721 /// drained by the application event loop (see
722 /// `WindowManager::drain_pending_follow_system_requests`), which switches
723 /// the app to `ThemeMode::Native` and recomputes the theme from current
724 /// OS colours. Mirrors `pending_theme_request`.
725 pub(crate) pending_follow_system_request: bool,
726 /// Raised by [`EventContext::set_text_scale`] during dispatch; drained by
727 /// the application event loop (see
728 /// `WindowManager::drain_pending_text_scale_requests`) so the change is
729 /// routed through `WindowManager::set_text_scale`, fanning the new factor
730 /// out to *every* window. Mirrors `pending_theme_request`.
731 pub(crate) pending_text_scale_request: Option<f32>,
732 /// Monotonic version counter bumped after every *real* accessibility
733 /// rebuild in [`Self::sync_accessibility`] (cache hits don't bump).
734 /// Mirror of [`crate::shortcut::ShortcutRegistry::version`]: an
735 /// automation / test harness can poll it to know whether the AT tree
736 /// changed without diffing the whole `TreeUpdate`.
737 at_version: crate::signal::Signal<u64>,
738 /// The framework's own live regions, one per politeness level. See
739 /// [`crate::announcer`]: each speaks every message from a node the tree
740 /// has never had, which is the only mechanism all three platform adapters
741 /// agree announces, and never in an update that moves focus.
742 announcer_polite: crate::announcer::Announcer,
743 announcer_assertive: crate::announcer::Announcer,
744 /// Where both announcers draw the id of each message's node from, so no
745 /// message is spoken from an id the tree has used before.
746 announcer_ids: crate::announcer::AnnouncerIds,
747 /// The announcements the platform adapters would have made from the
748 /// updates `sync_accessibility` returned (see
749 /// [`crate::accessibility::Announcement`]), drained by
750 /// [`Self::announcements_since`], while the tree records them
751 /// ([`Self::set_records_announcements`]).
752 announcement_ring: crate::accessibility::announcements::AnnouncementRing,
753 /// The ids the window's platform adapter holds, which differ from the
754 /// tree's own for a node that left the tree a reader sees and came back.
755 /// See [`crate::accessibility::adapter_ids`] and
756 /// [`Self::deliver_accessibility`].
757 adapter_ids: crate::accessibility::adapter_ids::AdapterIds,
758 /// What the last delivered update said about descriptions and live
759 /// regions, which is what the next one's descriptions are measured
760 /// against. See [`accessibility_description_impl`].
761 description_memory: accessibility_description_impl::DescriptionMemory,
762 /// Whether the `WidgetEvent::AccessAction` currently being dispatched was
763 /// consumed by a handler. Written by the dispatcher's `AccessAction` arm,
764 /// read (and reset) by [`Self::dispatch_access_action`], which is the only
765 /// caller that can answer "did anything happen?" to its own caller.
766 ///
767 /// A side channel because `dispatch_event_with_ops` returns `()` for every
768 /// event kind, and routing AT actions through the *same* path as everything
769 /// else is load-bearing (it is what lets an action open a window). The
770 /// alternative — reporting success whenever a live widget merely *existed*
771 /// at the target — is how an unhandled action came to look like a
772 /// successful one to every automation client.
773 access_action_handled: bool,
774 /// The `WindowState` for this tree's hosting window. Populated
775 /// by the app-level window manager when the tree is registered;
776 /// `None` for standalone trees. Cloned into every `EventContext`
777 /// and `BuildContext` so widgets can bind to the current window's
778 /// signals via `ctx.window()`.
779 pub(crate) window_state: Option<crate::window::WindowState>,
780}
781
782/// How long the shortened reshow delay stays active after the last tooltip
783/// dismisses. Long enough to cover moving between adjacent toolbar icons;
784/// short enough that a later, deliberate hover still pays the full initial
785/// delay. Not a theme token — it is session bookkeeping, not a visual feel.
786const TOOLTIP_SESSION_GRACE: std::time::Duration = std::time::Duration::from_millis(1000);
787
788/// Number of visible steps a sticky-on-dwell tooltip's promotion window is
789/// divided into.
790///
791/// The tree uses this only to decide *how often to wake* while a dwell is
792/// running — one redraw per step boundary rather than a free-run — but it must
793/// match the step count the content widget actually renders, or the indicator
794/// would advance on a different beat from the wake-ups driving it.
795/// `teksilo-widgets`' `DWELL_STEPS` is defined *as* this constant, so the two
796/// cannot drift; the per-step *duration* is derived from each entry's own
797/// `sticky_after`, so a caller that picks a non-default promotion window still
798/// gets correctly-spaced wake-ups.
799pub const TOOLTIP_DWELL_STEPS: u32 = 4;
800
801/// Max pointer travel (logical px) from the hover-origin before a pending
802/// tooltip timer restarts. Mirrors Windows hover-tracking slop
803/// (`SPI_GETMOUSEHOVERWIDTH` / height, typically ~4 px): the tip waits for a
804/// *paused* pointer, not merely "entered the bounds."
805const TOOLTIP_STATIONARY_SLOP: f32 = 4.0;
806
807/// A tooltip attachment managed by the WidgetTree.
808struct TooltipEntry {
809 anchor_id: WidgetId,
810 content_id: WidgetId,
811 /// The widget whose accessibility node should carry this tooltip's
812 /// description, which is not always the node the overlay hangs off.
813 ///
814 /// A composing control anchors the *overlay* on an inner chrome node it
815 /// built -- the thing with the right bounds to open a tooltip against --
816 /// while its role, its name and its focusability live on its own outer
817 /// node. A description on the inner one is a description an assistive
818 /// technology never reads, because it never lands there.
819 ///
820 /// Recorded by `BuildContext`'s `attach_tooltip*` wrappers as the widget
821 /// that was building at the time. Defaults to `anchor_id`, which is both
822 /// the historic behaviour and the right answer for a widget that anchors
823 /// its tooltip on itself.
824 ///
825 /// Naming an owner is a *claim*, not a guarantee: the accessibility walk
826 /// honours it only where exactly one tooltip claims that node. See
827 /// `WidgetTree::build_accessibility_recursive`.
828 description_owner_id: WidgetId,
829 delay: std::time::Duration,
830 /// Simulated hover start (for deterministic tests via advance_time).
831 hover_start: Option<std::time::Instant>,
832 /// Real hover start (for windowed apps via layout).
833 real_hover_start: Option<std::time::Instant>,
834 /// Pointer position when the current pending hover started. Used to
835 /// restart the delay if the pointer keeps moving inside the anchor
836 /// (stationary-pointer intent filter).
837 hover_origin: Option<teksilo_canvas::Point>,
838 overlay_id: Option<crate::overlay::OverlayId>,
839 /// When set, the tooltip auto-promotes to "sticky" after this
840 /// much elapsed time since it was shown. The entry stays in the
841 /// table and is just flagged sticky — the difference is that
842 /// pointer-leave no longer dismisses it and the overlay's
843 /// dismiss behavior is swapped to `EscapeOrClickOutside`.
844 sticky_after: Option<std::time::Duration>,
845 /// True when the dwell timer reached `sticky_after`. Causes
846 /// `tooltip_pointer_leave` to skip the dismissal and lets the
847 /// overlay survive pointer-leave until the user explicitly
848 /// dismisses it via Escape or a click outside.
849 is_sticky: bool,
850 /// When the overlay was shown (simulated). Together with
851 /// `sticky_after` drives auto-promotion.
852 shown_at_sim: Option<std::time::Instant>,
853 /// When the overlay was shown (real).
854 shown_at_real: Option<std::time::Instant>,
855 /// Optional shared sink the tooltip widget can read from to
856 /// compute its own dwell progress. Mirrors `shown_at_real`:
857 /// set on show, cleared on dismissal. Used by `RichTooltipWidget`
858 /// to drive the dwell indicator without relying on a fragile
859 /// paint-gap heuristic.
860 shown_at_sink: Option<std::rc::Rc<std::cell::Cell<Option<std::time::Instant>>>>,
861 /// True when the tooltip was shown by the keyboard-focus path
862 /// rather than the pointer-hover path. Focus-promoted tooltips
863 /// dismiss when focus moves outside both the anchor and the
864 /// tooltip content subtree (preventing accumulation as the user
865 /// Tabs through a form); pointer-dwelled stickies survive
866 /// focus changes and only dismiss via Escape or click-outside.
867 promoted_by_focus: bool,
868 /// Set while this entry's pending delay was started by keyboard focus
869 /// rather than by the pointer. Decides, at show time, that the surface
870 /// dismisses on `Escape`/click-outside rather than on pointer-leave (there
871 /// is no pointer in the story), and that it counts as focus-shown.
872 armed_by_focus: bool,
873 /// Set while this entry's pending delay was started by a **hold** — the
874 /// tree-owned long-press route in [`touch_route`].
875 ///
876 /// Decides two things at show time that neither the hover nor the focus arm
877 /// wants: the surface dismisses on `Escape` / a press outside (a finger has
878 /// already lifted, so there is no pointer left to leave), and it carries an
879 /// auto-dismiss of [`touch_route::TOUCH_TOOLTIP_DISMISS`] — because with no
880 /// pointer to leave and no focus to move, nothing else would ever retire it.
881 armed_by_hold: bool,
882 /// Set when the tip was dismissed while the focus that summoned it is
883 /// still inside its anchor — i.e. Escape on a focus-promoted tooltip.
884 ///
885 /// Escape restores focus to the anchor, and that restore runs the ordinary
886 /// focus path, which ends in `tooltip_focus_enter`. Without this flag the
887 /// tip the user just dismissed re-opens on the same keystroke, because
888 /// `dormant_dismissed_content` has already cleared `overlay_id` by then and
889 /// the entry looks eligible again. Cleared when focus genuinely leaves the
890 /// anchor (`tooltip_focus_leave_outside`), so Tabbing away and back
891 /// re-summons it normally. The hover path needs no equivalent: a stationary
892 /// pointer never re-fires `tooltip_pointer_enter`.
893 suppressed_until_focus_leaves: bool,
894 /// Where the tooltip opens relative to its anchor. `Below` (default)
895 /// for the common case; `Side` for anchors stacked vertically (menu
896 /// items, a vertical tab strip, list/tree rows) so the tooltip does
897 /// not cover the next sibling. Consulted at show time in both the
898 /// hover (`process_tooltips_impl`) and focus (`tooltip_focus_enter`)
899 /// paths.
900 placement: crate::overlay::TooltipPlacement,
901}
902
903/// A delayed overlay request (e.g., submenu hover-open delay).
904struct PendingDelayedOverlay {
905 request: crate::overlay::OverlayRequest,
906 delay: std::time::Duration,
907 focus_target: Option<WidgetId>,
908 /// Dismiss the anchor's sibling overlays when this one finally
909 /// shows, instead of when it was requested. See
910 /// [`EventContext::show_overlay_after_replacing_siblings`](crate::widget::EventContext::show_overlay_after_replacing_siblings).
911 replace_siblings: bool,
912 /// When the request was made (real time, for windowed apps).
913 real_requested_at: std::time::Instant,
914 /// When the request was made (simulated time, for tests).
915 sim_requested_at: std::time::Instant,
916}
917
918impl WidgetTree {
919 pub fn new() -> Self {
920 let initial_theme = crate::presets::intui::light();
921 // One signal, shared: the field the tree writes and the registry the
922 // application reads must be the same one, or a host mirroring "is the
923 // caret in a text widget" would never see focus move.
924 let focused_signal = crate::signal::Signal::new(None);
925 // ONE epoch. `sim_clock` starts here and the input clock is anchored
926 // here, so a single `advance_time` moves gesture deadlines, tooltips,
927 // overlays and animations against the same origin.
928 let epoch = std::time::Instant::now();
929 // ONE scheduler. The fling pump shares the tree's per-frame table
930 // rather than making a second one, so a coast wakes the loop through
931 // the same path a `Pulse` does.
932 let scheduler = crate::frame_tick_scheduler::FrameTickScheduler::new();
933 Self {
934 arena: WidgetArena::new(),
935 theme: initial_theme.clone(),
936 theme_signal: crate::signal::Signal::new(initial_theme.clone()),
937 density_policy: teksilo_tokens::DensityPolicy::default(),
938 user_text_scale: 1.0,
939 effective_theme: initial_theme,
940 effective_text_scale: 1.0,
941 text_scale_signal: crate::signal::Signal::new(1.0),
942 // Starts active: winit may not send `Focused(true)` for the first
943 // window, so a window must not be born inactive (caret hidden,
944 // selection muted) before the first focus event arrives.
945 window_active_signal: crate::signal::Signal::new(true),
946 text_backend: None,
947 focused: None,
948 focused_signal: focused_signal.clone(),
949 pointers: crate::pointer::table::PointerTable::new(),
950 hovered_signal: crate::signal::Signal::new(None),
951 last_pointer_kind_signal: crate::signal::Signal::new(
952 teksilo_tokens::PointerKind::Mouse,
953 ),
954 focus_visible: crate::signal::Signal::new(false),
955 presses: crate::press::PressTable::default(),
956 view_focus_stack: Vec::new(),
957 previous_pointer_position: None,
958 pending_focus_restore: Vec::new(),
959 last_interaction_anchors: Vec::new(),
960 last_proposal: SizeProposal::exact(800.0, 600.0),
961 pending_modal_requests: Vec::new(),
962 pending_modal_dismissal: false,
963 shortcut_registry: crate::shortcut::ShortcutRegistry::new(),
964 pending_intents: Vec::new(),
965 global_actions: Vec::new(),
966 text_surfaces: crate::text_surface::TextSurfaces::new(focused_signal.clone()),
967 key_capture: None,
968 binding_registry: crate::binding::BindingRegistry::new(),
969 idle_queue: crate::idle::IdleQueue::new(),
970 sim_clock: epoch,
971 input_clock: std::rc::Rc::new(crate::pointer::clock::MonotonicClock::new(epoch)),
972 current_input: crate::pointer::InputSnapshot::default(),
973 sim_time_frozen: false,
974 sim_input_origin: None,
975 sim_input_offset: std::time::Duration::ZERO,
976 focus_origin: None,
977 overlay_manager: crate::overlay::OverlayManager::new(),
978 draining_dismiss: std::cell::Cell::new(false),
979 tooltips: Vec::new(),
980 tooltip_session_until_sim: None,
981 tooltip_session_until_real: None,
982 highlight_tooltip: None,
983 layout_direction: crate::environment::LayoutDirection::default(),
984 animation_scheduler: crate::animation::AnimationScheduler::new(),
985 animated_values: Vec::new(),
986 animated_quads: crate::animated_quad::AnimatedQuadRegistry::new(),
987 frame_tick_scheduler: scheduler.clone(),
988 touch_motion: pan_arbiter::TouchMotion::new(scheduler),
989 armed_chain: None,
990 paint_epoch: 0,
991 cached_a11y: None,
992 a11y_dirty: true,
993 last_synced_shortcut_version: 0,
994 last_synced_locale: None,
995 last_synced_window_title: None,
996 synthetic_parent_map: std::collections::HashMap::new(),
997 synthetic_local_bounds: std::collections::HashMap::new(),
998 a11y_walk_generation: 0,
999 cached_frame: None,
1000 pending_dispatch: std::collections::VecDeque::new(),
1001 cancelled_pointers: Vec::new(),
1002 dispatch_depth: 0,
1003 current_cursor: crate::widget::CursorIcon::Default,
1004 node_declared_cursor: crate::widget::CursorIcon::Default,
1005 pending_delayed_overlays: Vec::new(),
1006 active_ids_scratch: Vec::new(),
1007 gesture_owners: std::collections::HashSet::new(),
1008 prefers_high_contrast: false,
1009 prefers_reduced_motion: false,
1010 text_scale_factor: 1.0,
1011 screen_reader: crate::environment::ScreenReaderState::default(),
1012 explore_by_touch: crate::environment::ExploreByTouch::default(),
1013 at_client_attached: false,
1014 density_announcement: None,
1015 context_menu_announcement: None,
1016 pending_touch_route: None,
1017 device_scale_factor: 1.0,
1018 safe_area: teksilo_canvas::EdgeInsets::ZERO,
1019 occluded_inset: None,
1020 soft_keyboard_request: None,
1021 active_drag: None,
1022 outbound_drag_source: None,
1023 os_drag_reentered: false,
1024 os_drop_accepted: None,
1025 title_bar_host: None,
1026 app_context: Rc::new(crate::event_source::TreeAppContext::empty()),
1027 locale: None,
1028 locale_signal: crate::signal::Signal::new(None),
1029 frame_tick: crate::signal::Signal::new(0.0_f32),
1030 frame_tick_requested: std::rc::Rc::new(std::cell::Cell::new(false)),
1031 frame_tick_armed_by_subscribers: false,
1032 in_focus_dispatch: std::rc::Rc::new(std::cell::Cell::new(false)),
1033 a11y_update_requested: std::rc::Rc::new(std::cell::Cell::new(false)),
1034 pending_wake_at: std::rc::Rc::new(std::cell::Cell::new(None)),
1035 pending_mount_actions: Vec::new(),
1036 last_frame_time: None,
1037 close_window_requested: false,
1038 force_close_requested: false,
1039 pending_locale_request: None,
1040 pending_theme_request: None,
1041 pending_follow_system_request: false,
1042 pending_text_scale_request: None,
1043 at_version: crate::signal::Signal::new(0),
1044 announcer_polite: crate::announcer::Announcer::new(
1045 crate::announcer::Politeness::Polite,
1046 ),
1047 announcer_assertive: crate::announcer::Announcer::new(
1048 crate::announcer::Politeness::Assertive,
1049 ),
1050 announcer_ids: crate::announcer::AnnouncerIds::new(),
1051 announcement_ring: crate::accessibility::announcements::AnnouncementRing::new(),
1052 adapter_ids: crate::accessibility::adapter_ids::AdapterIds::new(),
1053 description_memory: Default::default(),
1054 access_action_handled: false,
1055 window_state: None,
1056 }
1057 }
1058
1059 /// Construct an [`EventContext`]
1060 /// pre-populated with the tree's app-state registry, hosting
1061 /// `WindowState`, and a `&mut dyn WindowOps` handle so handlers
1062 /// can synchronously reach the multi-window API. Used by every
1063 /// dispatch site.
1064 pub(crate) fn make_event_context<'ops>(
1065 &self,
1066 ops: &'ops mut dyn crate::window::WindowOps,
1067 ) -> crate::widget::EventContext<'ops> {
1068 let drag_is_external = self.active_drag.as_ref().is_some_and(|d| d.is_external);
1069 // Read-only snapshot of tree query state that handlers may
1070 // need synchronously: the last pointer position and a
1071 // (content_id, bounds) slice of open overlays, both read by the
1072 // safe-triangle submenu hover gate, and the focused widget, read
1073 // by a container deciding whether a shortcut of its own should
1074 // yield to the widget the user is standing on.
1075 let overlay_snapshot: Vec<(
1076 crate::widget_id::WidgetId,
1077 teksilo_canvas::Rect,
1078 Option<teksilo_canvas::Point>,
1079 )> = self
1080 .overlay_manager
1081 .active_content_ids()
1082 .into_iter()
1083 .filter_map(|cid| {
1084 self.overlay_manager
1085 .bounds_for_content(cid)
1086 .map(|r| (cid, r, self.unexpired_safe_apex_for_content(cid)))
1087 })
1088 .collect();
1089 crate::widget::EventContext::new()
1090 .with_app_context(self.app_context.clone())
1091 .with_window_context(ops, self.window_state.clone())
1092 .with_drag_external(drag_is_external)
1093 .with_query_snapshot(
1094 self.last_pointer_position(),
1095 overlay_snapshot,
1096 self.focused(),
1097 )
1098 .with_pointer_captor(self.current_pointer_capture())
1099 .with_layout_direction(self.layout_direction)
1100 .with_window_active(self.is_window_active())
1101 .with_input_snapshot(self.current_input.clone())
1102 .with_touch_action(self.current_frozen_touch_action())
1103 .with_press(self.current_press_snapshot())
1104 .with_focus_dispatch_flag(self.in_focus_dispatch.clone())
1105 }
1106
1107 /// Run a closure with a fresh [`EventContext`] anchored at this
1108 /// tree, then collect any pending operations queued through the
1109 /// context (intents, modal requests, frame requests, idle
1110 /// callbacks…) so they take effect on the next event-loop tick.
1111 ///
1112 /// Used by the `teksilo-app` event-loop dispatcher to deliver
1113 /// async-result callbacks (file dialogs, future background
1114 /// tasks) on the main thread with full handler-equivalent
1115 /// semantics. There is no source widget for app-level events,
1116 /// so intents are anchored at the tree's first root id (or
1117 /// silently dropped when the tree is empty).
1118 pub fn run_with_event_context<F>(&mut self, ops: &mut dyn crate::window::WindowOps, f: F)
1119 where
1120 F: FnOnce(&mut crate::widget::EventContext),
1121 {
1122 let mut ctx = self.make_event_context(ops);
1123 f(&mut ctx);
1124 let anchor = self.arena.roots().first().copied();
1125 if let Some(anchor_id) = anchor {
1126 self.collect_from_ctx(ctx, anchor_id);
1127 } else {
1128 // Empty tree — nothing to anchor intents on. Drop ctx;
1129 // its only side effects (frame requests, cursor) are
1130 // not meaningful for an empty tree.
1131 drop(ctx);
1132 }
1133 }
1134
1135 /// Enqueue a one-shot action to run with a real
1136 /// [`EventContext`] after the current build,
1137 /// once the tree is mounted under its window. Used via
1138 /// [`BuildContext::run_after_mount`](crate::BuildContext::run_after_mount). Drained by
1139 /// [`Self::run_mount_actions`].
1140 pub(crate) fn queue_mount_action(
1141 &mut self,
1142 action: Box<dyn FnOnce(&mut crate::widget::EventContext)>,
1143 ) {
1144 self.pending_mount_actions.push(action);
1145 }
1146
1147 /// Whether any post-mount actions are waiting to run.
1148 pub fn has_pending_mount_actions(&self) -> bool {
1149 !self.pending_mount_actions.is_empty()
1150 }
1151
1152 /// Drain and run every queued post-mount action with a fresh
1153 /// [`EventContext`] built over `ops`. The app
1154 /// loop calls this each iteration with a real `WindowOps` sink (so
1155 /// `ctx.parent_window_handle()` resolves); headless tests call it with a
1156 /// `NoopWindowOps`. Actions enqueued *by* an action (rare) are left for the
1157 /// next drain rather than run re-entrantly.
1158 pub fn run_mount_actions(&mut self, ops: &mut dyn crate::window::WindowOps) {
1159 if self.pending_mount_actions.is_empty() {
1160 return;
1161 }
1162 let actions = std::mem::take(&mut self.pending_mount_actions);
1163 self.run_with_event_context(ops, move |ctx| {
1164 for action in actions {
1165 action(ctx);
1166 }
1167 });
1168 }
1169
1170 /// Attach the [`WindowState`](crate::window::WindowState) for this
1171 /// tree's hosting window. Called by `WindowManager::create_window`.
1172 pub fn set_window_state(&mut self, state: crate::window::WindowState) {
1173 self.window_state = Some(state);
1174 }
1175
1176 pub fn window_state(&self) -> Option<&crate::window::WindowState> {
1177 self.window_state.as_ref()
1178 }
1179
1180 /// The window's title as its accessible name: `None` without a window
1181 /// state or with a blank title, since a name that is empty is still a
1182 /// name to every adapter.
1183 pub(crate) fn window_title_for_accessibility(&self) -> Option<String> {
1184 let title = self.window_state.as_ref()?.title().get();
1185 (!title.trim().is_empty()).then_some(title)
1186 }
1187
1188 /// Clone the shared "frame requested" flag. Widgets stash this
1189 /// in their state and call `.set(true)` from inside frame-tick
1190 /// closures to chain-request another frame without needing
1191 /// mutable access to the tree. See `RichTextEditor` for the
1192 /// canonical use (caret blink, drag-select auto-scroll).
1193 pub fn frame_request_handle(&self) -> std::rc::Rc<std::cell::Cell<bool>> {
1194 self.frame_tick_requested.clone()
1195 }
1196
1197 /// Clone the shared wake-at deadline cell. Widgets stash this in
1198 /// their state and call `request_wake_at` from frame-tick effects
1199 /// to schedule a one-shot deadline without keeping the event loop
1200 /// in `Poll` mode. On the next `layout()` at or past the deadline,
1201 /// the tree auto-arms `frame_tick_requested` so the effect runs on
1202 /// the wake-up pass. Canonical use: the rich text editor's caret
1203 /// blink schedules a 500 ms wake instead of pumping every frame.
1204 pub fn wake_at_handle(&self) -> std::rc::Rc<std::cell::Cell<Option<std::time::Instant>>> {
1205 self.pending_wake_at.clone()
1206 }
1207
1208 /// Schedule a one-shot frame wake at `at`. Merges with any existing
1209 /// deadline — keeps the earlier instant so the most urgent wake
1210 /// wins.
1211 pub fn request_wake_at(&self, at: std::time::Instant) {
1212 let current = self.pending_wake_at.get();
1213 let merged = match current {
1214 Some(existing) if existing <= at => existing,
1215 _ => at,
1216 };
1217 self.pending_wake_at.set(Some(merged));
1218 }
1219
1220 /// The per-frame delta-seconds signal. Observers fire **only on frames
1221 /// the tree was asked to pump** via [`request_frame`](Self::request_frame);
1222 /// merely observing the signal does not keep the event loop awake.
1223 /// See `BuildContext::frame_tick` for widget-side access and
1224 /// `BuildContext::request_frame` for the opt-in request side.
1225 pub fn frame_tick(&self) -> crate::signal::Signal<f32> {
1226 self.frame_tick.clone()
1227 }
1228
1229 /// Ask the tree to pump exactly one more frame. `needs_redraw()`
1230 /// returns true until the request is consumed by the next
1231 /// `layout()` call, which fires the per-frame tick signal and
1232 /// clears the flag. Observers that still need more frames (drag
1233 /// auto-scroll, caret blink, pending document events) must call
1234 /// `request_frame()` again from inside their tick closure.
1235 ///
1236 /// Takes `&self` on purpose: widget handlers and per-frame effects
1237 /// receive a shared reference to the tree via `EventContext` /
1238 /// `BuildContext`, and the request flag is a `Cell` specifically so
1239 /// those shared paths can toggle it without ceremony.
1240 pub fn request_frame(&self) {
1241 self.frame_tick_requested.set(true);
1242 }
1243
1244 /// Request that the AccessKit tree be re-walked on the next
1245 /// [`sync_accessibility`](Self::sync_accessibility). Takes `&self` (the
1246 /// flag is a `Cell`) so handlers and `build()` closures reaching the tree
1247 /// through a shared reference can request a re-walk without `&mut` access.
1248 /// The drain at the top of `sync_accessibility` flips `a11y_dirty`.
1249 pub fn request_accessibility_update(&self) {
1250 self.a11y_update_requested.set(true);
1251 }
1252
1253 /// Speak `message` to the screen reader, politely.
1254 ///
1255 /// For anything the user needs told that is not the name of a widget: a
1256 /// completed action, a changed count, the result of an undo. The message is
1257 /// delivered on the next two accessibility syncs, which this schedules.
1258 ///
1259 /// Prefer `EventContext::announce` inside a handler and
1260 /// `BuildContext::announce` inside a build; this is the tree-level entry
1261 /// point both of those reach.
1262 ///
1263 /// Takes `impl Into<String>`, so `tr!(…)` works directly. See
1264 /// [`crate::announcer`] for why it is a `String` and not a
1265 /// `LocalizedString`, and for why an announcement beside a `Toast` says
1266 /// everything twice.
1267 pub fn announce(&mut self, message: impl Into<String>) {
1268 self.announce_with(message, crate::announcer::Politeness::Polite);
1269 }
1270
1271 /// Speak `message` to the screen reader at the given urgency.
1272 ///
1273 /// [`Politeness::Assertive`](crate::announcer::Politeness::Assertive)
1274 /// interrupts whatever is being spoken; reserve it for something the user
1275 /// must not miss and cannot recover by re-reading the screen.
1276 pub fn announce_with(
1277 &mut self,
1278 message: impl Into<String>,
1279 politeness: crate::announcer::Politeness,
1280 ) {
1281 match politeness {
1282 crate::announcer::Politeness::Polite => self.announcer_polite.push(message.into()),
1283 crate::announcer::Politeness::Assertive => {
1284 self.announcer_assertive.push(message.into())
1285 }
1286 }
1287 // A message is put in the tree by a sync, and a sync only happens on
1288 // a frame. Without both of these a message queued from a handler that
1289 // changed nothing visible would sit unspoken until something else
1290 // happened to redraw.
1291 self.request_accessibility_update();
1292 self.request_frame();
1293 }
1294
1295 /// Clone the shared "accessibility re-walk requested" flag, for the same
1296 /// stash-and-toggle pattern as [`frame_request_handle`](Self::frame_request_handle).
1297 pub fn a11y_request_handle(&self) -> std::rc::Rc<std::cell::Cell<bool>> {
1298 self.a11y_update_requested.clone()
1299 }
1300
1301 /// Whether the next `layout()` will fire the per-frame tick: a frame
1302 /// was requested, or a render painted a frame-tick subscriber's owner
1303 /// and re-armed the chain. Exposed for tests and for the event-loop
1304 /// driver that decides when to schedule the next wake-up; *when* that
1305 /// frame is due is [`frame_tick_deadline`](Self::frame_tick_deadline).
1306 pub fn frame_requested(&self) -> bool {
1307 self.frame_tick_requested.get() || self.frame_tick_armed_by_subscribers
1308 }
1309
1310 /// Consume both reasons for a frame tick at once, returning whether
1311 /// there was one. Every path that fires `frame_tick` goes through here,
1312 /// so neither flag can outlive the tick it asked for.
1313 pub(crate) fn take_frame_tick_request(&mut self) -> bool {
1314 let requested = self.frame_tick_requested.replace(false);
1315 let armed = std::mem::take(&mut self.frame_tick_armed_by_subscribers);
1316 requested || armed
1317 }
1318
1319 /// The next wake-up deadline for the per-frame-effect path, or
1320 /// `None` when no per-frame effect is armed.
1321 ///
1322 /// This is the **60 Hz cap** for continuous per-frame animations
1323 /// (`Pulse`, caret blink, drag auto-scroll, `--cycle` drivers). The
1324 /// per-frame-effect path used to force `ControlFlow::Poll`, which
1325 /// free-runs at the display's refresh rate — so on a 300 Hz panel a
1326 /// single `Pulse`/`Cycle` rendered at 300 fps (measured ~45 % CPU) for
1327 /// motion that looks identical at 60 fps. Routing it through a fixed
1328 /// 16.667 ms deadline (folded into
1329 /// [`next_timer_deadline`](Self::next_timer_deadline)) makes it pace at
1330 /// 60 Hz regardless of refresh rate, matching the signal-tween
1331 /// [`AnimationScheduler`](crate::animation::AnimationScheduler) and
1332 /// shader-quad [`AnimatedQuadRegistry`](crate::animated_quad::AnimatedQuadRegistry),
1333 /// which already share the same interval.
1334 ///
1335 /// A **throttled** subscriber (registered via
1336 /// [`FrameTickScheduler::subscribe_throttled`](crate::frame_tick_scheduler::FrameTickScheduler::subscribe_throttled),
1337 /// e.g. `Cycle`, whose visible child only changes once per period)
1338 /// stretches the wait for **its own** tick to its interval: the loop
1339 /// then sleeps to the period instead of rendering identical 60 fps
1340 /// frames in between. The interval for the subscribers' re-arm is the
1341 /// **minimum across all currently-visible subscribers**, so a `Cycle`
1342 /// next to a `Pulse` still ticks at 60 Hz while a lone `Cycle` sleeps to
1343 /// its period.
1344 ///
1345 /// A frame asked for through [`request_frame`](Self::request_frame) or
1346 /// [`frame_request_handle`](Self::frame_request_handle) is due at 60 Hz
1347 /// whatever subscribers are visible, and the earlier of the two
1348 /// deadlines wins. The announcer, a caret, a drag auto-scroll and the
1349 /// bootstrap frame of a new subscription all ask that way, and none of
1350 /// them can be made to wait on somebody else's clock: an announcement
1351 /// queued behind a once-a-minute clock was spoken a minute late, or at
1352 /// the user's next key press.
1353 ///
1354 /// Paces from `last_frame_time` so the cadence is drift-free; before
1355 /// the first render it fires on the next loop turn.
1356 pub fn frame_tick_deadline(&self) -> Option<std::time::Instant> {
1357 const DEFAULT_INTERVAL: std::time::Duration = std::time::Duration::from_micros(16_667);
1358 // Each reason for a frame brings its own pace. A subscriber re-arm
1359 // with no visible subscriber left keeps the 60 Hz fallback, so the
1360 // one frame that finds nothing to re-arm still runs and the flag
1361 // does not linger.
1362 let requested = self.frame_tick_requested.get().then_some(DEFAULT_INTERVAL);
1363 let subscribed = self.frame_tick_armed_by_subscribers.then(|| {
1364 self.frame_tick_scheduler
1365 .min_visible_interval(&self.arena, self.paint_epoch)
1366 .unwrap_or(DEFAULT_INTERVAL)
1367 });
1368 let interval = requested.into_iter().chain(subscribed).min()?;
1369 Some(match self.last_frame_time {
1370 Some(prev) => prev + interval,
1371 None => std::time::Instant::now(),
1372 })
1373 }
1374
1375 /// Subscribe `owner` to the per-frame-effect scheduler. The
1376 /// returned [`FrameTickSubscription`](crate::frame_tick_scheduler::FrameTickSubscription)
1377 /// is an RAII guard — drop it (typically by replacing the field on
1378 /// the owning widget on rebuild, or letting the widget's `Drop`
1379 /// run) to remove the subscription. While the guard is alive, the
1380 /// tree will keep re-arming the frame tick after every render
1381 /// in which `owner` was painted, and stop on frames where it
1382 /// wasn't — so a subscribed widget hidden inside a non-selected
1383 /// `Switcher` branch contributes zero idle frames.
1384 ///
1385 /// Apps should not call this directly — use
1386 /// [`BuildContext::subscribe_frame_tick`](crate::build_context::BuildContext::subscribe_frame_tick)
1387 /// from inside `Widget::build`.
1388 pub fn subscribe_frame_tick(
1389 &self,
1390 owner: WidgetId,
1391 ) -> crate::frame_tick_scheduler::FrameTickSubscription {
1392 self.frame_tick_scheduler.subscribe(owner)
1393 }
1394
1395 /// Like [`subscribe_frame_tick`](Self::subscribe_frame_tick), but the
1396 /// owner only needs to wake **at most once per `interval`** while
1397 /// visible. Same visibility gate; between wakes the event loop sleeps
1398 /// to the interval deadline instead of rendering identical 60 fps
1399 /// frames. Use for effects whose visible output changes far less often
1400 /// than 60 Hz — e.g. `Cycle`'s once-per-period index advance.
1401 ///
1402 /// Apps should not call this directly — use
1403 /// [`BuildContext::subscribe_frame_tick_throttled`](crate::build_context::BuildContext::subscribe_frame_tick_throttled)
1404 /// from inside `Widget::build`.
1405 pub fn subscribe_frame_tick_throttled(
1406 &self,
1407 owner: WidgetId,
1408 interval: std::time::Duration,
1409 ) -> crate::frame_tick_scheduler::FrameTickSubscription {
1410 self.frame_tick_scheduler
1411 .subscribe_throttled(owner, interval)
1412 }
1413
1414 /// Advance the frame tick signal when (and only when) a frame was
1415 /// requested. Called by `layout()` before the scheduler tick so the
1416 /// per-frame observers fire on the same frame they asked for.
1417 pub(crate) fn advance_frame_tick(&mut self, now: std::time::Instant) {
1418 if !self.take_frame_tick_request() {
1419 self.last_frame_time = Some(now);
1420 return;
1421 }
1422 let delta = match self.last_frame_time {
1423 Some(prev) => {
1424 let d = now.saturating_duration_since(prev).as_secs_f32();
1425 // Clamp absurd deltas (pause/breakpoint) so observers never see a spike.
1426 d.clamp(0.0, 0.1)
1427 }
1428 None => 0.0,
1429 };
1430 self.last_frame_time = Some(now);
1431 self.frame_tick.set(delta);
1432 }
1433
1434 /// Replace the per-tree app context. Called by `teksilo-app` when
1435 /// constructing a window so the widget tree can reach the registered
1436 /// event source adapter and post subscription events through the
1437 /// event-loop proxy.
1438 pub fn set_app_context(&mut self, app_context: Rc<crate::event_source::TreeAppContext>) {
1439 self.app_context = app_context;
1440 }
1441
1442 /// Get the per-tree app context. Used by `BuildContext::subscribe_event`
1443 /// and by the event-loop handler when dispatching incoming
1444 /// `AppEvent::SubscriptionEvent`.
1445 pub fn app_context(&self) -> &Rc<crate::event_source::TreeAppContext> {
1446 &self.app_context
1447 }
1448
1449 /// Switch the tree-level locale at runtime.
1450 ///
1451 /// Updates `locale_signal` (a reactive `Signal<Option<String>>`) and marks
1452 /// all widgets dirty for relayout and repaint. Widgets are **not** rebuilt:
1453 /// per-string reactivity flows through `LocalizedString::to_signal()` which
1454 /// observes the teksilo-i18n manager, and anything else that depends on the
1455 /// tree-level locale can bind to `locale_signal()`.
1456 pub fn set_locale(&mut self, locale: String) {
1457 if self.locale.as_deref() == Some(locale.as_str()) {
1458 return;
1459 }
1460 let new = Some(locale);
1461 self.locale = new.clone();
1462 self.locale_signal.set(new);
1463 self.arena.mark_all_dirty();
1464 }
1465
1466 /// Currently active locale identifier, if any.
1467 pub fn locale(&self) -> Option<&str> {
1468 self.locale.as_deref()
1469 }
1470
1471 /// Reactive handle on the current locale. Mirrors `locale()` but updates
1472 /// observers when `set_locale` is called.
1473 pub fn locale_signal(&self) -> &crate::signal::Signal<Option<String>> {
1474 &self.locale_signal
1475 }
1476
1477 fn pointer_inside_overlay_region(
1478 &self,
1479 overlay_id: crate::overlay::OverlayId,
1480 position: Point,
1481 ) -> bool {
1482 let Some(overlay) = self
1483 .overlay_manager
1484 .stack
1485 .iter()
1486 .find(|overlay| overlay.id == overlay_id)
1487 else {
1488 return false;
1489 };
1490
1491 if self.arena.is_active(overlay.anchor)
1492 && self.arena.bounds(overlay.anchor).contains(position)
1493 {
1494 return true;
1495 }
1496
1497 self.overlay_manager.stack.iter().any(|candidate| {
1498 (candidate.id == overlay_id
1499 || self
1500 .overlay_manager
1501 .is_descendant_of(candidate.id, overlay_id))
1502 && candidate.bounds.contains(position)
1503 })
1504 }
1505
1506 /// Whether the overlay's safe region is armed and still within
1507 /// [`SAFE_REGION_BUDGET`](crate::overlay::SAFE_REGION_BUDGET).
1508 ///
1509 /// Both clocks are consulted and either expiring is enough: the real
1510 /// one drives a running app, the simulated one drives headless tests
1511 /// (`advance_time`), and an overlay armed in one and aged in the
1512 /// other must still expire.
1513 fn safe_region_unexpired(
1514 &self,
1515 overlay_id: crate::overlay::OverlayId,
1516 real_now: std::time::Instant,
1517 sim_now: std::time::Instant,
1518 ) -> bool {
1519 let Some(overlay) = self
1520 .overlay_manager
1521 .stack
1522 .iter()
1523 .find(|overlay| overlay.id == overlay_id)
1524 else {
1525 return false;
1526 };
1527 if overlay.safe_apex.is_none() {
1528 return false;
1529 }
1530 let budget = crate::overlay::SAFE_REGION_BUDGET;
1531 let real_ok = overlay
1532 .safe_apex_started_real
1533 .is_none_or(|started| real_now.saturating_duration_since(started) < budget);
1534 let sim_ok = overlay
1535 .safe_apex_started_sim
1536 .is_none_or(|started| sim_now.saturating_duration_since(started) < budget);
1537 real_ok && sim_ok
1538 }
1539
1540 /// The armed safe-triangle apex of the overlay rooted at
1541 /// `content_id`, or `None` when no region is armed or its budget is
1542 /// spent.
1543 ///
1544 /// This is the form the per-dispatch `EventContext` snapshot carries,
1545 /// because a widget asking "is a traversal toward that submenu still
1546 /// live?" must get the same answer the dismissal path acts on — an
1547 /// unfiltered apex outlives the region by up to a frame and makes a
1548 /// sibling row stand aside for a submenu the framework has already
1549 /// stopped protecting.
1550 fn unexpired_safe_apex_for_content(
1551 &self,
1552 content_id: crate::widget_id::WidgetId,
1553 ) -> Option<teksilo_canvas::Point> {
1554 // Cheap short-circuit first: nothing is armed in the common case,
1555 // and this runs once per node per pointer dispatch.
1556 let apex = self.overlay_manager.safe_apex_for_content(content_id)?;
1557 let id = self.overlay_manager.find_by_content(content_id)?;
1558 self.safe_region_unexpired(id, std::time::Instant::now(), self.sim_clock)
1559 .then_some(apex)
1560 }
1561
1562 fn update_pointer_leave_overlays(
1563 &mut self,
1564 position: Point,
1565 ops: &mut dyn crate::window::WindowOps,
1566 ) {
1567 let overlay_ids: Vec<crate::overlay::OverlayId> = self
1568 .overlay_manager
1569 .stack
1570 .iter()
1571 .filter(|overlay| {
1572 matches!(
1573 overlay.dismiss,
1574 crate::overlay::DismissBehavior::PointerLeave { .. }
1575 )
1576 })
1577 .map(|overlay| overlay.id)
1578 .collect();
1579
1580 let real_now = std::time::Instant::now();
1581 let sim_now = self.sim_clock;
1582
1583 for overlay_id in overlay_ids {
1584 let inside = self.pointer_inside_overlay_region(overlay_id, position);
1585 // A pointer travelling the safe triangle toward this overlay
1586 // is still "inside" as far as dismissal is concerned — that
1587 // is the whole point of the triangle. Without this the
1588 // grace period runs for the entire diagonal and closes the
1589 // submenu mid-flight, no matter what the hover handlers do.
1590 // See `overlay::safe_triangle`.
1591 let armed = self.safe_region_unexpired(overlay_id, real_now, sim_now);
1592 let travelling = !inside
1593 && armed
1594 && self
1595 .overlay_manager
1596 .point_in_safe_region(overlay_id, position);
1597 // Arrived, or returned to the trigger row: the traversal is
1598 // over and the ordinary rules apply again.
1599 //
1600 // Straying out of the cone deliberately does NOT disarm. The
1601 // cone is a needle at its apex — the first sample after the
1602 // pointer leaves the trigger row is a pixel or two away, so
1603 // whether it lands inside is one quantized step's direction
1604 // rather than the user's intent. Disarming there made that
1605 // sample final, because a region is only ever armed as the
1606 // pointer leaves the row and the pointer has already left:
1607 // nothing could re-arm it. Keeping it armed makes the cone a
1608 // per-sample hold that the grace below re-evaluates instead,
1609 // so a wobble mid-diagonal costs nothing while a real change
1610 // of mind still closes the submenu one close-delay later. The
1611 // budget is what retires a region for good; the frame pass
1612 // spends it even for a pointer that stopped moving entirely.
1613 if armed && inside {
1614 self.overlay_manager.clear_safe_region(overlay_id);
1615 }
1616 if let Some(overlay) = self
1617 .overlay_manager
1618 .stack
1619 .iter_mut()
1620 .find(|overlay| overlay.id == overlay_id)
1621 {
1622 if inside || travelling {
1623 overlay.pointer_leave_started_real = None;
1624 overlay.pointer_leave_started_sim = None;
1625 } else if overlay.pointer_leave_started_real.is_none() {
1626 overlay.pointer_leave_started_real = Some(real_now);
1627 overlay.pointer_leave_started_sim = Some(sim_now);
1628 self.arena.mark_needs_paint(overlay.anchor);
1629 }
1630 }
1631 }
1632
1633 self.process_pointer_leave_overlays_real(&mut *ops);
1634 }
1635
1636 fn process_pointer_leave_overlays(&mut self) {
1637 let sim_now = self.sim_clock;
1638 let mut noop = crate::window::NoopWindowOps;
1639 self.process_pointer_leave_overlays_impl(
1640 |overlay| {
1641 overlay
1642 .pointer_leave_started_sim
1643 .map(|started| sim_now.saturating_duration_since(started))
1644 },
1645 &mut noop,
1646 );
1647 }
1648
1649 fn process_pointer_leave_overlays_real(&mut self, ops: &mut dyn crate::window::WindowOps) {
1650 let real_now = std::time::Instant::now();
1651 self.process_pointer_leave_overlays_impl(
1652 |overlay| {
1653 overlay
1654 .pointer_leave_started_real
1655 .map(|started| real_now.saturating_duration_since(started))
1656 },
1657 &mut *ops,
1658 );
1659 }
1660
1661 fn process_auto_dismiss_overlays(&mut self) {
1662 let sim_now = self.sim_clock;
1663 let mut noop = crate::window::NoopWindowOps;
1664 self.process_auto_dismiss_overlays_impl(
1665 |overlay| {
1666 overlay
1667 .auto_dismiss_after
1668 .map(|_| sim_now.saturating_duration_since(overlay.shown_at_sim))
1669 },
1670 &mut noop,
1671 );
1672 }
1673
1674 fn process_auto_dismiss_overlays_real(&mut self, ops: &mut dyn crate::window::WindowOps) {
1675 let real_now = std::time::Instant::now();
1676 self.process_auto_dismiss_overlays_impl(
1677 |overlay| {
1678 overlay
1679 .auto_dismiss_after
1680 .map(|_| real_now.saturating_duration_since(overlay.shown_at_real))
1681 },
1682 &mut *ops,
1683 );
1684 }
1685
1686 /// Drain overlays whose fade-out tween has completed (set up by
1687 /// `OverlayRequest::with_fade`). Parks the content as the normal
1688 /// dismiss path does, and hands focus back only when that leaves it
1689 /// nowhere ([`restore_focus_left_behind`](Self::restore_focus_left_behind)):
1690 /// the dismissal that started the fade may have meant to leave focus
1691 /// alone, and the user may have moved it on since; called once per layout pass
1692 /// after `process_auto_dismiss_overlays_real` so an overlay that
1693 /// hits its auto-dismiss deadline kicks off its fade-out tween
1694 /// in the same pass.
1695 pub(crate) fn process_overlay_fade_dismissals_real(
1696 &mut self,
1697 ops: &mut dyn crate::window::WindowOps,
1698 ) {
1699 let now = std::time::Instant::now();
1700 let pending = self.overlay_manager.process_pending_fade_dismissals(now);
1701 for (_id, dismissed, focus_restore) in pending {
1702 self.dormant_dismissed_content(&dismissed, &mut *ops);
1703 self.restore_focus_left_behind(focus_restore, &mut *ops);
1704 }
1705 }
1706
1707 /// Sim-clock variant for headless tests. Same shape as
1708 /// [`process_overlay_fade_dismissals_real`](Self::process_overlay_fade_dismissals_real)
1709 /// but reads `dismissing_started_sim`.
1710 pub(crate) fn process_overlay_fade_dismissals_sim(&mut self) {
1711 let mut noop = crate::window::NoopWindowOps;
1712 let pending = self
1713 .overlay_manager
1714 .process_pending_fade_dismissals_sim(self.sim_clock);
1715 for (_id, dismissed, focus_restore) in pending {
1716 self.dormant_dismissed_content(&dismissed, &mut noop);
1717 self.restore_focus_left_behind(focus_restore, &mut noop);
1718 }
1719 }
1720
1721 /// Hand focus to `restore` after an overlay has gone of its own accord
1722 /// (its auto-dismiss timer ran out, or its fade-out ended), but only when
1723 /// focus is left nowhere: the overlay held it and
1724 /// [`dormant_dismissed_content`](Self::dormant_dismissed_content) has just
1725 /// taken it away with the content, or nothing held it. Focus the user has
1726 /// moved elsewhere since the overlay opened stays where they put it. A tip
1727 /// that focus summoned holds its anchor as `restore`, and restoring that
1728 /// whatever held focus sent a reader who had Tabbed on back to the control
1729 /// they had just left.
1730 fn restore_focus_left_behind(
1731 &mut self,
1732 restore: Option<WidgetId>,
1733 ops: &mut dyn crate::window::WindowOps,
1734 ) {
1735 if let Some(restore) = restore
1736 && self.arena.is_active(restore)
1737 && self.focused.is_none_or(|id| !self.arena.is_active(id))
1738 {
1739 self.focus_ops(restore, ops);
1740 }
1741 }
1742
1743 fn process_auto_dismiss_overlays_impl(
1744 &mut self,
1745 elapsed_fn: impl Fn(&crate::overlay::ActiveOverlay) -> Option<std::time::Duration>,
1746 ops: &mut dyn crate::window::WindowOps,
1747 ) {
1748 let mut to_dismiss = Vec::new();
1749
1750 for overlay in self.overlay_manager.stack.iter().rev() {
1751 let Some(delay) = overlay.auto_dismiss_after else {
1752 continue;
1753 };
1754
1755 if to_dismiss
1756 .iter()
1757 .any(|ancestor| self.overlay_manager.is_descendant_of(overlay.id, *ancestor))
1758 {
1759 continue;
1760 }
1761
1762 if let Some(elapsed) = elapsed_fn(overlay)
1763 && elapsed >= delay
1764 {
1765 to_dismiss.push(overlay.id);
1766 }
1767 }
1768
1769 for overlay_id in to_dismiss {
1770 let (dismissed, focus_restore) =
1771 self.overlay_manager.dismiss_with_focus_restore(overlay_id);
1772 self.dormant_dismissed_content(&dismissed, &mut *ops);
1773 self.restore_focus_left_behind(focus_restore, &mut *ops);
1774 }
1775 }
1776
1777 fn process_pointer_leave_overlays_impl(
1778 &mut self,
1779 elapsed_fn: impl Fn(&crate::overlay::ActiveOverlay) -> Option<std::time::Duration>,
1780 ops: &mut dyn crate::window::WindowOps,
1781 ) {
1782 // Retire safe regions whose budget is spent. `update_pointer_leave_overlays`
1783 // does this too, but only when the pointer moves — and a pointer parked
1784 // inside the cone generates no moves at all, so without this pass the
1785 // submenu would stay open indefinitely. Expiring here also starts the
1786 // ordinary grace, so the overlay closes `delay` later exactly as if the
1787 // triangle had never been armed.
1788 let real_now = std::time::Instant::now();
1789 let sim_now = self.sim_clock;
1790 let expired: Vec<crate::overlay::OverlayId> = self
1791 .overlay_manager
1792 .stack
1793 .iter()
1794 .filter(|overlay| overlay.safe_apex.is_some())
1795 .map(|overlay| overlay.id)
1796 .filter(|id| !self.safe_region_unexpired(*id, real_now, sim_now))
1797 .collect();
1798 let budget = crate::overlay::SAFE_REGION_BUDGET;
1799 for id in expired {
1800 if let Some(overlay) = self
1801 .overlay_manager
1802 .stack
1803 .iter_mut()
1804 .find(|overlay| overlay.id == id)
1805 && overlay.pointer_leave_started_real.is_none()
1806 {
1807 // Backdate to the instant the budget ran out: the
1808 // pointer stopped counting as "inside" then, not when a
1809 // frame got around to noticing. Otherwise the grace
1810 // silently restarts from zero and the total wait
1811 // depends on the frame rate.
1812 let backdate = |started: Option<std::time::Instant>, now: std::time::Instant| {
1813 started
1814 .and_then(|s| s.checked_add(budget))
1815 .map(|deadline| deadline.min(now))
1816 .unwrap_or(now)
1817 };
1818 overlay.pointer_leave_started_real =
1819 Some(backdate(overlay.safe_apex_started_real, real_now));
1820 overlay.pointer_leave_started_sim =
1821 Some(backdate(overlay.safe_apex_started_sim, sim_now));
1822 }
1823 self.overlay_manager.clear_safe_region(id);
1824 }
1825
1826 let mut to_dismiss = Vec::new();
1827
1828 for overlay in self.overlay_manager.stack.iter().rev() {
1829 let crate::overlay::DismissBehavior::PointerLeave { delay } = overlay.dismiss else {
1830 continue;
1831 };
1832
1833 if to_dismiss
1834 .iter()
1835 .any(|ancestor| self.overlay_manager.is_descendant_of(overlay.id, *ancestor))
1836 {
1837 continue;
1838 }
1839
1840 if let Some(elapsed) = elapsed_fn(overlay)
1841 && elapsed >= delay
1842 {
1843 to_dismiss.push(overlay.id);
1844 }
1845 }
1846
1847 for overlay_id in to_dismiss {
1848 let (dismissed, focus_restore) =
1849 self.overlay_manager.dismiss_with_focus_restore(overlay_id);
1850 self.dormant_dismissed_content(&dismissed, &mut *ops);
1851 if let Some(restore_id) = focus_restore
1852 && self.arena.is_active(restore_id)
1853 {
1854 self.focus_ops(restore_id, &mut *ops);
1855 }
1856 }
1857 }
1858
1859 pub fn with_theme(mut self, theme: Theme) -> Self {
1860 // Update both the cached `Theme` AND the reactive
1861 // `theme_signal` — widgets that observe the signal (e.g.
1862 // `TextInputField` resetting the rich-text engine's default
1863 // text colour) would otherwise see the constructor's
1864 // `presets::intui::light()` initial value forever, even when
1865 // `TeksiloAppBuilder.theme(crate::presets::intui::dark())` was used.
1866 // `set_theme` already does this; `with_theme` was the
1867 // builder-time analogue that forgot to keep them aligned.
1868 self.theme = theme.clone();
1869 self.theme_signal.set(theme);
1870 self.recompute_effective_theme();
1871 self
1872 }
1873
1874 pub fn with_text_backend(
1875 mut self,
1876 backend: Rc<RefCell<dyn teksilo_canvas::TextBackend>>,
1877 ) -> Self {
1878 self.text_backend = Some(backend);
1879 self
1880 }
1881
1882 /// Attach a platform host for custom window chrome. Set by the
1883 /// `WindowManager` when the application opts in via
1884 /// `WindowConfig::custom_chrome(true)`. Widgets like `TitleBar` retrieve
1885 /// it from inside the root-builder closure via [`Self::title_bar_host`].
1886 pub fn with_title_bar_host(mut self, host: Rc<dyn crate::PlatformTitleBarHost>) -> Self {
1887 self.title_bar_host = Some(host);
1888 self
1889 }
1890
1891 pub fn set_title_bar_host(&mut self, host: Rc<dyn crate::PlatformTitleBarHost>) {
1892 self.title_bar_host = Some(host);
1893 }
1894
1895 /// Get the platform title bar host, if one was attached. Returns `None`
1896 /// when the application did not opt into custom chrome, or when the
1897 /// platform does not support it (X11 without an EWMH-capable window
1898 /// manager, or a headless build).
1899 pub fn title_bar_host(&self) -> Option<Rc<dyn crate::PlatformTitleBarHost>> {
1900 self.title_bar_host.clone()
1901 }
1902
1903 pub fn theme(&self) -> &Theme {
1904 &self.theme
1905 }
1906
1907 /// Reactive handle on the current theme. Updates fire when `set_theme`
1908 /// is called; widgets that want theme-derived values to stay live should
1909 /// build derived signals via `theme_signal.map(...)` or combine with
1910 /// other inputs using `.zip(...)`.
1911 pub fn theme_signal(&self) -> &crate::signal::Signal<Theme> {
1912 &self.theme_signal
1913 }
1914
1915 /// Whether any widget needs layout or paint (i.e., a redraw would be useful).
1916 ///
1917 /// Uses `has_running` rather than `has_active` so that animations
1918 /// parked by the window-inactive gate stop forcing the event loop
1919 /// into `ControlFlow::WaitUntil`. Without this, an unfocused window
1920 /// would still wake at the animation frame interval and the
1921 /// pause would save nothing. Both the signal scheduler AND the
1922 /// shader-driven animated-quad registry are consulted — a
1923 /// ProgressBar::indeterminate whose widget has no pending paint
1924 /// dirt still needs the loop to keep waking at the animation
1925 /// frame interval so its phase advances.
1926 pub fn needs_redraw(&self) -> bool {
1927 self.arena.any_needs_layout()
1928 || self.arena.any_needs_paint()
1929 || self.animation_scheduler.has_running()
1930 || self.animated_quads.has_running()
1931 || self.frame_requested()
1932 }
1933
1934 /// Whether a render pass is needed (any widget needs layout or paint).
1935 pub fn needs_render(&self) -> bool {
1936 self.arena.any_needs_layout() || self.arena.any_needs_paint()
1937 }
1938
1939 /// Whether this tree has reactive work that only a `layout()` pass can
1940 /// turn into arena dirt — i.e. whether reconciling it right now could
1941 /// change what [`needs_render`](Self::needs_render) reports.
1942 ///
1943 /// Read-only and cheap: `O(unique bound sources)` `u64` comparisons
1944 /// plus one peek per registered animated signal. No arena walk, no
1945 /// rebuilds, no geometry. Asking does not consume the answer, so it
1946 /// can be asked every dispatch.
1947 ///
1948 /// # Why this is exactly the right question, and no broader
1949 ///
1950 /// `teksilo_app::WindowManager::request_redraw_needing_render` exists
1951 /// for ONE case: a handler in window A wrote a `Signal` that window
1952 /// B's widgets also bind, and B — which never saw the event — must be
1953 /// reconciled before anyone can tell it needs repainting. Every OTHER
1954 /// thing `layout_with_ops` drives already has its own scheduling
1955 /// path and does not need this sweep:
1956 ///
1957 /// - tooltip dwell + sticky steps, delayed overlays, auto-dismiss,
1958 /// overlay fades, the animation scheduler, animated quads,
1959 /// gestures, `wake_at` and the 60 Hz frame tick are all timing
1960 /// driven, and every one of them contributes to
1961 /// [`next_timer_deadline`](Self::next_timer_deadline) — which
1962 /// `request_redraw_due` polls to wake precisely the due windows;
1963 /// - drag ticks follow that window's own pointer stream;
1964 /// - a handler that called `request_rebuild` marked the arena
1965 /// directly, so `needs_render()` is already true without any
1966 /// reconcile.
1967 ///
1968 /// So the two terms below are what the sweep uniquely covers:
1969 /// binding-registry staleness (the whole point), and a *pending*
1970 /// `animate_to` — which the scheduler has not started yet, so it
1971 /// contributes no deadline, and which only `process_pending_animations`
1972 /// (inside `layout`) can promote into one. The second term is
1973 /// belt-and-braces: arming an animation also advances the signal's
1974 /// generation, so a bound animated signal is already covered by the
1975 /// first — but an animated signal registered without being bound
1976 /// would not be, and this makes that impossible to get wrong.
1977 pub fn needs_reconcile(&self) -> bool {
1978 self.binding_registry.any_dirty()
1979 || self
1980 .animated_values
1981 .iter()
1982 .any(AnimatedRegistration::has_pending_animation)
1983 }
1984
1985 /// Register a `Signal<f32>` for animation support. The framework
1986 /// checks registered signals each frame for pending `animate_to`
1987 /// requests. Called automatically by `BuildContext::animated_signal()`
1988 /// — `owner` is `ctx.self_id()` of the widget whose `build()` created
1989 /// the signal. Used by the scheduler to pause/cancel animations when
1990 /// the owning widget is offscreen, dormant, or destroyed.
1991 pub fn register_animated_signal(
1992 &mut self,
1993 signal: &crate::signal::Signal<f32>,
1994 owner: WidgetId,
1995 ) {
1996 self.animated_values
1997 .retain(|registration| registration.is_alive());
1998 if let Some(existing) = self
1999 .animated_values
2000 .iter_mut()
2001 .find(|registration| registration.same_signal(signal))
2002 {
2003 // Signal may have been registered earlier with a placeholder
2004 // owner (e.g. a widget field constructed pre-build and
2005 // re-registered during build()) — prefer the latest owner.
2006 existing.owner = owner;
2007 return;
2008 }
2009 if let Some(weak_signal) = signal.weak_handle() {
2010 self.animated_values.push(AnimatedRegistration {
2011 weak: weak_signal,
2012 owner,
2013 });
2014 }
2015 }
2016
2017 /// Whether any animation is currently running.
2018 pub fn has_active_animations(&self) -> bool {
2019 self.animation_scheduler.has_active()
2020 }
2021
2022 /// Pick up pending `animate_to` requests from registered signals
2023 /// and start them on the animation scheduler.
2024 fn process_pending_animations(&mut self) {
2025 let now = self.animation_clock();
2026 self.process_pending_animations_at(now);
2027 }
2028
2029 /// Pick up pending animations using the given time (for sim clock).
2030 fn process_pending_animations_at(&mut self, now: std::time::Instant) {
2031 let mut pending = Vec::new();
2032 self.animated_values.retain(|registration| {
2033 if let Some(animation) = registration.take_pending_animation() {
2034 pending.push(animation);
2035 true
2036 } else {
2037 registration.is_alive()
2038 }
2039 });
2040
2041 for (signal, req, owner) in pending {
2042 if req.looping {
2043 let start = signal.get();
2044 self.animation_scheduler.animate_looping(
2045 &signal,
2046 owner,
2047 start,
2048 req.target,
2049 req.duration,
2050 req.easing,
2051 req.frame_interval,
2052 req.epsilon,
2053 req.max_duration,
2054 now,
2055 );
2056 } else {
2057 self.animation_scheduler.animate_with_options(
2058 &signal,
2059 owner,
2060 req.target,
2061 req.duration,
2062 req.easing,
2063 req.frame_interval,
2064 req.epsilon,
2065 req.max_duration,
2066 now,
2067 );
2068 }
2069 }
2070 }
2071
2072 /// Mark the owning window as active (focused AND not occluded) or
2073 /// inactive. Propagates to the animation scheduler AND the
2074 /// animated-quad registry so both pause-resume in lockstep — no
2075 /// ticks, no frame wakes, no GPU submits.
2076 ///
2077 /// On an actual state change it also fires `window_active_signal`
2078 /// (so build-time binders and `DimWhenInactive` react) and issues a
2079 /// global paint-only dirty mark, so every widget that reads
2080 /// `PaintContext::window_active` (caret gates, selection bands) repaints
2081 /// once. This is a repaint, not a relayout — geometry never changes when
2082 /// the window's active state flips (the caret keeps its space). Window
2083 /// focus changes are rare and user-driven, so the O(n) mark is cheap and
2084 /// Mark every node paint-dirty (no relayout, no rebuild) so the next
2085 /// render re-runs their `paint()`. This is the paint-cache invalidation an
2086 /// off-thread source needs after posting a [`RepaintWindowRequest`](crate::RepaintWindowRequest):
2087 /// a bare redraw request re-presents the cached frame, so a widget whose
2088 /// content changed off the UI thread (a terminal's PTY output) must be
2089 /// marked dirty for its `paint()` to run again.
2090 pub fn mark_all_needs_paint_only(&mut self) {
2091 self.arena.mark_all_needs_paint_only();
2092 }
2093
2094 /// strictly lighter than `set_theme`'s `mark_all_dirty` (layout + paint).
2095 pub fn set_window_active(&mut self, active: bool) {
2096 let mut noop = crate::window::NoopWindowOps;
2097 self.set_window_active_with_ops(active, &mut noop);
2098 }
2099
2100 /// [`set_window_active`](Self::set_window_active) with the caller's
2101 /// app-level [`WindowOps`](crate::window::WindowOps) sink, so the
2102 /// `on_pointer_cancel` handlers a deactivation fires can reach the
2103 /// multi-window API like any other handler.
2104 pub fn set_window_active_with_ops(
2105 &mut self,
2106 active: bool,
2107 ops: &mut dyn crate::window::WindowOps,
2108 ) {
2109 // The scheduler is measured on the tree's animation axis, so its pause
2110 // mark has to be taken there too — a pause stamped on the wall clock
2111 // while time is simulated would rebase every animation by the gap
2112 // between the axes on resume. The shader-driven quad registry has no
2113 // simulated door at all (it is ticked from `render()`), so it keeps the
2114 // wall clock.
2115 self.animation_scheduler
2116 .set_window_active(active, self.animation_clock());
2117 self.animated_quads
2118 .set_window_active(active, std::time::Instant::now());
2119 if self.window_active_signal.get() != active {
2120 self.window_active_signal.set(active);
2121 self.arena.mark_all_needs_paint_only();
2122 if !active {
2123 // A held pointer first, before any other state is cleared: a
2124 // widget that captured the pointer for a drag (a column-resize
2125 // grip, a splitter divider, a scrollbar thumb, a slider) will
2126 // never see the matching `PointerUp` — the user releases the
2127 // button over the window that took focus, and this window is
2128 // told nothing. Releasing the capture silently, which is what
2129 // this used to do, strands the widget instead: it keeps the
2130 // half of the interaction it owns, with no event left that
2131 // could clear it. The cancel funnel releases the capture *and*
2132 // tells it, so it can let go.
2133 self.cancel_all_pointers(
2134 crate::pointer::CancelReason::WindowDeactivated,
2135 &mut *ops,
2136 );
2137 // The pointer has left for another window; the OS sends no
2138 // leave event we can rely on, so a tooltip shown at the moment
2139 // of the switch would float over the newly-focused window's
2140 // chrome with nothing left to dismiss it. Retire tips and
2141 // cancel pending dwells — but leave *sticky* ones, which the
2142 // user pinned deliberately and expects to find on return.
2143 self.tooltip_window_deactivated();
2144 }
2145 }
2146 }
2147
2148 /// Whether the owning window is currently active (`focused AND not
2149 /// occluded`). The reactive companion is [`Self::window_active_signal`].
2150 pub fn is_window_active(&self) -> bool {
2151 self.window_active_signal.get()
2152 }
2153
2154 /// Reactive handle on window-active state. Fires when the window gains or
2155 /// loses active status. Bind at [`BindingLevel::RepaintOnly`] — an
2156 /// active-state flip never affects geometry. Starts `true`.
2157 ///
2158 /// [`BindingLevel::RepaintOnly`]: crate::binding::BindingLevel::RepaintOnly
2159 pub fn window_active_signal(&self) -> crate::signal::Signal<bool> {
2160 self.window_active_signal.clone()
2161 }
2162
2163 /// Register a new animated quad for the currently-building widget.
2164 /// Called by [`crate::build_context::BuildContext::animated_quad`];
2165 /// returns an opaque handle the widget stashes for its `paint()`
2166 /// call.
2167 pub fn register_animated_quad(
2168 &mut self,
2169 owner: WidgetId,
2170 kind: crate::animated_quad::AnimatedQuadKind,
2171 ) -> crate::animated_quad::AnimatedQuadHandle {
2172 self.animated_quads
2173 .register(owner, kind, std::time::Instant::now())
2174 }
2175
2176 /// Active animated-quad slot count. Test / debug helper.
2177 pub fn animated_quad_count(&self) -> usize {
2178 self.animated_quads.active_count()
2179 }
2180
2181 /// Advance animations by simulated time (for deterministic testing).
2182 ///
2183 /// An **alias** of [`advance_time`](Self::advance_time), not a second door.
2184 /// It was one once, and the two moved disjoint halves of the tree from
2185 /// clocks they each advanced independently: a caller that wanted both had
2186 /// to call both, which advanced simulated time twice, and a caller that
2187 /// wanted one silently froze the other — an animation and the fling it was
2188 /// racing could not be moved to the same instant by any sequence of calls.
2189 /// Kept as a name rather than folded away because it reads correctly at
2190 /// its ~120 call sites, all of which mean "advance the clock".
2191 pub fn tick_animations(&mut self, duration: std::time::Duration) {
2192 self.advance_time(duration);
2193 }
2194
2195 /// Switch the tree-level theme at runtime.
2196 ///
2197 /// Updates `theme_signal` (a reactive `Signal<Theme>`) and marks all widgets
2198 /// dirty for relayout and repaint. Widgets are **not** rebuilt: the
2199 /// `LayoutContext` and `PaintContext` already resolve the current theme on
2200 /// every pass, and any widget that derives state from theme tokens should
2201 /// do so through a `theme_signal()` subscription rather than a build-time
2202 /// capture. Preserves focus, scroll offsets, and other interaction state.
2203 pub fn set_theme(&mut self, theme: Theme) {
2204 self.theme = theme.clone();
2205 self.theme_signal.set(theme);
2206 self.recompute_effective_theme();
2207 self.arena.mark_all_dirty();
2208 // A theme change re-resolves typography, so every label re-shapes —
2209 // inside bounds the layout pass may leave untouched, which means no
2210 // resize is recorded and nothing else would dirty the tree. The
2211 // label's lines, and therefore its text runs, can be a different
2212 // set at the same size.
2213 self.a11y_dirty = true;
2214 }
2215
2216 /// The [`TargetDensity`] the active theme was projected onto.
2217 ///
2218 /// [`TargetDensity`]: teksilo_tokens::TargetDensity
2219 pub fn input_density(&self) -> teksilo_tokens::TargetDensity {
2220 self.theme.input.density
2221 }
2222
2223 /// Project the active theme onto another density and **rebuild** the tree.
2224 ///
2225 /// A rebuild, not [`Self::set_theme`]'s `mark_all_dirty()`: a target size is
2226 /// baked in `build()` (a `MinSize` wrapper, a recipe's `Rc<dyn FooStyle>`,
2227 /// the number of `Toolbar` items that fit), and marking layout + paint
2228 /// cannot re-bake it. This reuses the exact path a
2229 /// `BindingLevel::Rebuild` binding takes — `mark_needs_rebuild` on each
2230 /// root plus `mark_ancestors_need_layout` — so the next layout pass drains
2231 /// it through `process_rebuilds`, which already handles focus restoration,
2232 /// the a11y re-walk and interaction-state revalidation.
2233 ///
2234 /// A no-op when the density is already the requested one: a density switch
2235 /// throws away every widget id in the tree, so it must not fire on a
2236 /// repeated set.
2237 ///
2238 /// [`TargetDensity`]: teksilo_tokens::TargetDensity
2239 pub fn set_input_density(&mut self, density: teksilo_tokens::TargetDensity) {
2240 if self.theme.input.density == density {
2241 return;
2242 }
2243 // Exactly one utterance per switch, guaranteed by the guard above:
2244 // every widget id in the tree is about to be thrown away, so a screen
2245 // reader that was reading one is about to lose its place and needs to
2246 // be told what happened.
2247 if let Some(wording) = self.density_announcement.clone() {
2248 self.announce(wording(density));
2249 }
2250 self.set_theme(self.theme.with_density(density));
2251 // The `BindingLevel::Rebuild` arm of `process_state_changes`
2252 // (`widget_tree/layout_impl.rs`), applied at every root.
2253 for root in self.arena.roots() {
2254 self.arena.mark_needs_rebuild(root);
2255 self.arena.mark_ancestors_need_layout(root);
2256 }
2257 }
2258
2259 /// Announce density switches to a screen reader, in the application's own
2260 /// words.
2261 ///
2262 /// A density switch rebuilds the entire tree, so a screen reader loses its
2263 /// place and the user hears no explanation for it. Registering a wording
2264 /// makes [`Self::set_input_density`] speak once — and only once — per real
2265 /// switch, through the same [`Self::announce`] path everything else uses.
2266 ///
2267 /// The wording is the application's because it cannot be the framework's:
2268 /// `teksilo-i18n` depends on this crate, so nothing here can name
2269 /// `LocalizedString` or reach a translation bundle, and a hardcoded English
2270 /// sentence spoken into a French screen reader is worse than silence. Pass
2271 /// a closure that resolves `tr!(…)`:
2272 ///
2273 /// ```ignore
2274 /// tree.set_density_announcement(Some(std::rc::Rc::new(|d| match d {
2275 /// TargetDensity::Compact => tr!(layout_compact()).into(),
2276 /// TargetDensity::Comfortable => tr!(layout_comfortable()).into(),
2277 /// TargetDensity::Touch => tr!(layout_touch()).into(),
2278 /// })));
2279 /// ```
2280 ///
2281 /// `None` — the default — announces nothing.
2282 pub fn set_density_announcement(
2283 &mut self,
2284 wording: Option<std::rc::Rc<dyn Fn(teksilo_tokens::TargetDensity) -> String>>,
2285 ) {
2286 self.density_announcement = wording;
2287 }
2288
2289 /// How to word "a context menu opened" for a screen reader, when the menu
2290 /// was opened by a **hold**.
2291 ///
2292 /// The other three routes need nothing: a secondary press, `Shift+F10` and
2293 /// the AccessKit `ShowContextMenu` action are all deliberate, and the menu
2294 /// takes focus, which is announcement enough. A hold is the one route whose
2295 /// user cannot see the menu appear — a finger is on top of where it opens —
2296 /// and which they may not have meant.
2297 ///
2298 /// The wording is the application's for the same reason
2299 /// [`Self::set_density_announcement`]'s is: `teksilo-i18n` depends on this
2300 /// crate, so nothing here can name a `LocalizedString`, and a hardcoded
2301 /// English sentence spoken into a French screen reader is worse than
2302 /// silence.
2303 ///
2304 /// ```ignore
2305 /// tree.set_context_menu_announcement(Some(std::rc::Rc::new(|| {
2306 /// tr!(context_menu_opened()).into()
2307 /// })));
2308 /// ```
2309 ///
2310 /// `None` — the default — announces nothing. Where it is set, the
2311 /// announcement is still suppressed if the **pressed node's** own subtree
2312 /// already carries a live region — the widget speaking for itself, so the
2313 /// framework does not speak over it — through
2314 /// [`Self::announce_unless_widget_speaks`]. The menu's own subtree is not
2315 /// consulted: it is raised by this very call and has not been walked yet.
2316 pub fn set_context_menu_announcement(
2317 &mut self,
2318 wording: Option<std::rc::Rc<dyn Fn() -> String>>,
2319 ) {
2320 self.context_menu_announcement = wording;
2321 }
2322
2323 /// Speak `message`, unless `widget` already speaks for itself.
2324 ///
2325 /// A framework announcement that lands beside a widget's own live region
2326 /// says everything twice — the failure mode [`crate::announcer`] warns
2327 /// about for `Toast`. This is the check that avoids it: if the last
2328 /// accessibility tree carried a live region *inside* `widget`'s subtree
2329 /// that the platform adapters would speak for (in the filtered tree, with
2330 /// a name), the widget is already talking and this stays quiet. A live
2331 /// region that is hidden, or that carries its text where its role takes
2332 /// no name from, is silent on every platform and does not count.
2333 /// Returns whether the message was queued.
2334 ///
2335 /// It necessarily reads **one tree behind**. An announcement is queued
2336 /// during event dispatch; the live-region text it would duplicate is
2337 /// whatever the *last* built update carried, because the next one has not
2338 /// been built yet. A widget that speaks for the first time in the same
2339 /// dispatch is therefore not yet visible here — which is the right bias:
2340 /// it errs toward saying something rather than toward silence.
2341 pub fn announce_unless_widget_speaks(
2342 &mut self,
2343 widget: WidgetId,
2344 message: impl Into<String>,
2345 ) -> bool {
2346 if self.widget_subtree_speaks(widget) {
2347 return false;
2348 }
2349 self.announce(message);
2350 true
2351 }
2352
2353 /// Whether the last delivered accessibility tree had a live node in
2354 /// `widget`'s subtree that the platform adapters would speak for.
2355 ///
2356 /// Read through `accesskit_consumer`, so by the adapters' rules, whether
2357 /// or not this tree records announcements: the node is in the filtered
2358 /// tree (not hidden, not inside a hidden subtree), it is live, itself or
2359 /// through an ancestor, and it has a name, which for a `Status` is its
2360 /// label and not its value.
2361 /// A live region no platform can hear does not speak, and must not keep
2362 /// the framework quiet. The politeness must be set inside the subtree,
2363 /// too: a widget that is live only because it sits in somebody else's
2364 /// live region is not the one speaking.
2365 ///
2366 /// Synthetic children count too, resolved to their owning widget through
2367 /// the same parent map the AccessKit action router uses. `teksilo-scene`
2368 /// can mark a scene item as a live region, and a live region is a live
2369 /// region wherever it was emitted from.
2370 fn widget_subtree_speaks(&self, widget: WidgetId) -> bool {
2371 let mut wanted: std::collections::HashSet<accesskit::NodeId> =
2372 std::collections::HashSet::new();
2373 let mut stack = vec![widget];
2374 while let Some(id) = stack.pop() {
2375 if self.arena.get(id).is_none() {
2376 continue;
2377 }
2378 wanted.insert(crate::accessibility::widget_id_to_node_id(id));
2379 stack.extend_from_slice(self.arena.children(id));
2380 }
2381 let Some(update) = &self.cached_a11y else {
2382 return false;
2383 };
2384 crate::accessibility::announcements::speaks_within(update, |node_id| {
2385 wanted.contains(&node_id)
2386 || self
2387 .synthetic_parent_map
2388 .get(&node_id)
2389 .is_some_and(|owner| {
2390 wanted.contains(&crate::accessibility::widget_id_to_node_id(*owner))
2391 })
2392 })
2393 }
2394
2395 /// How the active density is chosen. See [`DensityPolicy`].
2396 ///
2397 /// [`DensityPolicy`]: teksilo_tokens::DensityPolicy
2398 pub fn density_policy(&self) -> teksilo_tokens::DensityPolicy {
2399 self.density_policy
2400 }
2401
2402 /// Set the density-selection policy.
2403 ///
2404 /// Storing a `Fixed(d)` policy does **not** by itself switch the density —
2405 /// call [`Self::set_input_density`] for that. `FollowLastPointer` is not
2406 /// acted on either: it is state and an accessor, and the field's own
2407 /// documentation says what is still undecided about honouring it.
2408 pub fn set_density_policy(&mut self, policy: teksilo_tokens::DensityPolicy) {
2409 self.density_policy = policy;
2410 }
2411
2412 /// Whether touch input is accepted. See
2413 /// [`InputTokens::touch_enabled`](teksilo_tokens::InputTokens::touch_enabled).
2414 pub fn touch_enabled(&self) -> bool {
2415 self.theme.input.touch_enabled
2416 }
2417
2418 /// The runtime touch kill switch. With `false`, the platform translator
2419 /// drops touch input and the router installs no touch-only recognizers,
2420 /// so an app can fall back to mouse-only behaviour at runtime.
2421 ///
2422 /// Repaint-level only: turning touch off changes which events are accepted,
2423 /// never a dimension, so nothing is rebuilt or relaid out here. (The
2424 /// translator and router honour it from P08 / P15; this is the state.)
2425 pub fn set_touch_enabled(&mut self, enabled: bool) {
2426 if self.theme.input.touch_enabled == enabled {
2427 return;
2428 }
2429 let mut theme = self.theme.clone();
2430 theme.input.touch_enabled = enabled;
2431 self.theme = theme.clone();
2432 self.theme_signal.set(theme);
2433 self.recompute_effective_theme();
2434 }
2435
2436 /// Recompute [`Self::effective_theme`] from the current `theme` and the
2437 /// combined text scale (`user_text_scale * text_scale_factor`). Callers
2438 /// that change either input are responsible for `mark_all_dirty()`.
2439 fn recompute_effective_theme(&mut self) {
2440 let combined = (self.user_text_scale as f64 * self.text_scale_factor) as f32;
2441 self.effective_theme = if (combined - 1.0).abs() < f32::EPSILON {
2442 self.theme.clone()
2443 } else {
2444 let mut t = self.theme.clone();
2445 t.typography = t.typography.scaled(combined);
2446 t
2447 };
2448 // Single source: every downstream consumer (the layout/paint context
2449 // `text_scale` field, the reactive `text_scale_signal`) reads from here.
2450 self.effective_text_scale = combined;
2451 self.text_scale_signal.set(combined);
2452 }
2453
2454 /// The combined effective text scale (`user_text_scale * OS text_scale_factor`).
2455 /// Read by the layout/paint walkers to populate `ctx.text_scale` for widgets
2456 /// that size from a source other than `Theme.typography`.
2457 pub fn effective_text_scale(&self) -> f32 {
2458 self.effective_text_scale
2459 }
2460
2461 /// Reactive handle on [`Self::effective_text_scale`]. Build-time binders that
2462 /// must react to a scale change without their own rebuild path bind this
2463 /// (e.g. `Calendar` binds it at `Rebuild` level so its fixed cell constants
2464 /// recompute). Fires on `set_user_text_scale` / theme / OS-pref change.
2465 pub fn text_scale_signal(&self) -> crate::signal::Signal<f32> {
2466 self.text_scale_signal.clone()
2467 }
2468
2469 /// Set the user-controlled global text-scale factor (`1.0` = 100 %).
2470 ///
2471 /// The factor multiplies with the OS accessibility text-scale preference to
2472 /// produce the rendered scale. Recomputes the effective theme and marks all
2473 /// widgets dirty so every text widget grows on the next pass; no rebuild,
2474 /// so focus/scroll/interaction state survive. Values outside `[0.25, 8.0]`
2475 /// are clamped. Persisted by the application via
2476 /// `teksilo_settings::TEXT_SCALE_KEY`.
2477 pub fn set_user_text_scale(&mut self, factor: f32) {
2478 let clamped = factor.clamp(0.25, 8.0);
2479 if (self.user_text_scale - clamped).abs() < f32::EPSILON {
2480 return;
2481 }
2482 self.user_text_scale = clamped;
2483 self.recompute_effective_theme();
2484 self.arena.mark_all_dirty();
2485 // Same reasoning as `set_theme`: bigger text re-wraps inside a box
2486 // whose size the parent may hold fixed.
2487 self.a11y_dirty = true;
2488 }
2489
2490 /// The current user-controlled text-scale factor (`1.0` = 100 %).
2491 pub fn user_text_scale(&self) -> f32 {
2492 self.user_text_scale
2493 }
2494
2495 /// After a rebuild that destroyed subtrees — or after a `visible_when` /
2496 /// `Switcher` pass parks the focused widget dormant — drop any interaction
2497 /// state (focus, hover) whose target `WidgetId` is no longer active.
2498 ///
2499 /// **FocusLost is load-bearing.** Clearing `self.focused` alone leaves the
2500 /// widget's own `on_focus` / `has_focus` / caret-blink state thinking it is
2501 /// still focused. A rich-text editor in that state keeps scheduling
2502 /// `wake_at` caret toggles and re-arming `frame_request` from its tick
2503 /// effect — and because `frame_tick` observers are **not** gated on
2504 /// dormancy, every open tab's editor (TabWidget mounts them all) still runs
2505 /// on those wakes. Rapid tab switches that park a focused editor without a
2506 /// real focus move (programmatic selection, race with pointer focus) used
2507 /// to accumulate stuck "focused" editors and unbounded frame work. Dispatch
2508 /// `FocusLost` first so widgets clear that state, then drop the tree's
2509 /// focus pointer.
2510 ///
2511 /// Preserves state when the target still exists *and* is active. Called from
2512 /// data-driven rebuild paths (`process_state_changes`) and after every
2513 /// rebuild drain; theme and locale switches no longer rebuild.
2514 pub(crate) fn revalidate_interaction_state(&mut self, ops: &mut dyn crate::window::WindowOps) {
2515 if let Some(id) = self.focused
2516 && !self.arena.is_active(id)
2517 {
2518 let old = self.focused;
2519 // Deliver FocusLost while the node still exists (dormant or about to
2520 // be torn down). Skip if the node is already gone — destroy paths
2521 // take care of bookkeeping without a deliverable target.
2522 if self.arena.get(id).is_some() {
2523 // Direct: no bubble through dormant ancestors, no overlay
2524 // dismiss side-effects — this is a teardown signal, not a
2525 // user-driven focus move.
2526 self.dispatch_to_widget_direct(
2527 id,
2528 &crate::event::WidgetEvent::FocusLost,
2529 &mut *ops,
2530 );
2531 }
2532 self.set_focused(None);
2533 self.focus_origin = None;
2534 self.update_focus_within_signals(old, None);
2535 self.update_view_focus_signals(old, None);
2536 self.a11y_dirty = true;
2537 }
2538 if self.focused.is_none() {
2539 self.focus_origin = None;
2540 }
2541 if let Some(id) = self.hovered_id()
2542 && !self.arena.is_active(id)
2543 {
2544 let old = self.hovered_id();
2545 self.set_hovered(None);
2546 self.update_hover_within_signals(old, None);
2547 }
2548 // Pointer capture anchored at a destroyed widget would otherwise
2549 // swallow every subsequent Move/Up — dispatch_to_widget rejects
2550 // inactive targets. Drop the capture so events resume normal
2551 // hit-test dispatch. Same for any in-flight drag session whose
2552 // source was torn down: the user sees the drag "stick".
2553 self.pointers.retain_active(&self.arena);
2554 // External (OS) drags have no in-app source widget, so they are never
2555 // torn down by source destruction — only internal drags are salvaged.
2556 let source_gone = self
2557 .active_drag
2558 .as_ref()
2559 .and_then(|s| s.source_widget)
2560 .is_some_and(|sw| !self.arena.is_active(sw));
2561 if source_gone {
2562 // `cancel_active_drag` fires on_drag_leave on the current
2563 // target before cleanup — the same contract as Escape.
2564 self.cancel_active_drag(&mut *ops);
2565 } else {
2566 // The drag *source* survived but its current hover **target** was
2567 // torn down by the rebuild (e.g. a side disabled / collapsed
2568 // mid-drag destroyed the panel under the pointer). Clear the stale
2569 // target id so a subsequent drop doesn't resolve to a destroyed
2570 // widget (and silently vanish); the next move — or the drop's own
2571 // re-hit-test — re-engages a live target.
2572 let stale_target = self
2573 .active_drag
2574 .as_ref()
2575 .and_then(|d| d.current_target)
2576 .is_some_and(|t| !self.arena.is_active(t));
2577 if stale_target && let Some(drag) = self.active_drag.as_mut() {
2578 drag.current_target = None;
2579 }
2580 }
2581 }
2582
2583 /// Rebuild a single composite widget: destroy old children, re-run `build()`,
2584 /// and wire up new children. Called from `process_state_changes()` when a
2585 /// binding at `BindingLevel::Rebuild` fires (data-driven rebuild). Theme
2586 /// and locale changes do **not** rebuild — they update reactive signals
2587 /// that widgets bind to via `theme_signal()` / `locale_signal()`.
2588 /// Test-only: force-mark a widget for rebuild on the next layout
2589 /// pass. Lets regression tests exercise the rebuild path without
2590 /// needing to trip a Signal binding. Exposed cross-crate (not
2591 /// `#[cfg(test)]`-gated) so widget-crate tests in `teksilo-widgets`
2592 /// and elsewhere can also drive rebuilds; the `_for_testing`
2593 /// suffix marks it as not intended for application code.
2594 pub fn arena_mark_needs_rebuild_for_testing(&mut self, id: WidgetId) {
2595 self.arena.mark_needs_rebuild(id);
2596 }
2597
2598 /// Force a [`DeferredSubtree`](crate::deferred_subtree::DeferredSubtree) at
2599 /// `id` to build its content now. A no-op for any other widget.
2600 ///
2601 /// The framework's own door into deferred content, for the case where the
2602 /// decision to show is the tree's rather than a widget's: a tooltip whose
2603 /// dwell has just matured has no open signal anyone could have handed over.
2604 pub(crate) fn materialize_deferred(&mut self, id: WidgetId) {
2605 let forced = self
2606 .arena
2607 .get_mut(id)
2608 .and_then(|n| n.widget.as_any_mut())
2609 .and_then(|any| any.downcast_mut::<crate::deferred_subtree::DeferredSubtree>())
2610 .map(|deferred| {
2611 let needed = !deferred.is_materialized();
2612 deferred.force();
2613 needed
2614 })
2615 .unwrap_or(false);
2616 if forced {
2617 self.rebuild_single_widget(id);
2618 }
2619 }
2620
2621 pub(crate) fn rebuild_single_widget(&mut self, widget_id: WidgetId) {
2622 // Per §9.4.5, drop the source handle first (stops further source-side
2623 // dispatch) and then remove the UI-side callback. Either order gives
2624 // the same user-visible outcome for events that get posted between
2625 // the two steps, but dropping the source handle first stops the
2626 // publisher thread's work sooner.
2627 //
2628 // ⚠ That reasoning is about the two steps below, and it used to be
2629 // read as covering the whole problem. It does not. The dangerous gap
2630 // is not the microseconds between these two lines, it is the whole
2631 // span from *publish* to *dispatch*: a backend event is posted with
2632 // the id its publisher captured and is handled by the UI thread
2633 // frames later, so any rebuild in between used to strand it. The ids
2634 // are therefore carried across into the new build (see
2635 // `BuildContext::reusable_sub_ids`) rather than being retired here.
2636 // Skribisto's Analysis pane hit this every time it was the restored
2637 // view at project open: it starts a long operation in `build()` and
2638 // sets its own `Rebuild`-bound state signal, the operation finished
2639 // inside its own rebuild, and the pane sat on "Reading the
2640 // manuscript…" for the rest of the session with nothing logged.
2641 // Cancel any looping/one-shot animations owned by this widget
2642 // before build() runs. Without this, a widget that creates a
2643 // fresh `animated_signal` in build() would leak the previous
2644 // instance's scheduler entry: the old Signal<f32> clone lives
2645 // in `animations` forever, ticking against an orphaned signal
2646 // (silent CPU waste) and, for looping animations, doubling up
2647 // when the new one registers.
2648 self.animation_scheduler.cancel_by_widget(widget_id);
2649 // Same pattern for shader-driven animated quads: free the
2650 // widget's slot(s) so `build()` can allocate fresh handles.
2651 // The old cached_paint (if any) carries stale slot indices —
2652 // clear it so paint() re-runs and re-emits DrawCommands with
2653 // the newly-allocated slot.
2654 self.animated_quads.cancel_by_widget(widget_id);
2655
2656 let drained_subs = if let Some(node) = self.arena.get_mut(widget_id) {
2657 node.effect_handles.clear();
2658 node.actions.clear();
2659 node.dirty.needs_rebuild = false;
2660 node.cached_paint = None;
2661 node.dirty.needs_paint = true;
2662 // Reset only the OWN handler bucket so `apply_self_handlers`
2663 // during this build's fresh build() starts from empty and
2664 // doesn't stack N-fold handler chains across rebuilds.
2665 // `external_handlers` — set by the `WidgetBuilder` chain at
2666 // creation time or by a composing parent's
2667 // `apply_handlers(child_id, ...)` — persists: those handlers
2668 // come from outside the widget and aren't re-emitted by its
2669 // own `build()`.
2670 //
2671 // `node_focusable` / `node_tab_index` / `node_cursor` /
2672 // `clips_children` / `context_menu_factory` are simple
2673 // values, not accumulating closures. Leave them alone —
2674 // apply_self_handlers rewrites them if the new build
2675 // specifies non-None values; otherwise values from the
2676 // creation site survive the rebuild.
2677 node.handlers = crate::event_handlers::EventHandlers::new();
2678 std::mem::take(&mut node.subscription_handles)
2679 } else {
2680 Vec::new()
2681 };
2682 // Rebuild wiped the OWN handler bucket above (the gesture arena
2683 // lived there), so the widget no longer owns any recognizers.
2684 // The next pointer hit re-runs `ensure_gesture_arena` and
2685 // re-inserts if the new build still wires gesture handlers.
2686 // External handlers (set via the builder chain at creation time)
2687 // persist, but `external_handlers` never carries a gesture arena
2688 // directly — it's always built by `ensure_gesture_arena` into
2689 // the OWN bucket.
2690 self.gesture_owners.remove(&widget_id);
2691 // Shortcuts the widget declared are torn down too — they will
2692 // be re-registered during the upcoming `build()` call. User
2693 // overrides live in a separate map keyed by id, so user
2694 // rebindings survive this round-trip (see ShortcutRegistry
2695 // graveyard semantics).
2696 self.shortcut_registry.unregister_all_for_owner(widget_id);
2697 self.global_actions.retain(|(owner, _)| *owner != widget_id);
2698 self.text_surfaces.remove(widget_id);
2699 // Re-apply `Widget::declare_shortcuts` so the static metadata
2700 // survives the rebuild (the unregister above wiped both
2701 // declared and build-registered entries; build() will refill
2702 // the handler-bearing ones, but it can't be relied on to
2703 // refill the metadata-only declarations).
2704 self.apply_declared_shortcuts(widget_id);
2705 // Drop any signal→widget bindings from the previous build
2706 // cycle so `build()` can re-register a fresh set without
2707 // accumulating duplicates across rebuilds.
2708 self.binding_registry.unregister_for_widget(widget_id);
2709 // Kept, in order, and handed to the upcoming `build()` so it re-subscribes under
2710 // the same ids. A subscription's id is what a publisher captured and posted with;
2711 // minting new ones here would leave every event already queued for this widget
2712 // naming an id nothing answers to. See `BuildContext::reusable_sub_ids`.
2713 let mut reusable_sub_ids = Vec::with_capacity(drained_subs.len());
2714 for (sub_id, handle) in drained_subs {
2715 drop(handle);
2716 self.app_context
2717 .subscription_callbacks
2718 .borrow_mut()
2719 .remove(&sub_id);
2720 self.app_context
2721 .subscription_ctx_callbacks
2722 .borrow_mut()
2723 .remove(&sub_id);
2724 reusable_sub_ids.push(sub_id);
2725 }
2726
2727 // Decide how to treat the existing children. Two modes:
2728 //
2729 // * Default (`preserves_children_on_rebuild() == false`): the widget
2730 // re-derives its whole subtree, so tear down every old child up
2731 // front and let `build()` produce a fresh set.
2732 //
2733 // * Reconcile (`preserves_children_on_rebuild() == true`): the widget
2734 // re-attaches the children it keeps (by id) and drops the rest. We
2735 // snapshot the old children, run `build()`, then destroy only the
2736 // old children the new build did NOT re-attach and did NOT re-parent
2737 // elsewhere. Re-attached children keep their state (focus, scroll,
2738 // text, subscriptions); dropped children are reaped rather than left
2739 // as stranded, still-active orphans.
2740 let preserve_children = self
2741 .arena
2742 .get(widget_id)
2743 .map(|n| n.widget.preserves_children_on_rebuild())
2744 .unwrap_or(false);
2745 let old_children: Vec<WidgetId> = self.arena.children(widget_id).to_vec();
2746 if !preserve_children {
2747 for child_id in &old_children {
2748 self.destroy_subtree(*child_id);
2749 }
2750 }
2751
2752 // The parentless nodes the *previous* build owned. Taken now so
2753 // `build()` records its new set into an empty list, and destroyed after
2754 // it returns — by then the widget's own fields point at the new nodes,
2755 // so tearing the old ones down cannot strand a live id in the widget.
2756 // Both the `preserve_children` reconcile and the plain path want this:
2757 // detached content is rebuilt wholesale either way (it is not addressed
2758 // by id from the outside, so there is nothing to preserve).
2759 let old_detached: Vec<WidgetId> = self
2760 .arena
2761 .get_mut(widget_id)
2762 .map(|node| std::mem::take(&mut node.detached))
2763 .unwrap_or_default();
2764
2765 let mut widget_box = match self.arena.take_widget(widget_id) {
2766 Some(widget) => widget,
2767 None => return,
2768 };
2769
2770 let mut build_ctx = crate::build_context::BuildContext {
2771 tree: self,
2772 composite_id: Some(widget_id),
2773 effect_handles: Vec::new(),
2774 subscription_handles: Vec::new(),
2775 reusable_sub_ids,
2776 };
2777 let new_children = widget_box.build(&mut build_ctx);
2778 let effect_handles = std::mem::take(&mut build_ctx.effect_handles);
2779 let subscription_handles = std::mem::take(&mut build_ctx.subscription_handles);
2780
2781 self.arena.restore_widget(widget_id, widget_box);
2782
2783 for &child_id in &new_children {
2784 if let Some(child_node) = self.arena.get_mut(child_id) {
2785 child_node.parent = Some(widget_id);
2786 }
2787 }
2788
2789 // Reconcile the preserve path: reap any old child the new build
2790 // dropped (not in `new_children`) and did not re-parent elsewhere
2791 // (its `parent` still points here). Authoritative parent pointers mean
2792 // a kept subtree re-parented out of a dropped sibling survives. Runs
2793 // before `node.children` is overwritten so the destroy walk can't see
2794 // the new list. Re-parented survivors already have their new parent by
2795 // now (`ctx.add` builds nested widgets synchronously and re-homes their
2796 // children), so the `parent == widget_id` test correctly excludes them.
2797 if preserve_children {
2798 let new_set: std::collections::HashSet<WidgetId> =
2799 new_children.iter().copied().collect();
2800 for &old_c in &old_children {
2801 if !new_set.contains(&old_c) && self.arena.parent(old_c) == Some(widget_id) {
2802 self.destroy_subtree_inner(old_c, true);
2803 }
2804 }
2805 }
2806
2807 if let Some(node) = self.arena.get_mut(widget_id) {
2808 node.children = new_children;
2809 node.effect_handles = effect_handles;
2810 node.subscription_handles = subscription_handles;
2811 }
2812
2813 // Reap the previous build's parentless content, now that the fresh set
2814 // is recorded and the widget points at it.
2815 for id in old_detached {
2816 self.destroy_subtree_inner(id, false);
2817 }
2818 }
2819
2820 /// Record that `owner` created and owns the parentless node `detached` —
2821 /// pre-built overlay content that is deliberately not a child. See
2822 /// [`BuildContext::add_detached`](crate::build_context::BuildContext::add_detached)
2823 /// and [`WidgetNode::detached`](crate::arena::WidgetNode).
2824 pub(crate) fn record_detached(&mut self, owner: WidgetId, detached: WidgetId) {
2825 if let Some(node) = self.arena.get_mut(owner) {
2826 node.detached.push(detached);
2827 }
2828 }
2829
2830 /// Destroy every parentless node `owner` owns, and forget them.
2831 ///
2832 /// Taken out of the node first: the destroy walk below can re-enter this
2833 /// function (a detached node may own detached nodes of its own — a rich
2834 /// tooltip's cascade children each pre-build their own), and it must not
2835 /// see a list it is halfway through consuming.
2836 fn destroy_detached_of(&mut self, owner: WidgetId) {
2837 let detached = self
2838 .arena
2839 .get_mut(owner)
2840 .map(|node| std::mem::take(&mut node.detached))
2841 .unwrap_or_default();
2842 for id in detached {
2843 self.destroy_subtree_inner(id, false);
2844 }
2845 }
2846
2847 /// Recursively destroy a subtree, dropping per-widget subscription
2848 /// handles and removing their UI-side callbacks. Use this in place of
2849 /// `arena.destroy()` whenever a widget that may have subscribed to
2850 /// events is being torn down.
2851 pub(crate) fn destroy_subtree(&mut self, widget_id: WidgetId) {
2852 self.destroy_subtree_inner(widget_id, false);
2853 }
2854
2855 /// Shared teardown for [`destroy_subtree`](Self::destroy_subtree) and the
2856 /// reconciling rebuild path. When `reparent_aware` is `true`, recursion
2857 /// descends into a child only if that child's `parent` still points at
2858 /// `widget_id`.
2859 ///
2860 /// A reconciling rebuild (a [`preserves_children_on_rebuild`] widget) may
2861 /// re-parent a kept subtree *out* of a dropped sibling and *into* the new
2862 /// tree. The dropped sibling's `children` list still lists that subtree
2863 /// (stale), so following it would tear down a node that is actually alive
2864 /// elsewhere. Following the authoritative `parent` pointer instead stops
2865 /// at the boundary of what genuinely still belongs to the node being
2866 /// destroyed. The per-node teardown ends with `arena.remove_node` (a
2867 /// single-node removal), NOT `arena.destroy` (which would re-recurse the
2868 /// stale `children` list and undo the skip).
2869 ///
2870 /// [`preserves_children_on_rebuild`]: crate::widget::Widget::preserves_children_on_rebuild
2871 fn destroy_subtree_inner(&mut self, widget_id: WidgetId, reparent_aware: bool) {
2872 // See the matching cancel in `rebuild_single_widget` — the
2873 // scheduler holds strong Signal<f32> clones, so the animation
2874 // would outlive its widget without this explicit cancellation.
2875 self.animation_scheduler.cancel_by_widget(widget_id);
2876 // Release the animated-quad slot(s) too.
2877 self.animated_quads.cancel_by_widget(widget_id);
2878 // A tooltip's content widget is parentless (`ctx.add`), so the child
2879 // walk below never reaches it — reap it explicitly or the entry and
2880 // its node outlive the anchor for the lifetime of the tree.
2881 self.retire_tooltips_of_destroyed_anchor(widget_id);
2882 // Same reasoning, one level up: every *other* parentless node this
2883 // widget built (a dropdown menu, a calendar, a tooltip's nested
2884 // cascade children) is unreachable from the child walk and dies here
2885 // or never.
2886 self.destroy_detached_of(widget_id);
2887
2888 let children: Vec<WidgetId> = self.arena.children(widget_id).to_vec();
2889 for child in children {
2890 if reparent_aware && self.arena.parent(child) != Some(widget_id) {
2891 // Re-parented into the surviving tree by this rebuild — leave it.
2892 continue;
2893 }
2894 self.destroy_subtree_inner(child, reparent_aware);
2895 }
2896 let drained_subs = self
2897 .arena
2898 .get_mut(widget_id)
2899 .map(|node| std::mem::take(&mut node.subscription_handles))
2900 .unwrap_or_default();
2901 for (sub_id, handle) in drained_subs {
2902 drop(handle);
2903 self.app_context
2904 .subscription_callbacks
2905 .borrow_mut()
2906 .remove(&sub_id);
2907 self.app_context
2908 .subscription_ctx_callbacks
2909 .borrow_mut()
2910 .remove(&sub_id);
2911 }
2912 // Drop any shortcuts the destroyed widget owned. Unlike
2913 // `rebuild_single_widget`, destruction is permanent; if the
2914 // user had overrides, they stay in the graveyard.
2915 self.shortcut_registry.unregister_all_for_owner(widget_id);
2916 self.global_actions.retain(|(owner, _)| *owner != widget_id);
2917 self.text_surfaces.remove(widget_id);
2918 // Bindings from this widget stop being relevant; clean them
2919 // up so the registry doesn't leak dead entries for the
2920 // lifetime of the app.
2921 self.binding_registry.unregister_for_widget(widget_id);
2922 // Keep `gesture_owners` honest — destroying the widget tears
2923 // down its handlers, so the per-frame gesture pass must stop
2924 // visiting it.
2925 self.gesture_owners.remove(&widget_id);
2926 // If focus pointed at the widget about to disappear, drop it
2927 // so later dispatch doesn't anchor intent walks at a dead id
2928 // (which would silently swallow the intent).
2929 if self.focused == Some(widget_id) {
2930 let old = self.focused;
2931 self.set_focused(None);
2932 self.focus_origin = None;
2933 self.update_focus_within_signals(old, None);
2934 self.update_view_focus_signals(old, None);
2935 }
2936 if self.hovered_id() == Some(widget_id) {
2937 let old = self.hovered_id();
2938 self.set_hovered(None);
2939 self.update_hover_within_signals(old, None);
2940 }
2941 // Symmetric with focus/hover above: a pointer capture anchored at the
2942 // widget about to disappear would otherwise swallow every subsequent
2943 // Move/Up (dispatch rejects inactive targets) until the next layout
2944 // pass runs `revalidate_interaction_state`. Drop it eagerly so capture
2945 // never outlives its owner, even when a destroy happens mid-gesture.
2946 self.pointers.release_captures_of(widget_id);
2947 // Single-node removal: this function already recursed into the
2948 // children above (honouring re-parenting when `reparent_aware`).
2949 // `arena.destroy` would re-recurse the now-stale `children` list and
2950 // tear down a survivor re-homed out of this subtree.
2951 self.arena.remove_node(widget_id);
2952 }
2953
2954 /// Set the layout direction (LTR/RTL). Marks all widgets as needing layout.
2955 pub fn set_layout_direction(&mut self, direction: crate::environment::LayoutDirection) {
2956 self.layout_direction = direction;
2957 self.arena.mark_all_dirty();
2958 }
2959
2960 /// The current layout direction.
2961 pub fn layout_direction(&self) -> crate::environment::LayoutDirection {
2962 self.layout_direction
2963 }
2964
2965 /// Set OS-level accessibility preferences.
2966 ///
2967 /// Called by `teksilo-app` after querying the platform layer. Updates the
2968 /// values fed into `PaintContext` and `Environment` on subsequent frames.
2969 /// Marks all widgets dirty so the new preferences take effect immediately.
2970 pub fn set_accessibility_preferences(
2971 &mut self,
2972 high_contrast: bool,
2973 reduced_motion: bool,
2974 text_scale_factor: f64,
2975 ) {
2976 let changed = self.prefers_high_contrast != high_contrast
2977 || self.prefers_reduced_motion != reduced_motion
2978 || (self.text_scale_factor - text_scale_factor).abs() > f64::EPSILON;
2979
2980 if changed {
2981 self.prefers_high_contrast = high_contrast;
2982 self.prefers_reduced_motion = reduced_motion;
2983 self.text_scale_factor = text_scale_factor;
2984 // The OS factor feeds the effective text scale (multiplied with the
2985 // user factor), so refresh the cached scaled typography.
2986 self.recompute_effective_theme();
2987 self.arena.mark_all_dirty();
2988 }
2989 }
2990
2991 /// Whether the OS has requested high-contrast mode.
2992 pub fn prefers_high_contrast(&self) -> bool {
2993 self.prefers_high_contrast
2994 }
2995
2996 /// Whether the OS has requested reduced motion.
2997 pub fn prefers_reduced_motion(&self) -> bool {
2998 self.prefers_reduced_motion
2999 }
3000
3001 /// OS text scaling factor (1.0 = normal).
3002 pub fn text_scale_factor(&self) -> f64 {
3003 self.text_scale_factor
3004 }
3005
3006 /// Report whether the *operating system* says an assistive technology is
3007 /// reading the screen.
3008 ///
3009 /// Fed by `teksilo-app` from `teksilo_platform::AccessibilityPreferences`,
3010 /// which asks Windows for `SPI_GETSCREENREADER`, AT-SPI for
3011 /// `org.a11y.Status.ScreenReaderEnabled`, and macOS for
3012 /// `NSWorkspace::isVoiceOverEnabled`. A platform that cannot answer leaves
3013 /// it [`ScreenReaderState::Unknown`], which behaves as "no".
3014 ///
3015 /// [`ScreenReaderState::Unknown`]: crate::environment::ScreenReaderState::Unknown
3016 ///
3017 /// **Not** AccessKit activation. An AccessKit adapter activates for
3018 /// anything that walks the tree — a screen magnifier, a voice-control front
3019 /// end, a UI-automation inspector, a tree browser like Accerciser — none of
3020 /// which want a touch to become a probe. Treating activation as evidence of
3021 /// a screen reader is how explore-by-touch gets switched on under an
3022 /// inspector and makes the app untouchable.
3023 ///
3024 /// [`ScreenReaderState`]: crate::environment::ScreenReaderState
3025 pub fn set_screen_reader_state(&mut self, state: crate::environment::ScreenReaderState) {
3026 self.screen_reader = state;
3027 }
3028
3029 /// The screen-reader state most recently reported by the platform.
3030 ///
3031 /// [`ScreenReaderState::Unknown`] until something reports one.
3032 ///
3033 /// [`ScreenReaderState::Unknown`]: crate::environment::ScreenReaderState::Unknown
3034 pub fn screen_reader_state(&self) -> crate::environment::ScreenReaderState {
3035 self.screen_reader
3036 }
3037
3038 /// Choose how explore-by-touch is decided for this window.
3039 ///
3040 /// [`ExploreByTouch::Off`] is the default and today's behaviour;
3041 /// [`ExploreByTouch::Auto`] follows [`Self::screen_reader_state`];
3042 /// [`ExploreByTouch::On`] forces it regardless. Read the resolved answer
3043 /// with [`Self::explore_by_touch_active`].
3044 ///
3045 /// [`ExploreByTouch::Off`]: crate::environment::ExploreByTouch::Off
3046 /// [`ExploreByTouch::Auto`]: crate::environment::ExploreByTouch::Auto
3047 /// [`ExploreByTouch::On`]: crate::environment::ExploreByTouch::On
3048 pub fn set_explore_by_touch(&mut self, mode: crate::environment::ExploreByTouch) {
3049 self.explore_by_touch = mode;
3050 }
3051
3052 /// The explore-by-touch policy most recently set.
3053 pub fn explore_by_touch(&self) -> crate::environment::ExploreByTouch {
3054 self.explore_by_touch
3055 }
3056
3057 /// Whether explore-by-touch is in force right now.
3058 ///
3059 /// `On` is unconditional; `Auto` requires the platform to have reported an
3060 /// active screen reader; `Off` is never in force. Nothing in the framework
3061 /// consumes this yet — the touch-as-probe interaction it gates has no
3062 /// owner — so it is a supply, a policy and a query, and no pointer path
3063 /// branches on it.
3064 pub fn explore_by_touch_active(&self) -> bool {
3065 use crate::environment::{ExploreByTouch, ScreenReaderState};
3066 match self.explore_by_touch {
3067 ExploreByTouch::Off => false,
3068 ExploreByTouch::On => true,
3069 ExploreByTouch::Auto => self.screen_reader == ScreenReaderState::Active,
3070 }
3071 }
3072
3073 /// Report whether an AccessKit client is attached to this window.
3074 ///
3075 /// Written by `teksilo-app` from the platform adapter's activation and
3076 /// deactivation handlers, and used **asymmetrically** on purpose:
3077 ///
3078 /// * Attaching proves nothing. Magnifier, Voice Access and a UI-automation
3079 /// inspector all activate the adapter, so this never sets
3080 /// [`ScreenReaderState::Active`].
3081 /// * Detaching proves something. When the last client goes away there is
3082 /// no screen reader either, so a `true` → `false` transition forces
3083 /// [`ScreenReaderState::Inactive`] and an
3084 /// [`ExploreByTouch::Auto`](crate::environment::ExploreByTouch::Auto)
3085 /// window stops exploring immediately, without waiting for the next OS
3086 /// query. A later OS query is free to say `Active` again.
3087 ///
3088 /// [`ScreenReaderState::Active`]: crate::environment::ScreenReaderState::Active
3089 /// [`ScreenReaderState::Inactive`]: crate::environment::ScreenReaderState::Inactive
3090 pub fn set_at_client_attached(&mut self, attached: bool) {
3091 if self.at_client_attached && !attached {
3092 self.screen_reader = crate::environment::ScreenReaderState::Inactive;
3093 }
3094 self.at_client_attached = attached;
3095 }
3096
3097 /// Whether an AccessKit client is currently attached to this window.
3098 pub fn at_client_attached(&self) -> bool {
3099 self.at_client_attached
3100 }
3101
3102 /// Set the host window HiDPI device scale (physical px per logical px).
3103 /// Written by `teksilo-app` when the window is created and again on
3104 /// `WindowEvent::ScaleFactorChanged`. Surfaced to widgets via
3105 /// `LayoutContext::scale_factor`.
3106 ///
3107 /// Layout needs no dirty-marking here: it rides the layout pass that
3108 /// follows, and a scale change already triggers a relayout. The
3109 /// accessibility tree does, because the scale is the root node's
3110 /// transform (AccessKit wants physical coordinates, the tree emits
3111 /// logical ones) and a plain relayout does not invalidate the AT cache —
3112 /// so dragging a window between a 1x and a 2x monitor would otherwise
3113 /// leave every reported rectangle at the old display's scale.
3114 pub fn set_device_scale_factor(&mut self, scale_factor: f32) {
3115 if self.device_scale_factor != scale_factor {
3116 self.device_scale_factor = scale_factor;
3117 self.a11y_dirty = true;
3118 }
3119 }
3120
3121 /// The host window HiDPI device scale most recently set (1.0 by default).
3122 pub fn device_scale_factor(&self) -> f32 {
3123 self.device_scale_factor
3124 }
3125
3126 /// Report the host window's platform safe-area insets — the region the
3127 /// window owns but a person cannot fully see or touch (a display cutout, a
3128 /// rounded corner, a home indicator).
3129 ///
3130 /// Fed by `teksilo-app` from
3131 /// `teksilo_platform::safe_area`, which reads the window on macOS and
3132 /// answers `ZERO` everywhere else because no other desktop platform
3133 /// reports one. Overlays clamp into what is left; the root layout
3134 /// proposal is deliberately **not** shrunk — a safe area moves what floats
3135 /// over the content, not the content.
3136 pub fn set_safe_area(&mut self, insets: teksilo_canvas::EdgeInsets) {
3137 if self.safe_area != insets {
3138 self.safe_area = insets;
3139 // Overlay placement is recomputed from scratch by every layout
3140 // pass, so the change reaches the screen as soon as one runs; the
3141 // frame request is what guarantees one does.
3142 self.request_frame();
3143 }
3144 }
3145
3146 /// The safe-area insets most recently set (`ZERO` by default).
3147 pub fn safe_area(&self) -> teksilo_canvas::EdgeInsets {
3148 self.safe_area
3149 }
3150
3151 /// Report a rectangle of the window currently covered from outside the
3152 /// tree — a soft keyboard, a platform IME candidate window — in
3153 /// window-logical pixels, or `None` when nothing covers it.
3154 ///
3155 /// A **rectangle**, not a named edge, because that is what a platform
3156 /// reports and because the placement code resolves it by keeping the
3157 /// largest free slab rather than by insetting an edge: a keyboard at the
3158 /// bottom gives the band above it, a candidate window at a side gives the
3159 /// band beside it, and neither needs the platform to say which edge it
3160 /// came from.
3161 ///
3162 /// Scope: like the safe area, this reaches **overlay placement only**. The
3163 /// root layout proposal keeps the whole window, so a scroll container
3164 /// still extends behind the keyboard and nothing reflows when one rises —
3165 /// which is what the desktop convention wants, and what keeps a keyboard
3166 /// appearing from being a full relayout of the document. Bringing a
3167 /// focused field out from behind the band is a scroll, against
3168 /// [`usable_viewport`](Self::usable_viewport), not a resize.
3169 pub fn set_occluded_inset(&mut self, occluded: Option<Rect>) {
3170 if self.occluded_inset != occluded {
3171 self.occluded_inset = occluded;
3172 self.request_frame();
3173 }
3174 }
3175
3176 /// The occluding rectangle most recently set (`None` by default).
3177 pub fn occluded_inset(&self) -> Option<Rect> {
3178 self.occluded_inset
3179 }
3180
3181 /// The viewport overlays are placed into: the last laid-out window size,
3182 /// less the safe area, less anything covering it.
3183 ///
3184 /// The same rectangle `position_overlays` clamps into, exposed so a
3185 /// consumer that must put something *in front of* a keyboard — a
3186 /// scroll-into-view for the focused field — can ask for it rather than
3187 /// re-deriving it.
3188 pub fn usable_viewport(&self) -> Rect {
3189 let proposal = self.last_proposal();
3190 let size = teksilo_canvas::Size::new(
3191 proposal.width.unwrap_or(0.0),
3192 proposal.height.unwrap_or(0.0),
3193 );
3194 self.overlay_viewport_for(size)
3195 .usable(self.layout_direction)
3196 }
3197
3198 /// Build the overlay viewport for a window of `size`, folding in the
3199 /// safe area and the occluding rectangle.
3200 pub(crate) fn overlay_viewport_for(
3201 &self,
3202 size: teksilo_canvas::Size,
3203 ) -> crate::overlay::OverlayViewport {
3204 crate::overlay::OverlayViewport::new(size)
3205 .with_safe_area(self.safe_area)
3206 .with_occluded(self.occluded_inset)
3207 }
3208
3209 /// Ask the platform to show (`true`) or hide (`false`) its on-screen
3210 /// keyboard.
3211 ///
3212 /// Recorded here rather than pushed straight at the window because the one
3213 /// thing the request must not do is re-assert IME allowance while a
3214 /// composition is live, and the IME-allowance state lives in the app
3215 /// layer's per-window reconcile. `teksilo-app` takes the request once per
3216 /// dispatch, after that reconcile, and applies it against the platform's
3217 /// [`SoftKeyboardSupport`](crate::window::SoftKeyboardSupport) answer.
3218 pub fn request_soft_keyboard(&mut self, visible: bool) {
3219 self.soft_keyboard_request = Some(visible);
3220 }
3221
3222 /// Take the pending soft-keyboard request, if any. Called by the app layer
3223 /// once per dispatch.
3224 pub fn take_soft_keyboard_request(&mut self) -> Option<bool> {
3225 self.soft_keyboard_request.take()
3226 }
3227
3228 /// Mark a widget as clipping its children to its bounds (scroll areas).
3229 pub fn set_clips_children(&mut self, id: WidgetId, clips: bool) {
3230 self.arena.set_clips_children(id, clips);
3231 }
3232
3233 /// Apply a `HandlerSet` to an existing node in the arena, routed
3234 /// into the rebuild-cleared `handlers` slot (the widget's own
3235 /// self-applied handlers).
3236 /// Register any *bound* builder-level accessibility Props
3237 /// (`access_hidden` / `access_label` / `access_description` /
3238 /// `access_value`) at `BindingLevel::AccessibilityOnly`, so that a change
3239 /// to the underlying signal flips `a11y_dirty` and the AccessKit tree
3240 /// re-walks — re-resolving the announced hidden-state / name / description
3241 /// / value — without a visual relayout. Static Props are ignored by
3242 /// `register_if_bound`. Takes the registry explicitly (rather than `&self`)
3243 /// so insertion-path callers can keep a disjoint `&mut self.arena` borrow
3244 /// on the node alive.
3245 fn register_access_prop_bindings(
3246 access: &crate::widget_builder::AccessibilityOverrides,
3247 id: WidgetId,
3248 registry: &crate::binding::BindingRegistry,
3249 ) {
3250 use crate::binding::BindingLevel::AccessibilityOnly;
3251 if let Some(p) = access.hidden.as_ref() {
3252 p.register_if_bound(id, registry, AccessibilityOnly);
3253 }
3254 if let Some(p) = access.label.as_ref() {
3255 p.register_if_bound(id, registry, AccessibilityOnly);
3256 }
3257 if let Some(p) = access.description.as_ref() {
3258 p.register_if_bound(id, registry, AccessibilityOnly);
3259 }
3260 if let Some(p) = access.value.as_ref() {
3261 p.register_if_bound(id, registry, AccessibilityOnly);
3262 }
3263 }
3264
3265 pub(crate) fn apply_self_handler_set(
3266 &mut self,
3267 id: WidgetId,
3268 mut handler_set: crate::widget_builder::HandlerSet,
3269 ) {
3270 // `visible_when` needs the binding registry (which the arena lacks), so
3271 // pull it out here and apply it via `self.visible_when` after.
3272 let visible_when = handler_set.visible_when.take();
3273 // Same reason for the reactive access Props: the arena can't reach the
3274 // registry, so register them here before handing the set to the arena.
3275 if let Some(access) = handler_set.access.as_ref() {
3276 Self::register_access_prop_bindings(access, id, &self.binding_registry);
3277 }
3278 self.arena
3279 .apply_handler_set(id, handler_set, crate::arena::HandlerScope::Own);
3280 if let Some(prop) = visible_when {
3281 self.visible_when(id, prop);
3282 }
3283 }
3284
3285 /// Apply a `HandlerSet` to an existing node as *external* handlers —
3286 /// the kind attached by a composing parent via
3287 /// `BuildContext::apply_handlers(child_id, ...)` or by the
3288 /// `WidgetBuilder` chain at insertion time. These persist across
3289 /// the target widget's own rebuilds.
3290 pub(crate) fn apply_external_handler_set(
3291 &mut self,
3292 id: WidgetId,
3293 mut handler_set: crate::widget_builder::HandlerSet,
3294 ) {
3295 // See `apply_self_handler_set`: route `visible_when` and the reactive
3296 // access Props through the registry (the arena can't reach it).
3297 let visible_when = handler_set.visible_when.take();
3298 if let Some(access) = handler_set.access.as_ref() {
3299 Self::register_access_prop_bindings(access, id, &self.binding_registry);
3300 }
3301 self.arena
3302 .apply_handler_set(id, handler_set, crate::arena::HandlerScope::External);
3303 if let Some(prop) = visible_when {
3304 self.visible_when(id, prop);
3305 }
3306 }
3307
3308 /// Append an accessibility `labelled_by` relation onto an already-mounted
3309 /// node, *preserving* any overrides the widget already carries — unlike
3310 /// `apply_external_handler_set`, which replaces the whole override struct.
3311 /// Used by container widgets (e.g. `FormLayout`) to name a field after its
3312 /// label once both ids are known. Idempotent: re-adding the same target is
3313 /// a no-op, so a composite may re-register the relation on every rebuild.
3314 pub(crate) fn push_access_labelled_by(&mut self, id: WidgetId, label_id: WidgetId) {
3315 if let Some(node) = self.arena.get_mut(id) {
3316 let overrides = node.access_overrides.get_or_insert_with(|| {
3317 Box::new(crate::widget_builder::AccessibilityOverrides::default())
3318 });
3319 // A composite that names itself from its content re-registers the
3320 // relation on every rebuild. Appending blindly would concatenate the
3321 // title into the name once per rebuild.
3322 if overrides.labelled_by.contains(&label_id) {
3323 return;
3324 }
3325 overrides.labelled_by.push(label_id);
3326 self.a11y_dirty = true;
3327 }
3328 }
3329
3330 /// Append an accessibility `described_by` relation onto an already-mounted
3331 /// node, preserving existing overrides (the `described_by` counterpart of
3332 /// [`push_access_labelled_by`](Self::push_access_labelled_by)).
3333 pub(crate) fn push_access_described_by(&mut self, id: WidgetId, target_id: WidgetId) {
3334 if let Some(node) = self.arena.get_mut(id) {
3335 let overrides = node.access_overrides.get_or_insert_with(|| {
3336 Box::new(crate::widget_builder::AccessibilityOverrides::default())
3337 });
3338 if overrides.described_by.contains(&target_id) {
3339 return;
3340 }
3341 overrides.described_by.push(target_id);
3342 self.a11y_dirty = true;
3343 }
3344 }
3345
3346 /// Set a per-child alignment override on a widget.
3347 pub fn set_alignment(&mut self, id: WidgetId, alignment: teksilo_tokens::Alignment) {
3348 self.arena.set_alignment_override(id, alignment);
3349 }
3350
3351 /// Get the binding registry for registering State→Widget bindings.
3352 pub fn binding_registry(&self) -> &crate::binding::BindingRegistry {
3353 &self.binding_registry
3354 }
3355
3356 /// Shared access to the shortcut registry. Widgets register their
3357 /// default shortcuts through here during `build()` (via
3358 /// `BuildContext::register_shortcut`); settings UIs and
3359 /// persistence layers read and mutate overrides directly.
3360 pub fn shortcut_registry(&self) -> &crate::shortcut::ShortcutRegistry {
3361 &self.shortcut_registry
3362 }
3363
3364 pub fn shortcut_registry_mut(&mut self) -> &mut crate::shortcut::ShortcutRegistry {
3365 &mut self.shortcut_registry
3366 }
3367
3368 /// Install a one-shot key-capture callback, returning a
3369 /// [`CaptureHandle`](crate::shortcut::CaptureHandle) whose `Drop`
3370 /// cancels the capture if it hasn't already fired. The next
3371 /// `KeyDown` the tree receives bypasses shortcut-registry lookup
3372 /// and invokes the callback with:
3373 /// - the captured [`KeyStroke`](crate::shortcut::KeyStroke)
3374 /// - mutable access to the registry (rebind in-place)
3375 /// - a mutable [`EventContext`] (so the handler can also emit
3376 /// commands, send intents, dismiss overlays, …)
3377 ///
3378 /// Calling this while a previous capture is armed creates a
3379 /// **separate** slot; the prior handle, when eventually dropped,
3380 /// cancels only its own (now-orphaned) slot. The new capture
3381 /// wins.
3382 pub fn begin_key_capture(
3383 &mut self,
3384 callback: impl FnOnce(
3385 crate::shortcut::KeyStroke,
3386 &mut crate::shortcut::ShortcutRegistry,
3387 &mut EventContext,
3388 ) + 'static,
3389 ) -> crate::shortcut::CaptureHandle {
3390 let slot: crate::shortcut::KeyCaptureSlot =
3391 std::rc::Rc::new(std::cell::RefCell::new(Some(Box::new(callback))));
3392 self.key_capture = Some(slot.clone());
3393 crate::shortcut::CaptureHandle::new(slot)
3394 }
3395
3396 /// Cancel any currently-armed key capture without invoking it.
3397 /// Equivalent to dropping the [`CaptureHandle`](crate::shortcut::CaptureHandle),
3398 /// but exposed here so callers that lost the handle (or never
3399 /// kept one) can still bail out.
3400 pub fn cancel_key_capture(&mut self) {
3401 if let Some(slot) = self.key_capture.take() {
3402 slot.borrow_mut().take();
3403 }
3404 }
3405
3406 /// Whether a key-capture callback is currently armed.
3407 pub fn is_capturing_keys(&self) -> bool {
3408 self.key_capture
3409 .as_ref()
3410 .map(|slot| slot.borrow().is_some())
3411 .unwrap_or(false)
3412 }
3413
3414 /// Consume any pending key-capture callback. Used internally by
3415 /// the dispatch path — returns the boxed closure so the caller
3416 /// can invoke it once the KeyStroke has been constructed. Also
3417 /// drops the outer `Option<Rc<...>>` so `is_capturing_keys` goes
3418 /// back to `false`.
3419 pub(crate) fn take_key_capture(&mut self) -> Option<crate::shortcut::KeyCaptureCallback> {
3420 let slot = self.key_capture.take()?;
3421 slot.borrow_mut().take()
3422 }
3423
3424 /// Append an [`Action`](crate::action::Action) to a widget's arena
3425 /// node. Invoked by `BuildContext::register_action`; not meant
3426 /// to be called directly.
3427 /// Record that `widget_id` edits text. Replaces any previous registration
3428 /// from the same widget, so a rebuild re-points rather than accumulating.
3429 pub(crate) fn push_text_surface(
3430 &mut self,
3431 widget_id: WidgetId,
3432 surface: std::rc::Rc<dyn crate::text_surface::TextSurface>,
3433 ) {
3434 self.text_surfaces.insert(widget_id, surface);
3435 }
3436
3437 /// A cloneable view of this tree's text surfaces, for a caller that must ask
3438 /// the question later, without a `&WidgetTree` in hand.
3439 pub fn text_surfaces(&self) -> crate::text_surface::TextSurfaces {
3440 self.text_surfaces.clone()
3441 }
3442
3443 /// The text-editing widget that currently holds the keyboard focus.
3444 ///
3445 /// `None` when focus is elsewhere — or nowhere — which is exactly what a
3446 /// host needs in order to know that a text chord is safe to route itself.
3447 pub fn focused_text_surface(
3448 &self,
3449 ) -> Option<std::rc::Rc<dyn crate::text_surface::TextSurface>> {
3450 self.text_surfaces.focused()
3451 }
3452
3453 /// Is the keyboard focus inside a widget that edits text?
3454 ///
3455 /// The cheap half of [`focused_text_surface`](Self::focused_text_surface),
3456 /// for a host that only needs to decide whether to step aside.
3457 pub fn focused_is_text_surface(&self) -> bool {
3458 self.text_surfaces.focused_is_text_surface()
3459 }
3460
3461 pub(crate) fn push_action(&mut self, widget_id: WidgetId, action: crate::action::Action) {
3462 if let Some(node) = self.arena.get_mut(widget_id) {
3463 node.actions.push(action);
3464 }
3465 }
3466
3467 /// Telemetry dispatch tap. Looks up a registered
3468 /// [`crate::telemetry::TelemetryContext`] in `app_state` and emits
3469 /// an `intent.dispatched` event with the intent's name. No-op when
3470 /// no telemetry is configured. Errors and consent gating are
3471 /// handled inside the reporter — this site only needs to call
3472 /// `record`.
3473 fn tap_intent_dispatched(&self, intent: &crate::intent::Intent) {
3474 let Some(tcx) = self
3475 .app_context()
3476 .app_state::<crate::telemetry::TelemetryContext>()
3477 else {
3478 return;
3479 };
3480 let install_id = tcx.reporter.install_id();
3481 let props = [
3482 crate::telemetry::Prop {
3483 key: "name",
3484 value: crate::telemetry::PropValue::StaticStr(intent.name),
3485 },
3486 crate::telemetry::Prop {
3487 key: "source",
3488 value: crate::telemetry::PropValue::Enum {
3489 variant: intent.source.as_str(),
3490 },
3491 },
3492 ];
3493 let event = crate::telemetry::Event {
3494 name: "intent.dispatched",
3495 category: crate::telemetry::EventCategory::Intent,
3496 timestamp: std::time::SystemTime::now(),
3497 install_id,
3498 session_id: &tcx.session_id,
3499 schema_version: tcx.schema_version,
3500 props: &props,
3501 };
3502 tcx.reporter.record(&event);
3503 }
3504
3505 /// Histogram of widget concrete-type names across the active
3506 /// arena. Used by the `widget.census` telemetry emitter to surface
3507 /// "which widgets does this app actually use" data back to the
3508 /// framework. Keyed by
3509 /// `std::any::type_name::<T>()` of the concrete widget — a
3510 /// dotted, fully-qualified path like
3511 /// `teksilo_widgets::button::Button`.
3512 ///
3513 /// `&'static str` keys: `type_name_of_val` returns a
3514 /// compile-time string, so the histogram preserves the static
3515 /// lifetime all the way to the wire-format prop. This avoids
3516 /// any allocation for the type-name strings themselves.
3517 ///
3518 /// Cost: one `Box<dyn Widget>` indirection per active node plus
3519 /// a `HashMap` insert. Sub-millisecond on arenas with thousands
3520 /// of widgets. Safe to call every frame in tests; in production
3521 /// gate behind a periodic ticker (hourly or on-idle).
3522 pub fn widget_type_histogram(&self) -> std::collections::HashMap<&'static str, u32> {
3523 let mut out = std::collections::HashMap::<&'static str, u32>::new();
3524 for id in self.arena.active_ids_iter() {
3525 if let Some(node) = self.arena.get(id) {
3526 // `Widget::type_name` is monomorphized per impl, so
3527 // calling through the vtable correctly resolves to
3528 // the concrete type — `type_name_of_val(&*widget)`
3529 // alone would collapse to `"dyn teksilo_core::widget::Widget"`.
3530 let name: &'static str = node.widget.type_name();
3531 *out.entry(name).or_insert(0) += 1;
3532 }
3533 }
3534 out
3535 }
3536
3537 /// Number of active widgets in the arena. Cheap; matches the
3538 /// totals returned by `widget_type_histogram` when summed.
3539 pub fn active_widget_count(&self) -> usize {
3540 self.arena.active_ids_iter().count()
3541 }
3542
3543 /// Enqueue an intent for dispatch from `source`. Called from
3544 /// `collect_from_ctx` after a handler runs `ctx.send_intent(...)`
3545 /// and from the KeyDown shortcut-interception path.
3546 pub(crate) fn enqueue_intent(
3547 &mut self,
3548 source: WidgetId,
3549 intent: crate::intent::Intent,
3550 propagate_when_disabled: bool,
3551 ) {
3552 self.pending_intents
3553 .push((source, intent, propagate_when_disabled));
3554 }
3555
3556 /// Dispatch every queued intent. Handlers may call
3557 /// `ctx.send_intent(...)` to enqueue more; the loop consumes
3558 /// those too until the queue drains. No ordering guarantee
3559 /// beyond "first-enqueued is first-dispatched"; the `pop` path
3560 /// uses `remove(0)` to keep that FIFO behavior.
3561 pub(crate) fn drain_pending_intents(&mut self, ops: &mut dyn crate::window::WindowOps) {
3562 while !self.pending_intents.is_empty() {
3563 let (source, intent, propagate) = self.pending_intents.remove(0);
3564 self.dispatch_intent(source, intent, propagate, &mut *ops);
3565 }
3566 }
3567
3568 /// Walk `source → root` invoking any [`Action`](crate::action::Action)
3569 /// whose `intent` name matches. The first enabled, `Handled`
3570 /// response stops the walk. A `Propagated` or disabled action
3571 /// (when the shortcut's `propagate_when_disabled` is true) lets
3572 /// the walk continue. A disabled action with
3573 /// `propagate_when_disabled == false` consumes the intent at that
3574 /// level without invoking a handler.
3575 pub(crate) fn dispatch_intent(
3576 &mut self,
3577 source: WidgetId,
3578 intent: crate::intent::Intent,
3579 propagate_when_disabled: bool,
3580 ops: &mut dyn crate::window::WindowOps,
3581 ) {
3582 // Telemetry tap. Single insertion point catches every intent
3583 // — shortcut-driven, programmatic via `send_intent`, etc. —
3584 // because every dispatch funnels through here. A no-op when
3585 // no `TelemetryContext` is registered.
3586 self.tap_intent_dispatched(&intent);
3587
3588 // Pre-compute the source → root chain so the walk doesn't
3589 // need to hold any arena borrow while invoking handlers.
3590 let chain: Vec<WidgetId> = {
3591 let mut v = vec![source];
3592 let mut current = self.arena.parent(source);
3593 while let Some(id) = current {
3594 v.push(id);
3595 current = self.arena.parent(id);
3596 }
3597 v
3598 };
3599
3600 for id in chain {
3601 if !self.arena.is_active(id) || !self.arena.is_enabled(id) {
3602 continue;
3603 }
3604
3605 // Take out the first matching action by intent name so
3606 // we can invoke its FnMut handler without holding an
3607 // arena-wide borrow. The action is reinserted at its
3608 // original position so declaration order is preserved
3609 // for any follow-on dispatch.
3610 let Some((mut action, idx, enabled)) = self.arena.get_mut(id).and_then(|node| {
3611 let idx = node.actions.iter().position(|a| a.intent == intent.name)?;
3612 let enabled = node.actions[idx].is_enabled();
3613 Some((node.actions.remove(idx), idx, enabled))
3614 }) else {
3615 continue;
3616 };
3617
3618 if !enabled {
3619 // Return the action untouched.
3620 if let Some(node) = self.arena.get_mut(id) {
3621 node.actions.insert(idx, action);
3622 }
3623 if propagate_when_disabled {
3624 continue;
3625 }
3626 return;
3627 }
3628
3629 let mut ctx = self.make_event_context(&mut *ops);
3630 let response = (action.handler)(&intent, &mut ctx);
3631 if let Some(node) = self.arena.get_mut(id) {
3632 node.actions.insert(idx, action);
3633 }
3634 self.collect_from_ctx(ctx, id);
3635
3636 match response {
3637 crate::intent::IntentResponse::Handled => return,
3638 crate::intent::IntentResponse::Propagated => continue,
3639 }
3640 }
3641
3642 // Fallback: window-global actions (registered via
3643 // `register_action_global`). The source→root walk found no consuming
3644 // node action, so consult app-global commands — reachable regardless of
3645 // where the intent originated (menu-bar overlay, content, shortcut).
3646 let mut i = 0;
3647 while i < self.global_actions.len() {
3648 let matches = {
3649 let (_, action) = &self.global_actions[i];
3650 action.intent == intent.name && action.is_enabled()
3651 };
3652 if !matches {
3653 i += 1;
3654 continue;
3655 }
3656 // Take the action out so the FnMut handler can run without holding a
3657 // borrow on `self`; reinsert at its slot afterwards.
3658 let (owner, mut action) = self.global_actions.remove(i);
3659 let mut ctx = self.make_event_context(&mut *ops);
3660 let response = (action.handler)(&intent, &mut ctx);
3661 self.global_actions.insert(i, (owner, action));
3662 self.collect_from_ctx(ctx, owner);
3663 match response {
3664 crate::intent::IntentResponse::Handled => return,
3665 crate::intent::IntentResponse::Propagated => {
3666 i += 1;
3667 continue;
3668 }
3669 }
3670 }
3671 }
3672
3673 /// Register a window-global [`Action`](crate::action::Action) owned by
3674 /// `owner`. Consulted as a dispatch fallback (see [`Self::dispatch_intent`]);
3675 /// torn down when `owner` rebuilds or is destroyed. Backs
3676 /// [`BuildContext::register_action_global`](crate::BuildContext::register_action_global).
3677 pub(crate) fn push_global_action(&mut self, owner: WidgetId, action: crate::action::Action) {
3678 self.global_actions.push((owner, action));
3679 }
3680
3681 // --- Window-close request (drained by the app loop) ---
3682
3683 /// Drain the "close this window" flag set by
3684 /// [`EventContext::close_window`] during dispatch. A *guarded* close
3685 /// — the app routes it through the window's close guard.
3686 pub fn take_close_window_request(&mut self) -> bool {
3687 std::mem::replace(&mut self.close_window_requested, false)
3688 }
3689
3690 /// Drain the "close this window, no questions asked" flag set by
3691 /// [`EventContext::close_window_forced`] during dispatch. An
3692 /// *unconditional* close that bypasses the window's close guard.
3693 pub fn take_force_close_request(&mut self) -> bool {
3694 std::mem::replace(&mut self.force_close_requested, false)
3695 }
3696
3697 /// Drain the pending locale switch raised by
3698 /// [`EventContext::set_locale`] during dispatch. The app layer
3699 /// (`WindowManager::drain_pending_locale_requests`) parses the
3700 /// result and routes it through `WindowManager::set_locale` so the
3701 /// `I18nManager`'s active locale, version signal, and layout
3702 /// direction all stay in sync with the tree.
3703 pub fn take_pending_locale_request(&mut self) -> Option<String> {
3704 self.pending_locale_request.take()
3705 }
3706
3707 /// Drain the pending theme switch raised by
3708 /// [`EventContext::set_theme`] during dispatch. The app layer
3709 /// (`WindowManager::drain_pending_theme_requests`) routes it through
3710 /// `WindowManager::set_theme` so the new theme is applied to every
3711 /// window, not just the one whose handler requested it.
3712 pub fn take_pending_theme_request(&mut self) -> Option<crate::styles::Theme> {
3713 self.pending_theme_request.take()
3714 }
3715
3716 /// Drain the pending "follow OS theme" request raised by
3717 /// [`EventContext::follow_system_theme`] during dispatch. The app layer
3718 /// (`WindowManager::drain_pending_follow_system_requests`) switches to
3719 /// `ThemeMode::Native` and recomputes the theme from the OS for every
3720 /// window. Returns `true` if a request was pending.
3721 pub fn take_pending_follow_system_request(&mut self) -> bool {
3722 std::mem::take(&mut self.pending_follow_system_request)
3723 }
3724
3725 /// Drain the pending text-scale change raised by
3726 /// [`EventContext::set_text_scale`] during dispatch. The app layer
3727 /// (`WindowManager::drain_pending_text_scale_requests`) routes it through
3728 /// `WindowManager::set_text_scale` so the new factor is applied to every
3729 /// window, not just the one whose handler requested it.
3730 pub fn take_pending_text_scale_request(&mut self) -> Option<f32> {
3731 self.pending_text_scale_request.take()
3732 }
3733
3734 /// Drain all pending modal requests recorded during event handling.
3735 ///
3736 /// Each request includes the originating widget so higher layers can
3737 /// resolve routing and focus behavior relative to the source tree.
3738 pub fn drain_pending_modal_requests(&mut self) -> Vec<crate::modal::QueuedModalRequest> {
3739 std::mem::take(&mut self.pending_modal_requests)
3740 }
3741
3742 /// Drain whether the current native modal window should be dismissed.
3743 pub fn drain_pending_modal_dismissal(&mut self) -> bool {
3744 std::mem::replace(&mut self.pending_modal_dismissal, false)
3745 }
3746
3747 // --- Widget insertion ---
3748
3749 /// Walk `Widget::declare_shortcuts` for an already-inserted widget
3750 /// and register every returned shortcut with the registry, owned
3751 /// by `id`. Called at insertion AND at rebuild so the declared
3752 /// metadata survives across rebuilds (which `unregister_all_for_owner`
3753 /// would otherwise wipe). Build-time `ctx.register_shortcut` calls
3754 /// upsert handlers on top; the registry is idempotent on id.
3755 pub(crate) fn apply_declared_shortcuts(&mut self, id: WidgetId) {
3756 let declared = self
3757 .arena
3758 .get(id)
3759 .map(|n| n.widget.declare_shortcuts())
3760 .unwrap_or_default();
3761 for shortcut in declared {
3762 self.shortcut_registry.register_owned(shortcut, id);
3763 }
3764 }
3765
3766 /// Internal: insert a widget, call build(), wire children, register clips.
3767 fn insert_widget(&mut self, widget: Box<dyn Widget>) -> WidgetId {
3768 let id = self.arena.insert(widget);
3769
3770 {
3771 if let Some(mut widget_box) = self.arena.take_widget(id) {
3772 if let Some(handler_set) = widget_box.take_handler_set() {
3773 self.arena.restore_widget(id, widget_box);
3774 if let Some(node) = self.arena.get_mut(id) {
3775 // Handlers attached at the widget's creation site
3776 // are external from its own perspective — keep
3777 // them out of the rebuild-cleared `handlers`
3778 // slot so they survive data-driven rebuilds.
3779 node.external_handlers = handler_set.handlers;
3780 node.node_focusable = handler_set.focusable;
3781 node.node_tab_index = handler_set.tab_index;
3782 node.node_cursor = handler_set.cursor;
3783 // `clips_children` and `event_pass_through` are
3784 // node-level flags on `WidgetNode` — they must
3785 // be mirrored here too. Without this an
3786 // `Inner::new().event_pass_through(true)` chain
3787 // silently no-ops (the flag stays at default
3788 // `false`), and any widget wrapped with it
3789 // catches every pointer event in its bounds.
3790 if let Some(clips) = handler_set.clips_children {
3791 node.clips_children = clips;
3792 }
3793 if let Some(pass_through) = handler_set.event_pass_through {
3794 node.event_pass_through = pass_through;
3795 }
3796 if let Some(dead_zone) = handler_set.gesture_dead_zone {
3797 node.gesture_dead_zone = dead_zone;
3798 }
3799 if let Some(role) = handler_set.long_press_role {
3800 node.long_press_role = role;
3801 }
3802 if let Some(action) = handler_set.touch_action {
3803 node.touch_action = action;
3804 }
3805 if let Some(claim) = handler_set.pan_claim {
3806 node.pan_claim = Some(claim);
3807 }
3808 if let Some(behavior) = handler_set.overscroll_behavior {
3809 node.overscroll_behavior = behavior;
3810 }
3811 if let Some(activation) = handler_set.drag_activation {
3812 node.drag_activation = activation;
3813 }
3814 if let Some(policy) = handler_set.multi_contact {
3815 node.multi_contact = policy;
3816 }
3817 if let Some(keyboard_capture) = handler_set.keyboard_capture {
3818 node.keyboard_capture = keyboard_capture;
3819 }
3820 if let Some(hit_transparent) = handler_set.hit_transparent {
3821 node.hit_transparent = hit_transparent;
3822 }
3823 if let Some(slop) = handler_set.hit_slop {
3824 node.hit_slop = Some(slop);
3825 }
3826 if let Some(no_slop) = handler_set.no_hit_slop {
3827 node.no_hit_slop = no_slop;
3828 }
3829 if handler_set.context_menu_factory.is_some() {
3830 node.context_menu_factory = handler_set.context_menu_factory;
3831 }
3832 if let Some(sig) = handler_set.focus_within {
3833 node.focus_within_signal = Some(sig);
3834 }
3835 if let Some(sig) = handler_set.hover_within {
3836 node.hover_within_signal = Some(sig);
3837 }
3838 // Builder-chained `visible_when: prop`. Mirror of
3839 // `WidgetTree::visible_when`: register a bound prop at
3840 // Relayout, then store it on the node. (Disjoint field
3841 // borrow, like `access_hidden` below.)
3842 if let Some(prop) = handler_set.visible_when {
3843 prop.register_if_bound(
3844 id,
3845 &self.binding_registry,
3846 crate::binding::BindingLevel::Relayout,
3847 );
3848 node.visible_state = Some(prop);
3849 }
3850 // Builder-level accessibility overrides + subtree
3851 // mode. Mirrored here because this insertion path
3852 // bypasses `apply_handler_set`.
3853 if handler_set.access.is_some() {
3854 // Register any bound access_hidden/label/description/
3855 // value Props at AccessibilityOnly so the AT tree
3856 // re-walks when they flip. (Disjoint field borrow:
3857 // `node` borrows `self.arena`, this reads
3858 // `self.binding_registry`.)
3859 if let Some(access) = handler_set.access.as_ref() {
3860 Self::register_access_prop_bindings(
3861 access,
3862 id,
3863 &self.binding_registry,
3864 );
3865 }
3866 // Merged, not assigned: a node can already carry a
3867 // block from its builder chain, and replacing it
3868 // drops everything in it (see
3869 // `AccessibilityOverrides::merge_from`).
3870 match (&mut node.access_overrides, handler_set.access) {
3871 (Some(existing), Some(incoming)) => existing.merge_from(*incoming),
3872 (slot, incoming) => *slot = incoming,
3873 }
3874 }
3875 if let Some(mode) = handler_set.access_subtree {
3876 node.access_subtree = mode;
3877 }
3878 }
3879 } else {
3880 self.arena.restore_widget(id, widget_box);
3881 }
3882 }
3883 }
3884
3885 // Walk Widget::declare_shortcuts before build() so the
3886 // declared metadata lands in the registry first; if build()
3887 // also registers the same id with a real on_activate, the
3888 // registry upserts (preserving any user override).
3889 self.apply_declared_shortcuts(id);
3890
3891 {
3892 let mut widget_box = match self.arena.take_widget(id) {
3893 Some(widget) => widget,
3894 None => return id,
3895 };
3896 let mut build_ctx = crate::build_context::BuildContext {
3897 tree: self,
3898 composite_id: Some(id),
3899 effect_handles: Vec::new(),
3900 subscription_handles: Vec::new(),
3901 // A first mount has no previous build to inherit ids from.
3902 reusable_sub_ids: Vec::new(),
3903 };
3904 let built_children = widget_box.build(&mut build_ctx);
3905 let effect_handles = std::mem::take(&mut build_ctx.effect_handles);
3906 let subscription_handles = std::mem::take(&mut build_ctx.subscription_handles);
3907
3908 self.arena.restore_widget(id, widget_box);
3909
3910 // Transfer per-widget handles to the node. Both lists are
3911 // stored unconditionally — a leaf widget that registers an
3912 // effect in its build() still needs its ObserverHandle to
3913 // persist (otherwise the effect unregisters the moment
3914 // BuildContext drops).
3915 if let Some(node) = self.arena.get_mut(id) {
3916 node.subscription_handles = subscription_handles;
3917 node.effect_handles = effect_handles;
3918 }
3919
3920 if !built_children.is_empty() {
3921 for &child_id in &built_children {
3922 if let Some(child_node) = self.arena.get_mut(child_id) {
3923 child_node.parent = Some(id);
3924 }
3925 }
3926 if let Some(node) = self.arena.get_mut(id) {
3927 node.children = built_children;
3928 }
3929 }
3930 }
3931
3932 let clips = self
3933 .arena
3934 .get(id)
3935 .is_some_and(|node| node.widget.clips_children());
3936 if clips {
3937 self.arena.set_clips_children(id, true);
3938 }
3939
3940 id
3941 }
3942
3943 /// Add a widget to the tree.
3944 pub fn add(&mut self, widget: impl Widget + 'static) -> WidgetId {
3945 self.insert_widget(Box::new(widget))
3946 }
3947
3948 /// Add a pre-boxed widget to the tree.
3949 pub fn add_boxed(&mut self, widget: Box<dyn Widget>) -> WidgetId {
3950 self.insert_widget(widget)
3951 }
3952
3953 /// The widget that paints `id`'s title, when it has one.
3954 ///
3955 /// See [`Widget::accessible_title_node`].
3956 pub fn widget_accessible_title_node(&self, id: WidgetId) -> Option<WidgetId> {
3957 self.arena.get(id)?.widget.accessible_title_node()
3958 }
3959
3960 /// Add a widget as a child of another widget.
3961 pub fn add_child(&mut self, parent: WidgetId, widget: impl Widget + 'static) -> WidgetId {
3962 let boxed: Box<dyn Widget> = Box::new(widget);
3963
3964 let id = self.arena.insert_child(parent, boxed);
3965
3966 {
3967 if let Some(mut widget_box) = self.arena.take_widget(id) {
3968 if let Some(handler_set) = widget_box.take_handler_set() {
3969 self.arena.restore_widget(id, widget_box);
3970 if let Some(node) = self.arena.get_mut(id) {
3971 // Creation-site handlers are external (persist
3972 // across the widget's own rebuilds) — see the
3973 // matching block in `insert_widget`.
3974 node.external_handlers = handler_set.handlers;
3975 node.node_focusable = handler_set.focusable;
3976 node.node_tab_index = handler_set.tab_index;
3977 node.node_cursor = handler_set.cursor;
3978 if let Some(clips) = handler_set.clips_children {
3979 node.clips_children = clips;
3980 }
3981 if let Some(pass_through) = handler_set.event_pass_through {
3982 node.event_pass_through = pass_through;
3983 }
3984 if let Some(dead_zone) = handler_set.gesture_dead_zone {
3985 node.gesture_dead_zone = dead_zone;
3986 }
3987 if let Some(role) = handler_set.long_press_role {
3988 node.long_press_role = role;
3989 }
3990 if let Some(action) = handler_set.touch_action {
3991 node.touch_action = action;
3992 }
3993 if let Some(claim) = handler_set.pan_claim {
3994 node.pan_claim = Some(claim);
3995 }
3996 if let Some(behavior) = handler_set.overscroll_behavior {
3997 node.overscroll_behavior = behavior;
3998 }
3999 if let Some(activation) = handler_set.drag_activation {
4000 node.drag_activation = activation;
4001 }
4002 if let Some(policy) = handler_set.multi_contact {
4003 node.multi_contact = policy;
4004 }
4005 if let Some(keyboard_capture) = handler_set.keyboard_capture {
4006 node.keyboard_capture = keyboard_capture;
4007 }
4008 if let Some(hit_transparent) = handler_set.hit_transparent {
4009 node.hit_transparent = hit_transparent;
4010 }
4011 if let Some(slop) = handler_set.hit_slop {
4012 node.hit_slop = Some(slop);
4013 }
4014 if let Some(no_slop) = handler_set.no_hit_slop {
4015 node.no_hit_slop = no_slop;
4016 }
4017 if handler_set.context_menu_factory.is_some() {
4018 node.context_menu_factory = handler_set.context_menu_factory;
4019 }
4020 if let Some(sig) = handler_set.focus_within {
4021 node.focus_within_signal = Some(sig);
4022 }
4023 if let Some(sig) = handler_set.hover_within {
4024 node.hover_within_signal = Some(sig);
4025 }
4026 // Builder-chained `visible_when: prop`. Same as in
4027 // `insert_widget`.
4028 if let Some(prop) = handler_set.visible_when {
4029 prop.register_if_bound(
4030 id,
4031 &self.binding_registry,
4032 crate::binding::BindingLevel::Relayout,
4033 );
4034 node.visible_state = Some(prop);
4035 }
4036 // Builder-level accessibility overrides + subtree
4037 // mode. Same rationale as in `insert_widget`.
4038 if handler_set.access.is_some() {
4039 // Register any bound access_hidden/label/description/
4040 // value Props at AccessibilityOnly so the AT tree
4041 // re-walks when they flip. (Disjoint field borrow:
4042 // `node` borrows `self.arena`, this reads
4043 // `self.binding_registry`.)
4044 if let Some(access) = handler_set.access.as_ref() {
4045 Self::register_access_prop_bindings(
4046 access,
4047 id,
4048 &self.binding_registry,
4049 );
4050 }
4051 // Merged, not assigned: a node can already carry a
4052 // block from its builder chain, and replacing it
4053 // drops everything in it (see
4054 // `AccessibilityOverrides::merge_from`).
4055 match (&mut node.access_overrides, handler_set.access) {
4056 (Some(existing), Some(incoming)) => existing.merge_from(*incoming),
4057 (slot, incoming) => *slot = incoming,
4058 }
4059 }
4060 if let Some(mode) = handler_set.access_subtree {
4061 node.access_subtree = mode;
4062 }
4063 }
4064 } else {
4065 self.arena.restore_widget(id, widget_box);
4066 }
4067 }
4068 }
4069
4070 // Same shortcut-declaration walk as `insert_widget` — keeps
4071 // metadata visible from the moment the child mounts, before
4072 // build() runs.
4073 self.apply_declared_shortcuts(id);
4074
4075 {
4076 if let Some(mut widget_box) = self.arena.take_widget(id) {
4077 let mut build_ctx = crate::build_context::BuildContext {
4078 tree: self,
4079 composite_id: Some(id),
4080 effect_handles: Vec::new(),
4081 subscription_handles: Vec::new(),
4082 // A first mount has no previous build to inherit ids from.
4083 reusable_sub_ids: Vec::new(),
4084 };
4085 let built_children = widget_box.build(&mut build_ctx);
4086 let effect_handles = std::mem::take(&mut build_ctx.effect_handles);
4087 let subscription_handles = std::mem::take(&mut build_ctx.subscription_handles);
4088
4089 self.arena.restore_widget(id, widget_box);
4090
4091 // Transfer per-widget handles to the node. See the
4092 // matching block in `insert_widget` — effect and
4093 // subscription handles must persist for leaf widgets
4094 // too, not only composite ones.
4095 if let Some(node) = self.arena.get_mut(id) {
4096 node.subscription_handles = subscription_handles;
4097 node.effect_handles = effect_handles;
4098 }
4099
4100 if !built_children.is_empty() {
4101 for &child_id in &built_children {
4102 if let Some(child_node) = self.arena.get_mut(child_id) {
4103 child_node.parent = Some(id);
4104 }
4105 }
4106 if let Some(node) = self.arena.get_mut(id) {
4107 node.children = built_children;
4108 }
4109 }
4110 }
4111 }
4112
4113 let clips = self
4114 .arena
4115 .get(id)
4116 .is_some_and(|node| node.widget.clips_children());
4117 if clips {
4118 self.arena.set_clips_children(id, true);
4119 }
4120
4121 id
4122 }
4123
4124 // --- Property bindings ---
4125
4126 /// Bind a widget's visibility to a boolean prop.
4127 /// When false, the widget is set dormant; when true, it is activated.
4128 /// Accepts `Signal<bool>`, `Prop<bool>`, or plain `bool`.
4129 pub fn visible_when(&mut self, id: WidgetId, state: impl Into<crate::signal::Prop<bool>>) {
4130 let prop = state.into();
4131 prop.register_if_bound(
4132 id,
4133 &self.binding_registry,
4134 crate::binding::BindingLevel::Relayout,
4135 );
4136 if let Some(node) = self.arena.get_mut(id) {
4137 node.visible_state = Some(prop);
4138 }
4139 }
4140
4141 /// Install (or reuse) the activation signal on a node and return a
4142 /// handle to it. The framework sets it to `false` when the node is
4143 /// parked dormant (`Switcher` / `visible_when`) and `true` when it is
4144 /// re-activated — see [`crate::arena::WidgetArena::set_dormant`] /
4145 /// [`activate`](crate::arena::WidgetArena::activate). The returned
4146 /// signal is initialised to the node's current active state. Used by
4147 /// widgets owning a resource outside the paint pass (a native subview)
4148 /// that must hide/show it in lockstep with framework activation.
4149 pub fn activation_signal(&mut self, id: WidgetId) -> crate::signal::Signal<bool> {
4150 if let Some(node) = self.arena.get_mut(id) {
4151 if let Some(existing) = node.activation_signal.clone() {
4152 return existing;
4153 }
4154 let active = node.activation == crate::arena::ActivationState::Active;
4155 let sig = crate::signal::Signal::new(active);
4156 node.activation_signal = Some(sig.clone());
4157 sig
4158 } else {
4159 // Node missing (shouldn't happen in build) — hand back a
4160 // detached signal so the caller still gets a valid handle.
4161 crate::signal::Signal::new(true)
4162 }
4163 }
4164
4165 // -----------------------------------------------------------------
4166 // In-node target geometry
4167 // -----------------------------------------------------------------
4168
4169 /// The interactive sub-regions the widget at `id` paints inside its own
4170 /// single node, in absolute arena coordinates.
4171 ///
4172 /// The read side of [`Widget::target_regions`]:
4173 /// a scroll bar's thumb, a slider's knob, a header cell's filter
4174 /// affordance. Empty for the overwhelming majority of widgets, whose node
4175 /// *is* their target and which therefore have nothing to add.
4176 ///
4177 /// Reporting only — reading this changes nothing. It exists so a
4178 /// conformance audit, and a test of one, can see geometry that no layout
4179 /// ever produced.
4180 pub fn widget_target_regions(&self, id: WidgetId) -> Vec<crate::partition::TargetRegion> {
4181 let Some(node) = self.arena.get(id) else {
4182 return Vec::new();
4183 };
4184 node.widget.target_regions(self.arena.bounds(id))
4185 }
4186
4187 /// The hit outset the **mounted** widget at `id` declares for `kind`,
4188 /// against the tree's live input tokens.
4189 ///
4190 /// The read side of [`Widget::hit_outset`], and the companion of
4191 /// [`widget_target_regions`](Self::widget_target_regions): both let a
4192 /// conformance audit — and a test of one — see target geometry that no
4193 /// layout ever produced.
4194 ///
4195 /// It has to read the mounted node rather than a freshly-built widget,
4196 /// because an outset is usually derived from what the widget *painted*,
4197 /// and an unmounted one has painted nothing. That is also what makes the
4198 /// **gates** assertable: a decorative avatar, an inert twist arrow, a
4199 /// disabled swatch and a breadcrumb's current crumb all take no press, so
4200 /// each must declare `EdgeInsets::ZERO` — a widened node that then refuses
4201 /// the press is a hole punched in whatever is behind it.
4202 ///
4203 /// The tokens are the **effective** theme's, not `theme`'s, because that
4204 /// is what the hit path itself reads:
4205 /// `hit_test_for_excluding` builds its `HitContext` from
4206 /// `effective_theme.input`, as do the pointer profile and the touch-enabled
4207 /// gate in `pointer_state.rs`. The two themes agree only for as long as
4208 /// nothing between them touches `input` — `recompute_effective_theme`
4209 /// currently projects typography alone — and an accessor that describes a
4210 /// path has to read that path's source rather than one that happens to
4211 /// match it.
4212 ///
4213 /// Reporting only — reading this changes nothing.
4214 pub fn widget_hit_outset(
4215 &self,
4216 id: WidgetId,
4217 kind: teksilo_tokens::PointerKind,
4218 ) -> teksilo_canvas::EdgeInsets {
4219 let Some(node) = self.arena.get(id) else {
4220 return teksilo_canvas::EdgeInsets::ZERO;
4221 };
4222 node.widget.hit_outset(kind, &self.effective_theme.input)
4223 }
4224
4225 // -----------------------------------------------------------------
4226 // Press state
4227 // -----------------------------------------------------------------
4228
4229 /// Install (or reuse) the framework press signal on a node and return a
4230 /// handle to it.
4231 ///
4232 /// `true` while the node holds a pointer press whose visual is showing:
4233 /// between press and release, `false` once the pointer leaves the press's
4234 /// tap boundary and `true` again on re-entry, cleared on a cancel or when
4235 /// a peer wins the arbitration. See `docs/touch-and-pen.md` §7.
4236 pub fn pressed_signal(&mut self, id: WidgetId) -> crate::signal::Signal<bool> {
4237 let showing = self.is_pressed(id);
4238 let Some(node) = self.arena.get_mut(id) else {
4239 // Node missing (should not happen during build) — hand back a
4240 // detached signal so the caller still gets a valid handle.
4241 return crate::signal::Signal::new(false);
4242 };
4243 if let Some(existing) = node.pressed_signal.clone() {
4244 return existing;
4245 }
4246 let sig = crate::signal::Signal::new(showing);
4247 node.pressed_signal = Some(sig.clone());
4248 sig
4249 }
4250
4251 /// The press held by the pointer being dispatched, as `(inside, pending)`,
4252 /// for [`EventContext`]'s per-dispatch
4253 /// snapshot. `None` when that pointer holds no press.
4254 pub(crate) fn current_press_snapshot(&self) -> Option<(bool, bool)> {
4255 self.presses
4256 .get(self.current_pointer_id())
4257 .map(|p| (p.inside, p.pending()))
4258 }
4259
4260 /// The contact holding `id`'s press, whether or not its visual is showing.
4261 ///
4262 /// `None` for a node nothing is pressing. A node held by a finger whose
4263 /// press-feedback delay has not elapsed still answers with that finger:
4264 /// the press is real, only its visual is waiting.
4265 pub fn pressed_by(&self, id: WidgetId) -> Option<crate::pointer::PointerId> {
4266 self.presses.owner_of(id)
4267 }
4268
4269 /// Whether `id`'s press visual is showing — held, inside its tap boundary,
4270 /// and past any press-feedback delay. What the node's
4271 /// [`pressed_signal`](Self::pressed_signal) mirrors.
4272 pub fn is_pressed(&self, id: WidgetId) -> bool {
4273 self.presses
4274 .for_node(id)
4275 .is_some_and(crate::press::Press::showing)
4276 }
4277
4278 /// Whether `id` is held and the pointer has not left the press's tap
4279 /// boundary. True during a press-feedback delay, unlike
4280 /// [`is_pressed`](Self::is_pressed).
4281 pub fn press_is_inside(&self, id: WidgetId) -> bool {
4282 self.presses.for_node(id).is_some_and(|p| p.inside)
4283 }
4284
4285 /// Whether `id` is held but its press-feedback delay has not elapsed, so
4286 /// the visual is deliberately withheld.
4287 pub fn press_pending(&self, id: WidgetId) -> bool {
4288 self.presses
4289 .for_node(id)
4290 .is_some_and(crate::press::Press::pending)
4291 }
4292
4293 /// Publish `id`'s press signal from the table. The one place a press
4294 /// signal is written, so "the table changed" and "the recipe was told"
4295 /// cannot drift apart.
4296 pub(crate) fn publish_pressed(&mut self, id: WidgetId) {
4297 let showing = self.is_pressed(id);
4298 if let Some(node) = self.arena.get(id)
4299 && let Some(sig) = node.pressed_signal.clone()
4300 && sig.get() != showing
4301 {
4302 sig.set(showing);
4303 }
4304 }
4305
4306 /// Fire the `activation_signal` of every node that transitioned
4307 /// Active↔Dormant since the last flush. Called at a well-defined tree-level
4308 /// point (the end of `process_state_changes`), never from inside the arena
4309 /// recursion — so an observer (e.g. a `WebView` calling the engine's
4310 /// `set_visible`) runs after the visibility pass has fully committed,
4311 /// matching the `focus_within` / `hover_within` update discipline.
4312 pub(crate) fn flush_activation_signals(&mut self) {
4313 let changes = self.arena.take_activation_changes();
4314 for (id, _recorded) in changes {
4315 // Re-read the node at flush time; it still exists (the transition
4316 // was recorded in the same synchronous operation).
4317 let Some(node) = self.arena.get(id) else {
4318 continue;
4319 };
4320 let Some(sig) = node.activation_signal.clone() else {
4321 continue;
4322 };
4323 // Fire the node's **current** state, not the value recorded at the
4324 // transition, and only when it differs from what observers last
4325 // saw. `pending_activation_changes` is an append-only queue: a
4326 // node parked and re-activated inside one batch records both
4327 // edges, and replaying them in order hands observers a `false`
4328 // that was never observable — the node is already Active by the
4329 // time anyone is told anything.
4330 //
4331 // The in-tree modal path does exactly that on every open: build
4332 // the content, `set_dormant` it, mount the scrim, `activate` it,
4333 // then move focus in. Both edges land in one batch and flush
4334 // *after* the focus dispatch, so the stale `false` arrives last
4335 // and observers act on a state that has already been superseded.
4336 // For a text editor that meant its dormancy handler wiped the
4337 // `has_focus` it had just been granted, and the dialog opened with
4338 // no caret; a `WebView` would have taken a real `set_visible(false)`
4339 // OS call for a subview that never left the screen.
4340 //
4341 // Collapsing to the final state also makes the flush idempotent
4342 // over duplicate ids: the first iteration syncs the signal, the
4343 // rest find it already equal and skip. `Signal::set` notifies
4344 // unconditionally, so the equality guard is what stops the
4345 // redundant fanout.
4346 let active = node.activation == crate::arena::ActivationState::Active;
4347 if sig.get() != active {
4348 sig.set(active);
4349 }
4350 }
4351 }
4352
4353 /// Bind an opacity multiplier (0..1) to a widget. The render walker
4354 /// emits `SetOpacity(value)` before painting the widget's subtree
4355 /// and `RestoreOpacity` afterwards, so the multiplier composes
4356 /// correctly with ancestor opacity scopes via the canvas's stacked
4357 /// opacity model. Bound at `Repaint` level: opacity changes never
4358 /// trigger relayout. Pass any `Prop<f32>` or `Signal<f32>` source
4359 /// (typically an animated signal driven by a `Fade` wrapper).
4360 pub fn set_opacity(&mut self, id: WidgetId, opacity: impl Into<crate::signal::Prop<f32>>) {
4361 let prop = opacity.into();
4362 prop.register_if_bound(
4363 id,
4364 &self.binding_registry,
4365 crate::binding::BindingLevel::RepaintOnly,
4366 );
4367 if let Some(node) = self.arena.get_mut(id) {
4368 node.opacity_prop = Some(prop);
4369 }
4370 }
4371
4372 /// Bind a 2D affine transform to a widget. The render walker emits
4373 /// `PushTransform(value)` before painting the widget's subtree and
4374 /// `PopTransform` afterwards; the renderer composes the transform
4375 /// onto its stack so nested wrappers and widget-internal canvas
4376 /// transforms compose correctly. Bound at `Repaint` level: visual-
4377 /// only transforms never trigger relayout. Wrappers that want the
4378 /// transform's *value change* to also drive layout (e.g.
4379 /// `Scale::reflow(true)`) must additionally bind the *driver*
4380 /// signal to themselves at `Relayout` level — the transform prop
4381 /// itself stays at Repaint. Pass a `Transform2D`, `Signal<Transform2D>`,
4382 /// or `Prop<Transform2D>`.
4383 pub fn set_transform(
4384 &mut self,
4385 id: WidgetId,
4386 transform: impl Into<crate::signal::Prop<teksilo_canvas::Transform2D>>,
4387 ) {
4388 let prop = transform.into();
4389 prop.register_if_bound(
4390 id,
4391 &self.binding_registry,
4392 crate::binding::BindingLevel::RepaintOnly,
4393 );
4394 if let Some(node) = self.arena.get_mut(id) {
4395 node.transform_prop = Some(prop);
4396 // A plain transform is a *self* transform — clear any prior
4397 // content-transform marker so the flag can never go stale if a
4398 // node switches from `set_content_transform` to `set_transform`.
4399 node.content_transform = false;
4400 }
4401 }
4402
4403 /// Like [`set_transform`](Self::set_transform), but marks the transform as
4404 /// a **content** transform: it positions the node's content within a fixed
4405 /// parent-space viewport (the node's bounds) rather than transforming the
4406 /// node itself. Hit-testing then keeps the whole viewport interactive at
4407 /// any pan / zoom. Used by `SceneView`; see
4408 /// `WidgetNode::content_transform`.
4409 pub fn set_content_transform(
4410 &mut self,
4411 id: WidgetId,
4412 transform: impl Into<crate::signal::Prop<teksilo_canvas::Transform2D>>,
4413 ) {
4414 let prop = transform.into();
4415 prop.register_if_bound(
4416 id,
4417 &self.binding_registry,
4418 crate::binding::BindingLevel::RepaintOnly,
4419 );
4420 if let Some(node) = self.arena.get_mut(id) {
4421 node.transform_prop = Some(prop);
4422 node.content_transform = true;
4423 }
4424 }
4425
4426 /// Bind a Gaussian-equivalent blur radius to a widget. The render
4427 /// walker emits `BeginBlurredSubtree { bounds, radius }` before
4428 /// painting the widget's subtree and `EndBlurredSubtree` afterwards;
4429 /// the renderer redirects drawing into an intermediate texture, runs
4430 /// a dual-Kawase blur chain at the requested radius, and composites
4431 /// the blurred result back into the parent pass. Bound at `Repaint`
4432 /// level: blur radius changes never trigger relayout. Sub-perceptual
4433 /// radii (< 0.5) skip the Begin/End pair entirely so animated
4434 /// enable/disable patterns have zero per-frame cost when fully off.
4435 /// Pass any `Prop<f32>` or `Signal<f32>` source.
4436 pub fn set_blur(&mut self, id: WidgetId, radius: impl Into<crate::signal::Prop<f32>>) {
4437 let prop = radius.into();
4438 prop.register_if_bound(
4439 id,
4440 &self.binding_registry,
4441 crate::binding::BindingLevel::RepaintOnly,
4442 );
4443 if let Some(node) = self.arena.get_mut(id) {
4444 node.blur_prop = Some(prop);
4445 }
4446 }
4447
4448 /// Bind a widget's enabled state to a boolean prop or compatibility state binding.
4449 /// When false, the widget and its entire subtree ignore all events but remain
4450 /// visible. Focus traversal skips disabled subtrees and AccessKit marks their
4451 /// nodes as disabled. Accepts `Signal<bool>`, `Prop<bool>`, compatibility state
4452 /// bindings, or plain `bool`.
4453 ///
4454 /// The bound signal registers at `BindingLevel::SubtreeRepaint`: when
4455 /// it flips, the entire subtree rooted at `id` is marked for repaint
4456 /// (not relayout — geometry doesn't change). Leaves like
4457 /// `IconWidget` then re-resolve their role color
4458 /// using the new `PaintContext::effective_enabled` value, so a
4459 /// disabled subtree's icons and text dim automatically.
4460 pub fn enabled_when(&mut self, id: WidgetId, state: impl Into<crate::signal::Prop<bool>>) {
4461 let prop = state.into();
4462 // SubtreeRepaint propagates the visual dirty mark through the
4463 // disabled subtree so leaves re-resolve their role colors.
4464 prop.register_if_bound(
4465 id,
4466 &self.binding_registry,
4467 crate::binding::BindingLevel::SubtreeRepaint,
4468 );
4469 // AccessibilityOnly is orthogonal — it flips `a11y_dirty` so
4470 // AccessKit's `disabled` flag refreshes on the next a11y sync
4471 // (the accessibility walker reads `arena.is_enabled(id)`,
4472 // which is already correct via the prop, but the tree needs
4473 // to be told to rebuild).
4474 prop.register_if_bound(
4475 id,
4476 &self.binding_registry,
4477 crate::binding::BindingLevel::AccessibilityOnly,
4478 );
4479 if let Some(node) = self.arena.get_mut(id) {
4480 node.enabled_state = Some(prop);
4481 }
4482 }
4483
4484 /// Reactive view of "is this widget effectively enabled?" — the AND
4485 /// of the widget's own `enabled_state` and every ancestor's.
4486 /// [`Self::is_enabled`] is the non-reactive equivalent; this method
4487 /// gives composite widgets a `Signal<bool>` for derived state.
4488 ///
4489 /// Leaves (`IconWidget`, `TextWidget`, `RectWidget`) do NOT need this
4490 /// — they receive the resolved bool via
4491 /// [`crate::widget::PaintContext::effective_enabled`] at paint time.
4492 /// This method is for composites that want to derive cursor / custom
4493 /// paint roles / etc. reactively.
4494 ///
4495 /// Install-or-reuse, exactly like [`Self::activation_signal`]: the signal
4496 /// lives on the node and the framework refreshes it from the live arena
4497 /// once per state-change pass (`flush_effective_enabled_signals`).
4498 ///
4499 /// It is deliberately NOT a signal derived by walking the ancestor chain
4500 /// here. A widget's `parent` is still `None` while its own `build()` runs
4501 /// — `insert_widget` inserts the node parentless and wires the parent link
4502 /// only after `build()` returns — so an ancestor walk performed from
4503 /// inside `build()` (which is how every caller uses this) sees an empty
4504 /// chain and would capture the widget's OWN `enabled` prop as the whole
4505 /// answer, permanently. That was a real bug: a Button inside a disabled
4506 /// form stayed painted as if enabled.
4507 ///
4508 /// The value is seeded from the live arena and corrected on the next
4509 /// flush, so a first-`build()` caller (parent not yet wired) and a
4510 /// rebuild caller (parent wired) both converge before anything paints.
4511 pub fn effective_enabled_signal(&mut self, id: WidgetId) -> crate::signal::Signal<bool> {
4512 if let Some(existing) = self
4513 .arena
4514 .get(id)
4515 .and_then(|n| n.effective_enabled_signal.clone())
4516 {
4517 return existing;
4518 }
4519 // Seed from the live tree. Mid-`build()` the parent is not wired yet,
4520 // so this is the widget's own state only; `flush_effective_enabled_signals`
4521 // corrects it against the fully-wired tree before the first paint.
4522 let seed = self.arena.is_enabled(id);
4523 let sig = crate::signal::Signal::new(seed);
4524 let Some(node) = self.arena.get_mut(id) else {
4525 // Node missing (shouldn't happen in build) — hand back a detached
4526 // handle so the caller still gets a valid signal.
4527 return crate::signal::Signal::new(true);
4528 };
4529 node.effective_enabled_signal = Some(sig.clone());
4530 self.arena.watch_effective_enabled(id);
4531 sig
4532 }
4533
4534 /// Refresh every node-resident `effective_enabled_signal` against the live
4535 /// arena, firing observers only where the value actually changed.
4536 ///
4537 /// Unlike [`Self::flush_activation_signals`] this cannot be driven off a
4538 /// change queue: a node's `enabled_state` is a `Prop<bool>` that may be
4539 /// bound to an app `Signal` which flips without the arena being notified,
4540 /// so there is no mutation site at which to record a transition. Instead
4541 /// this recomputes the (cheap, `O(depth)`) ancestor AND for each opted-in
4542 /// node and diffs. Only nodes that called
4543 /// [`Self::effective_enabled_signal`] are visited, so a tree with no
4544 /// interactive widgets pays nothing.
4545 ///
4546 /// Values are collected first and set afterwards: a `Signal::set` observer
4547 /// may mutate the tree, and must not run while the arena is being walked —
4548 /// the same discipline as `flush_activation_signals` and the
4549 /// `focus_within` / `hover_within` updates.
4550 pub(crate) fn flush_effective_enabled_signals(&mut self) {
4551 self.arena.prune_effective_enabled_watchers();
4552 let mut updates: Vec<(crate::signal::Signal<bool>, bool)> = Vec::new();
4553 for id in self.arena.effective_enabled_watchers() {
4554 let Some(sig) = self
4555 .arena
4556 .get(id)
4557 .and_then(|n| n.effective_enabled_signal.clone())
4558 else {
4559 continue;
4560 };
4561 let now = self.arena.is_enabled(id);
4562 if sig.get() != now {
4563 updates.push((sig, now));
4564 }
4565 }
4566 for (sig, value) in updates {
4567 sig.set(value);
4568 }
4569 }
4570
4571 /// Whether a widget is effectively enabled. Returns `false` if the widget
4572 /// itself or any ancestor has `enabled_state` bound to `false`.
4573 pub fn is_enabled(&self, id: WidgetId) -> bool {
4574 self.arena.is_enabled(id)
4575 }
4576
4577 /// Bind a widget's Tab-key participation to a boolean prop or
4578 /// compatibility state binding. When false, the widget is removed
4579 /// from Tab / Shift+Tab traversal (`cycle_focus`) but remains
4580 /// reachable via `request_focus` and arrow-key navigation that
4581 /// calls `request_focus`. Implements the ARIA roving-tabindex
4582 /// pattern (HTML `tabindex="-1"` semantics). Accepts
4583 /// `Signal<bool>`, `Prop<bool>`, or plain `bool`.
4584 /// Publish what a data view's `Space` should do when the row containing
4585 /// `id` holds the keyboard cursor. See
4586 /// [`WidgetNode::keyboard_toggle`](crate::arena::WidgetNode).
4587 pub fn set_keyboard_toggle(
4588 &mut self,
4589 id: WidgetId,
4590 f: std::rc::Rc<dyn Fn(&mut crate::widget::EventContext)>,
4591 ) {
4592 if let Some(node) = self.arena.get_mut(id) {
4593 node.keyboard_toggle = Some(f);
4594 }
4595 }
4596
4597 /// The first keyboard-toggle action published in `root`'s subtree, in
4598 /// traversal order.
4599 ///
4600 /// Searched per keypress rather than cached: a data view rebuilds its rows
4601 /// as they realize, so an id recorded at build time would outlive the
4602 /// widget it named.
4603 pub fn keyboard_toggle_in(
4604 &self,
4605 root: WidgetId,
4606 ) -> Option<std::rc::Rc<dyn Fn(&mut crate::widget::EventContext)>> {
4607 if let Some(f) = self.arena.get(root).and_then(|n| n.keyboard_toggle.clone()) {
4608 return Some(f);
4609 }
4610 for &child in self.arena.children(root) {
4611 if let Some(found) = self.keyboard_toggle_in(child) {
4612 return Some(found);
4613 }
4614 }
4615 None
4616 }
4617
4618 pub fn set_tab_stop(&mut self, id: WidgetId, state: impl Into<crate::signal::Prop<bool>>) {
4619 let prop = state.into();
4620 // Bind at the lightest level — tab-stop changes never affect
4621 // layout or paint; cycle_focus reads the current value on
4622 // each Tab keypress.
4623 prop.register_if_bound(
4624 id,
4625 &self.binding_registry,
4626 crate::binding::BindingLevel::RepaintOnly,
4627 );
4628 if let Some(node) = self.arena.get_mut(id) {
4629 node.tab_stop = Some(prop);
4630 }
4631 }
4632
4633 /// Current Tab-key participation for a widget. Returns the value
4634 /// of the `tab_stop` prop if bound, or `true` (the default) when
4635 /// no binding is present. Mirrors the filter used by
4636 /// `cycle_focus` — primarily for tests asserting the
4637 /// roving-tabindex contract.
4638 pub fn tab_stop(&self, id: WidgetId) -> bool {
4639 self.arena
4640 .get(id)
4641 .and_then(|node| node.tab_stop.as_ref())
4642 .map(|prop| prop.get())
4643 .unwrap_or(true)
4644 }
4645
4646 /// Declare `id` as a **traversal-scope boundary** with the given policy.
4647 /// `cycle_focus` then treats the node's subtree as an independent Tab
4648 /// group: `tab_index` values inside it are scoped (they never collide
4649 /// with sibling scopes) and `policy` governs Tab at the scope's ends.
4650 ///
4651 /// The scope node is forced non-focusable — it is a transparent boundary,
4652 /// never itself a Tab stop. Called from `BuildContext::set_traversal_scope`
4653 /// (which the `FocusScope` wrapper widget invokes during `build`), and
4654 /// directly usable from tests with no dependency on the widgets crate.
4655 pub fn set_traversal_scope(
4656 &mut self,
4657 id: WidgetId,
4658 policy: crate::focus::TraversalScopePolicy,
4659 ) {
4660 if let Some(node) = self.arena.get_mut(id) {
4661 node.node_traversal_scope = Some(policy);
4662 node.node_focusable = Some(false);
4663 }
4664 }
4665
4666 /// Remove a previously set traversal-scope marker from `id` (rebuild
4667 /// paths where a `FocusScope` is replaced by a non-scope widget). Leaves
4668 /// `node_focusable` untouched — a later handler-set application resets it.
4669 pub fn clear_traversal_scope(&mut self, id: WidgetId) {
4670 if let Some(node) = self.arena.get_mut(id) {
4671 node.node_traversal_scope = None;
4672 }
4673 }
4674
4675 /// Current traversal-scope policy on `id`, if any. For tests asserting
4676 /// the scope marker contract.
4677 pub fn traversal_scope(&self, id: WidgetId) -> Option<crate::focus::TraversalScopePolicy> {
4678 self.arena
4679 .get(id)
4680 .and_then(|node| node.node_traversal_scope)
4681 }
4682
4683 // --- Theme override ---
4684
4685 /// Set a theme override on a widget. All descendants of this widget
4686 /// will see the modified theme during layout and paint.
4687 /// The override function receives a mutable `Theme` to modify.
4688 ///
4689 /// ```
4690 /// # use teksilo_core::{Widget, LayoutResponse, LayoutContext, widget_tree::WidgetTree};
4691 /// # use teksilo_canvas::{Size, SizeProposal};
4692 /// # use teksilo_tokens::ColorTokens;
4693 /// # #[derive(Debug)] struct MinWidget;
4694 /// # impl Widget for MinWidget {
4695 /// # fn layout_response(&self, _: SizeProposal, _: &LayoutContext) -> LayoutResponse {
4696 /// # Size::new(0.0, 0.0).into()
4697 /// # }
4698 /// # }
4699 /// # let mut tree = WidgetTree::new();
4700 /// # let panel_id = tree.add(MinWidget);
4701 /// tree.set_theme_override(panel_id, |theme| {
4702 /// theme.colors = ColorTokens::dark_default();
4703 /// });
4704 /// ```
4705 pub fn set_theme_override(
4706 &mut self,
4707 id: WidgetId,
4708 f: impl Fn(&mut crate::styles::Theme) + 'static,
4709 ) {
4710 let had_override = self
4711 .arena
4712 .get(id)
4713 .is_some_and(|n| n.theme_override.is_some());
4714 if let Some(node) = self.arena.get_mut(id) {
4715 node.theme_override = Some(crate::environment::ThemeOverride { func: Box::new(f) });
4716 node.dirty.needs_layout = true;
4717 node.dirty.needs_paint = true;
4718 }
4719 if !had_override {
4720 self.arena.theme_override_count += 1;
4721 }
4722 }
4723
4724 /// Get the resolved theme for a specific widget (applying ancestor overrides).
4725 pub fn resolved_theme(&self, id: WidgetId) -> crate::styles::Theme {
4726 self.arena.resolve_theme(id, &self.theme).into_owned()
4727 }
4728}
4729
4730impl Default for WidgetTree {
4731 fn default() -> Self {
4732 Self::new()
4733 }
4734}
4735
4736#[cfg(test)]
4737mod activation_signal_tests {
4738 use super::*;
4739 use crate::build_context::BuildContext;
4740 use crate::signal::Signal;
4741 use crate::widget::{LayoutContext, LayoutResponse, Widget};
4742 use teksilo_canvas::SizeProposal;
4743
4744 /// A leaf that, on build, opts into its activation signal and mirrors it
4745 /// into an out-of-band signal the test can read.
4746 #[derive(Debug)]
4747 struct ActivationProbe {
4748 log: Signal<Vec<bool>>,
4749 }
4750
4751 impl Widget for ActivationProbe {
4752 fn build(&mut self, ctx: &mut BuildContext) -> Vec<WidgetId> {
4753 let id = ctx.self_id();
4754 let vis = ctx.activation_signal(id);
4755 let log = self.log.clone();
4756 ctx.effect(&vis, move |active| {
4757 let mut v = log.get();
4758 v.push(*active);
4759 log.set(v);
4760 });
4761 Vec::new()
4762 }
4763
4764 fn layout_response(&self, proposal: SizeProposal, _ctx: &LayoutContext) -> LayoutResponse {
4765 proposal.resolve(10.0, 10.0).into()
4766 }
4767 }
4768
4769 /// A widget that enqueues a post-mount action via `run_after_mount` has it
4770 /// run exactly once, with a real `EventContext`, when the tree drains
4771 /// (`run_mount_actions`) — and `has_pending_mount_actions` reflects the
4772 /// queue state.
4773 #[derive(Debug)]
4774 struct MountActionProbe {
4775 ran: Signal<u32>,
4776 }
4777
4778 impl Widget for MountActionProbe {
4779 fn build(&mut self, ctx: &mut BuildContext) -> Vec<WidgetId> {
4780 let ran = self.ran.clone();
4781 ctx.run_after_mount(move |_ectx| ran.set(ran.get() + 1));
4782 Vec::new()
4783 }
4784
4785 fn layout_response(&self, proposal: SizeProposal, _ctx: &LayoutContext) -> LayoutResponse {
4786 proposal.resolve(10.0, 10.0).into()
4787 }
4788 }
4789
4790 #[test]
4791 fn run_after_mount_runs_once_on_drain() {
4792 let mut tree = WidgetTree::new();
4793 let ran = Signal::new(0_u32);
4794 tree.add(MountActionProbe { ran: ran.clone() });
4795 tree.layout(SizeProposal::exact(100.0, 100.0));
4796
4797 // Queued during build, not yet run.
4798 assert!(tree.has_pending_mount_actions());
4799 assert_eq!(ran.get(), 0);
4800
4801 // Drain with a Noop sink (as headless callers do).
4802 tree.run_mount_actions(&mut crate::window::NoopWindowOps);
4803 assert_eq!(ran.get(), 1);
4804 assert!(!tree.has_pending_mount_actions());
4805
4806 // Draining again is a no-op (the queue is empty).
4807 tree.run_mount_actions(&mut crate::window::NoopWindowOps);
4808 assert_eq!(ran.get(), 1);
4809 }
4810
4811 #[test]
4812 fn activation_signal_fires_on_dormant_and_reactivate() {
4813 let mut tree = WidgetTree::new();
4814 let log = Signal::new(Vec::<bool>::new());
4815 let probe = tree.add(ActivationProbe { log: log.clone() });
4816
4817 // Gate the probe's visibility on a signal.
4818 let visible = Signal::new(true);
4819 tree.visible_when(probe, visible.clone());
4820 tree.layout(SizeProposal::exact(100.0, 100.0));
4821
4822 // Initially active: effect registration alone fires nothing.
4823 assert_eq!(log.get(), Vec::<bool>::new());
4824
4825 // Hide → dormant → activation signal false.
4826 visible.set(false);
4827 tree.layout(SizeProposal::exact(100.0, 100.0));
4828 assert_eq!(log.get(), vec![false]);
4829
4830 // Show → active → activation signal true.
4831 visible.set(true);
4832 tree.layout(SizeProposal::exact(100.0, 100.0));
4833 assert_eq!(log.get(), vec![false, true]);
4834
4835 // Redundant relayout while active fires nothing new.
4836 tree.layout(SizeProposal::exact(100.0, 100.0));
4837 assert_eq!(log.get(), vec![false, true]);
4838 }
4839
4840 /// **A node parked and re-woken before the flush never looks dormant.**
4841 ///
4842 /// `pending_activation_changes` is an append-only queue, so this records
4843 /// two edges; replaying them in order would hand observers a `false` that
4844 /// was already superseded — for a state signal that is a lie, not a
4845 /// history. `present_in_tree_modal_request` takes exactly this route on
4846 /// every dialog (build the content, park it, mount the scrim, wake it,
4847 /// *then* move focus in), and the stale `false` landed after the focus
4848 /// dispatch: a text editor's dormancy handler wiped the focus it had just
4849 /// been granted and the dialog opened with no caret.
4850 #[test]
4851 fn a_park_and_wake_inside_one_batch_fires_nothing() {
4852 let mut tree = WidgetTree::new();
4853 let log = Signal::new(Vec::<bool>::new());
4854 let probe = tree.add(ActivationProbe { log: log.clone() });
4855 tree.layout(SizeProposal::exact(100.0, 100.0));
4856 assert_eq!(log.get(), Vec::<bool>::new());
4857
4858 tree.set_dormant(probe);
4859 tree.activate(probe);
4860 tree.layout(SizeProposal::exact(100.0, 100.0));
4861 assert_eq!(
4862 log.get(),
4863 Vec::<bool>::new(),
4864 "a node that ends the batch where it started never observably \
4865 changed — firing the intermediate `false` makes observers act on \
4866 a state that was never visible",
4867 );
4868
4869 // The converse still reports: a batch with a *net* transition fires
4870 // once, with the state the node actually ended in.
4871 tree.activate(probe);
4872 tree.set_dormant(probe);
4873 tree.layout(SizeProposal::exact(100.0, 100.0));
4874 assert_eq!(
4875 log.get(),
4876 vec![false],
4877 "a net Active→Dormant batch must still report, exactly once",
4878 );
4879
4880 tree.activate(probe);
4881 tree.layout(SizeProposal::exact(100.0, 100.0));
4882 assert_eq!(log.get(), vec![false, true]);
4883 }
4884}
4885
4886#[cfg(test)]
4887mod visible_when_builder_tests {
4888 use super::*;
4889 use crate::signal::{Prop, Signal};
4890 use crate::widget_builder::WidgetBuilder;
4891
4892 /// `.visible_when(signal)` on any widget builder threads a *bound*
4893 /// visibility prop onto the inserted node — so `teksu!`'s property form
4894 /// (`Widget { visible_when: sig }`) reaches the same `node.visible_state`
4895 /// slot as the imperative `ctx.visible_when(id, sig)`.
4896 #[test]
4897 fn visible_when_builder_binds_node_visibility() {
4898 let mut tree = WidgetTree::new();
4899 let shown = Signal::new(false);
4900 let id = tree.add(crate::test_widgets::FillWidget::new().visible_when(shown.clone()));
4901
4902 let node = tree.arena.get(id).expect("node exists");
4903 assert!(
4904 matches!(node.visible_state, Some(Prop::Bound(_))),
4905 "`.visible_when(Signal)` must store a bound visibility prop"
4906 );
4907 }
4908
4909 /// A static `bool` is accepted too (`Prop::Static`), matching
4910 /// `ctx.visible_when` / `access_hidden` semantics.
4911 #[test]
4912 fn visible_when_builder_accepts_static_bool() {
4913 let mut tree = WidgetTree::new();
4914 let id = tree.add(crate::test_widgets::FillWidget::new().visible_when(false));
4915
4916 let node = tree.arena.get(id).expect("node exists");
4917 assert!(matches!(node.visible_state, Some(Prop::Static(false))));
4918 }
4919}
4920
4921#[cfg(test)]
4922mod text_scale_tests {
4923 use super::*;
4924
4925 #[test]
4926 fn effective_theme_starts_equal_to_theme() {
4927 let tree = WidgetTree::new();
4928 assert_eq!(
4929 tree.effective_theme.typography.body.size,
4930 tree.theme.typography.body.size
4931 );
4932 assert_eq!(tree.user_text_scale(), 1.0);
4933 }
4934
4935 #[test]
4936 fn effective_text_scale_and_signal_track_the_combined_factor() {
4937 let mut tree = WidgetTree::new();
4938 assert_eq!(tree.effective_text_scale(), 1.0);
4939 assert_eq!(tree.text_scale_signal().get(), 1.0);
4940
4941 tree.set_user_text_scale(1.5);
4942 assert!((tree.effective_text_scale() - 1.5).abs() < 0.001);
4943 assert!((tree.text_scale_signal().get() - 1.5).abs() < 0.001);
4944
4945 // OS preference multiplies in.
4946 tree.set_accessibility_preferences(false, false, 2.0);
4947 assert!((tree.effective_text_scale() - 3.0).abs() < 0.01);
4948 assert!((tree.text_scale_signal().get() - 3.0).abs() < 0.01);
4949 }
4950
4951 #[test]
4952 fn set_user_text_scale_scales_effective_typography() {
4953 let mut tree = WidgetTree::new();
4954 let base = tree.theme.typography.body.size;
4955 tree.set_user_text_scale(1.5);
4956 assert!((tree.effective_theme.typography.body.size - base * 1.5).abs() < 0.001);
4957 // The unscaled base theme is untouched.
4958 assert_eq!(tree.theme.typography.body.size, base);
4959 }
4960
4961 #[test]
4962 fn set_theme_preserves_existing_user_scale() {
4963 let mut tree = WidgetTree::new();
4964 tree.set_user_text_scale(2.0);
4965 let dark = crate::presets::intui::dark();
4966 let dark_base = dark.typography.body.size;
4967 tree.set_theme(dark);
4968 assert!((tree.effective_theme.typography.body.size - dark_base * 2.0).abs() < 0.001);
4969 }
4970
4971 #[test]
4972 fn os_text_scale_multiplies_with_user_scale() {
4973 let mut tree = WidgetTree::new();
4974 let base = tree.theme.typography.body.size;
4975 tree.set_user_text_scale(1.5);
4976 // OS preference reports 1.2 → combined 1.8.
4977 tree.set_accessibility_preferences(false, false, 1.2);
4978 assert!((tree.effective_theme.typography.body.size - base * 1.8).abs() < 0.01);
4979 }
4980
4981 #[test]
4982 fn same_scale_is_a_noop_and_factor_is_clamped() {
4983 let mut tree = WidgetTree::new();
4984 tree.set_user_text_scale(1.5);
4985 // Re-setting the same value should not panic / change anything.
4986 tree.set_user_text_scale(1.5);
4987 assert_eq!(tree.user_text_scale(), 1.5);
4988 // Out-of-range clamps into [0.25, 8.0].
4989 tree.set_user_text_scale(100.0);
4990 assert_eq!(tree.user_text_scale(), 8.0);
4991 }
4992}
4993
4994/// Covers the `WidgetTree`-level facts
4995/// `teksilo_app::WindowManager::request_redraw_needing_render` (the
4996/// targeted cross-window redraw added for shared-`Signal` dispatch
4997/// fan-out) relies on. Neither test touches windows at all — they exist
4998/// to pin down `needs_render()`'s contract in isolation, since
4999/// teksilo-app cannot stand up a real `PlatformWindow` in a unit test.
5000#[cfg(test)]
5001mod cross_window_redraw_signal_tests {
5002 use super::*;
5003 use crate::signal::Signal;
5004 use crate::test_widgets::{FillWidget, StackWidget};
5005 use teksilo_canvas::SizeProposal;
5006
5007 /// The premise the fix acts on, AND the trap a naive fix would fall
5008 /// into. A `Signal` shared by two independent trees (standing in for
5009 /// two windows) is supposed to dirty both when mutated, even though
5010 /// only one of them is the tree whose dispatch made the mutation —
5011 /// but `Signal::set` only flips a dirty flag on the signal itself and
5012 /// in the `BindingRegistry`; nothing walks that into a tree's
5013 /// `needs_layout` / `needs_paint` bits (what `needs_render()` reads)
5014 /// except that tree's OWN `process_state_changes`, run at the top of
5015 /// its OWN `layout()`. So immediately after the mutation, with
5016 /// neither tree having re-run `layout()`, BOTH read clean — a naive
5017 /// "just check `needs_render()`" cross-window redraw would see
5018 /// nothing to do and stay a permanent no-op. Once tree B's `layout()`
5019 /// runs (what `request_redraw_needing_render` does for every window
5020 /// before checking it), the same mutation is finally visible there.
5021 ///
5022 /// Each tree wraps its gated leaf in a `StackWidget` parent (rather
5023 /// than gating a bare root leaf) so the fact under test — an ACTIVE
5024 /// widget ending up dirty — is unambiguous: `any_needs_layout()` /
5025 /// `any_needs_paint()` only ever look at `Active` nodes, and a leaf
5026 /// that itself goes dormant is deliberately excluded from both (a
5027 /// hidden widget has nothing to paint). What must go dirty here is
5028 /// the STILL-ACTIVE stack, via `mark_ancestors_need_layout` — the
5029 /// same mechanism that makes a real window's content re-flow around
5030 /// a child that just appeared or disappeared.
5031 #[test]
5032 fn a_shared_signal_mutation_only_shows_up_after_that_trees_own_layout_reconciles_it() {
5033 let shared = Signal::new(true);
5034
5035 let mut tree_a = WidgetTree::new();
5036 let stack_a = tree_a.add(StackWidget::new());
5037 let id_a = tree_a.add_child(stack_a, FillWidget::new());
5038 tree_a.visible_when(id_a, shared.clone());
5039
5040 let mut tree_b = WidgetTree::new();
5041 let stack_b = tree_b.add(StackWidget::new());
5042 let id_b = tree_b.add_child(stack_b, FillWidget::new());
5043 tree_b.visible_when(id_b, shared.clone());
5044
5045 let proposal = SizeProposal::exact(100.0, 100.0);
5046
5047 // Bring both to the same clean baseline a real event loop reaches
5048 // after its initial layout + paint.
5049 tree_a.layout(proposal);
5050 tree_a.render();
5051 tree_b.layout(proposal);
5052 tree_b.render();
5053 assert!(!tree_a.needs_render(), "precondition: tree A starts clean");
5054 assert!(!tree_b.needs_render(), "precondition: tree B starts clean");
5055
5056 // Simulate a handler mutating the shared Signal during tree A's
5057 // dispatch. Neither tree re-runs layout() here yet.
5058 shared.set(false);
5059
5060 assert!(
5061 !tree_a.needs_render(),
5062 "the mutation alone does not retroactively dirty tree A either — \
5063 a Signal write cannot poke an arena directly, only the next \
5064 process_state_changes (inside layout()) can"
5065 );
5066 assert!(
5067 !tree_b.needs_render(),
5068 "and tree B reads exactly as clean as tree A does at this point — \
5069 checking needs_render() without reconciling first cannot tell them apart"
5070 );
5071
5072 // ...but they are NOT indistinguishable to `needs_reconcile()`,
5073 // which is what `request_redraw_needing_render` actually gates
5074 // its reconcile on. Both trees observe the shared Signal, so
5075 // both report pending reactive work here — and asking is
5076 // read-only, so asking tree A first does not answer for tree B.
5077 assert!(
5078 tree_a.needs_reconcile() && tree_b.needs_reconcile(),
5079 "both trees must report pending reactive work from the shared write"
5080 );
5081
5082 // This is what `request_redraw_needing_render` does for a window
5083 // whose gate is open — reconcile at the window's OWN current
5084 // size, which is what walks a pending Signal-driven change into
5085 // the arena.
5086 tree_b.layout(proposal);
5087
5088 assert!(
5089 tree_b.needs_render(),
5090 "tree B, which merely OBSERVES the shared Signal, is now dirty — \
5091 this is the cross-tree fan-out request_redraw_needing_render \
5092 exists to notice (via its own reconcile-then-check) and repaint"
5093 );
5094 assert!(
5095 !tree_b.needs_reconcile(),
5096 "and having reconciled, tree B's gate closes again"
5097 );
5098 assert!(
5099 tree_a.needs_reconcile(),
5100 "while tree A — which has NOT reconciled — is still waiting; one \
5101 window's reconcile must never close another's gate"
5102 );
5103 }
5104
5105 /// The gate `request_redraw_needing_render` gained must stay SHUT for
5106 /// a window with nothing reactive pending, or it saves nothing: that
5107 /// method runs after every dispatched event, and an open gate costs
5108 /// a full `layout_with_ops` — a dozen per-frame passes (pending
5109 /// animations, frame tick, scheduler tick, drag tick,
5110 /// `process_state_changes`, tooltips, four overlay passes) before it
5111 /// reaches the geometry short-circuit, for every open window, on
5112 /// every event of a fast mouse-move stream.
5113 #[test]
5114 fn needs_reconcile_is_false_for_an_idle_tree() {
5115 let shared = Signal::new(true);
5116 let mut idle = WidgetTree::new();
5117 let stack = idle.add(StackWidget::new());
5118 let leaf = idle.add_child(stack, FillWidget::new());
5119 idle.visible_when(leaf, shared.clone());
5120 idle.layout(SizeProposal::exact(100.0, 100.0));
5121 idle.render();
5122
5123 assert!(!idle.needs_reconcile(), "nothing written — gate shut");
5124 assert!(!idle.needs_reconcile(), "and asking does not open it");
5125
5126 shared.set(false);
5127 assert!(idle.needs_reconcile(), "a write opens it");
5128 idle.layout(SizeProposal::exact(100.0, 100.0));
5129 assert!(!idle.needs_reconcile(), "reconciling closes it again");
5130 }
5131
5132 /// A *pending* `animate_to` contributes no scheduler deadline until
5133 /// `process_pending_animations` promotes it, so `next_timer_deadline`
5134 /// (and therefore `request_redraw_due`) cannot see it. The gate must,
5135 /// or arming an animation from another window's handler would leave
5136 /// it parked until something unrelated woke the window.
5137 #[test]
5138 fn needs_reconcile_sees_an_animation_armed_but_not_yet_started() {
5139 let mut tree = WidgetTree::new();
5140 let id = tree.add(FillWidget::new());
5141 tree.layout(SizeProposal::exact(50.0, 50.0));
5142 tree.render();
5143
5144 // Registered but deliberately NOT bound to any widget, so the
5145 // binding-registry term cannot be what notices it.
5146 let anim = Signal::new_animated(0.0_f32);
5147 tree.register_animated_signal(&anim, id);
5148 assert!(!tree.needs_reconcile(), "precondition: nothing armed yet");
5149
5150 anim.animate_to(
5151 1.0,
5152 std::time::Duration::from_millis(200),
5153 teksilo_tokens::Easing::Linear,
5154 );
5155 assert!(
5156 tree.needs_reconcile(),
5157 "an armed-but-unstarted animation is reactive work only layout() can pick up"
5158 );
5159 assert!(
5160 anim.has_pending_animation(),
5161 "and asking must not have consumed the request"
5162 );
5163
5164 tree.layout(SizeProposal::exact(50.0, 50.0));
5165 assert!(
5166 !anim.has_pending_animation(),
5167 "the reconcile promoted it into the scheduler"
5168 );
5169 }
5170
5171 /// An animation armed *after* the wall clock has overtaken the simulated one
5172 /// must still run.
5173 ///
5174 /// `layout` promotes a pending `animate_to` into the scheduler; once
5175 /// `tick_animations` is driving the tree, the scheduler is only ever ticked at
5176 /// `sim_clock`. Stamping the promotion with `Instant::now()` therefore put the
5177 /// start in the scheduler's *future* the moment a test's real time outran the
5178 /// simulated time it had asked for — and a start in the future does not run
5179 /// slow, it does not run at all. That made animated headless tests a function
5180 /// of machine load: green run alone, frozen once a full suite filled the cores
5181 /// and stretched each test's wall-clock time past its simulated budget.
5182 ///
5183 /// The two clocks below are the shape of that: 90 ms simulated against at
5184 /// least 100 ms real, so simulated time never catches up. Under the old
5185 /// behaviour the animation stays pinned at its start value forever.
5186 #[test]
5187 fn an_animation_armed_after_real_time_outran_the_sim_clock_still_runs() {
5188 let mut tree = WidgetTree::new();
5189 let id = tree.add(FillWidget::new());
5190 tree.layout(SizeProposal::exact(50.0, 50.0));
5191
5192 // Put the tree in simulated time, then let the wall clock get ahead of it.
5193 tree.tick_animations(std::time::Duration::from_millis(10));
5194 std::thread::sleep(std::time::Duration::from_millis(100));
5195
5196 let anim = Signal::new_animated(0.0_f32);
5197 tree.register_animated_signal(&anim, id);
5198 anim.animate_to(
5199 1.0,
5200 std::time::Duration::from_millis(50),
5201 teksilo_tokens::Easing::Linear,
5202 );
5203 tree.layout(SizeProposal::exact(50.0, 50.0));
5204
5205 // 80 ms of simulated time against a 50 ms animation: comfortably finished
5206 // on the only clock the scheduler is ever ticked with, and still short of
5207 // the ~100 ms of real time that has passed.
5208 tree.tick_animations(std::time::Duration::from_millis(80));
5209
5210 assert_eq!(
5211 anim.get(),
5212 1.0,
5213 "the animation must be measured against the clock it is ticked with, \
5214 not the wall clock that has already run past it"
5215 );
5216 assert!(
5217 !tree.has_active_animations(),
5218 "and having reached its target it must be off the scheduler"
5219 );
5220 }
5221
5222 /// A layout pass on a simulated tree advances no animation.
5223 ///
5224 /// The mirror image of the test above, and the other half of the same
5225 /// contract: `layout` both **promotes** a pending `animate_to` and
5226 /// **ticks** the scheduler, and it has to do both against the same clock.
5227 /// Promoting at `sim_clock` while ticking at `Instant::now()` hands the
5228 /// freshly promoted animation an elapsed time equal to the tree's entire
5229 /// wall-clock age — so it finishes inside the very layout pass that started
5230 /// it, and how much of it a test ever observes depends on how long that
5231 /// test took to get there.
5232 ///
5233 /// The 120 ms slept below is what the wall clock would contribute; the
5234 /// tween is 100 ms, so under the old behaviour it is already over before
5235 /// the caller advances anything.
5236 #[test]
5237 fn a_layout_pass_on_a_simulated_tree_advances_no_animation() {
5238 let mut tree = WidgetTree::new();
5239 let id = tree.add(FillWidget::new());
5240 tree.layout(SizeProposal::exact(50.0, 50.0));
5241
5242 // Put the tree on the simulated clock, then let real time run past the
5243 // whole duration of the animation that is about to be armed.
5244 tree.advance_time(std::time::Duration::from_millis(1));
5245 std::thread::sleep(std::time::Duration::from_millis(120));
5246
5247 let anim = Signal::new_animated(0.0_f32);
5248 tree.register_animated_signal(&anim, id);
5249 anim.animate_to(
5250 100.0,
5251 std::time::Duration::from_millis(100),
5252 teksilo_tokens::Easing::Linear,
5253 );
5254 tree.layout(SizeProposal::exact(50.0, 50.0));
5255
5256 assert_eq!(
5257 anim.get(),
5258 0.0,
5259 "a layout pass promotes the animation; it does not also age it by \
5260 however long the tree has been alive"
5261 );
5262
5263 // It moves when, and only when, the clock is advanced.
5264 tree.advance_time(std::time::Duration::from_millis(50));
5265 assert!(
5266 (anim.get() - 50.0).abs() < 2.0,
5267 "half of a 100 ms linear tween: {}",
5268 anim.get()
5269 );
5270 }
5271
5272 /// `needs_render()` (paint/layout dirt only) must stay `false` while a
5273 /// per-frame `Signal<f32>` animation is merely *running*, with nothing
5274 /// new to paint. `request_redraw_needing_render` filters on
5275 /// `needs_render()`, not the broader `needs_redraw()`, precisely so a
5276 /// window with a live animation isn't forced into an extra immediate
5277 /// redraw on every sibling-window event — that would defeat the 60 Hz
5278 /// `WaitUntil` pacing those animations already get elsewhere and
5279 /// reintroduce the uncapped free-running redraw bug that pacing was
5280 /// written to remove.
5281 #[test]
5282 fn needs_render_excludes_a_running_animation_with_no_dirty_paint() {
5283 let mut tree = WidgetTree::new();
5284 let id = tree.add(FillWidget::new());
5285 tree.layout(SizeProposal::exact(50.0, 50.0));
5286 tree.render();
5287 assert!(!tree.needs_render(), "precondition: tree starts clean");
5288 assert!(!tree.needs_redraw(), "precondition: nothing running yet");
5289
5290 let anim = Signal::new_animated(0.0_f32);
5291 tree.register_animated_signal(&anim, id);
5292 anim.animate_to(
5293 1.0,
5294 std::time::Duration::from_millis(200),
5295 teksilo_tokens::Easing::Linear,
5296 );
5297 // `process_pending_animations` (which picks up the pending
5298 // `animate_to` and starts it on the scheduler) runs inside `layout`.
5299 tree.layout(SizeProposal::exact(50.0, 50.0));
5300
5301 assert!(
5302 tree.needs_redraw(),
5303 "an animation just started, so needs_redraw() (has_running()) must be true"
5304 );
5305 assert!(
5306 !tree.needs_render(),
5307 "but nothing is actually dirty for paint/layout — needs_render() must stay false, \
5308 which is the whole point of using it (not needs_redraw()) as the cross-window filter"
5309 );
5310 }
5311}
5312
5313#[cfg(test)]
5314mod effective_enabled_signal_tests {
5315 use super::*;
5316 use crate::build_context::BuildContext;
5317 use crate::signal::Signal;
5318 use crate::widget::{LayoutContext, LayoutResponse, Widget};
5319 use std::cell::RefCell;
5320 use std::rc::Rc;
5321 use teksilo_canvas::SizeProposal;
5322
5323 type SignalSlot = Rc<RefCell<Option<Signal<bool>>>>;
5324
5325 /// A leaf that opts into `effective_enabled_signal` from inside its own
5326 /// `build()` — the only way real widgets use it, and the case that was
5327 /// broken. It publishes the handle so the test can read the live value.
5328 #[derive(Debug)]
5329 struct EnabledProbe {
5330 out: SignalSlot,
5331 }
5332
5333 impl Widget for EnabledProbe {
5334 fn build(&mut self, ctx: &mut BuildContext) -> Vec<WidgetId> {
5335 let id = ctx.self_id();
5336 let sig = ctx.effective_enabled_signal(id);
5337 // Also pins that the signal is *mutable*: the previous derived
5338 // implementation panicked here with "observe() is only supported
5339 // on mutable signals", which is why widgets could not use
5340 // `ctx.effect` to react to being disabled.
5341 ctx.effect(&sig, |_| {});
5342 *self.out.borrow_mut() = Some(sig);
5343 Vec::new()
5344 }
5345
5346 fn layout_response(&self, proposal: SizeProposal, _ctx: &LayoutContext) -> LayoutResponse {
5347 proposal.resolve(10.0, 10.0).into()
5348 }
5349 }
5350
5351 /// A composite that adds the probe through the ordinary `ctx.add` idiom, so
5352 /// the child is inserted PARENTLESS and builds before its parent link is
5353 /// wired — the exact situation that defeated the old
5354 /// walk-the-ancestors-at-call-time implementation.
5355 #[derive(Debug)]
5356 struct Form {
5357 enabled: Signal<bool>,
5358 out: SignalSlot,
5359 }
5360
5361 impl Widget for Form {
5362 fn build(&mut self, ctx: &mut BuildContext) -> Vec<WidgetId> {
5363 let id = ctx.self_id();
5364 ctx.enabled_when(id, self.enabled.clone());
5365 vec![ctx.add(EnabledProbe {
5366 out: self.out.clone(),
5367 })]
5368 }
5369
5370 fn layout_response(&self, proposal: SizeProposal, _ctx: &LayoutContext) -> LayoutResponse {
5371 proposal.resolve(10.0, 10.0).into()
5372 }
5373 }
5374
5375 fn mount_form(enabled: Signal<bool>) -> (WidgetTree, WidgetId, Signal<bool>) {
5376 let out: SignalSlot = Rc::new(RefCell::new(None));
5377 let mut tree = WidgetTree::new();
5378 let form = tree.add(Form {
5379 enabled,
5380 out: out.clone(),
5381 });
5382 tree.layout(SizeProposal::exact(100.0, 100.0));
5383 let sig = out.borrow().clone().expect("probe published its signal");
5384 (tree, form, sig)
5385 }
5386
5387 /// THE REGRESSION. A widget whose own `enabled` is untouched must still
5388 /// report disabled when an ANCESTOR is disabled. This failed before the
5389 /// signal became node-resident: `insert_widget` inserts the node with
5390 /// `parent: None` and wires the parent only after `build()` returns, so an
5391 /// ancestor walk done during `build()` saw an empty chain and captured
5392 /// "enabled" for the widget's whole life.
5393 #[test]
5394 fn tracks_an_ancestor_disabled_before_mount() {
5395 let (_tree, _form, sig) = mount_form(Signal::new(false));
5396 assert!(
5397 !sig.get(),
5398 "a child of a disabled ancestor must report effectively-disabled"
5399 );
5400 }
5401
5402 /// The live case: the ancestor's bound signal flips after mount. The child
5403 /// must follow, in both directions, with no rebuild.
5404 #[test]
5405 fn follows_an_ancestor_flipping_after_mount() {
5406 let enabled = Signal::new(true);
5407 let (mut tree, _form, sig) = mount_form(enabled.clone());
5408 assert!(sig.get(), "starts enabled");
5409
5410 enabled.set(false);
5411 tree.layout(SizeProposal::exact(100.0, 100.0));
5412 assert!(!sig.get(), "child follows the ancestor going disabled");
5413
5414 enabled.set(true);
5415 tree.layout(SizeProposal::exact(100.0, 100.0));
5416 assert!(sig.get(), "and follows it coming back");
5417 }
5418
5419 /// A widget's own `enabled_state` still works on its own.
5420 #[test]
5421 fn honours_the_widgets_own_state() {
5422 let out: SignalSlot = Rc::new(RefCell::new(None));
5423 let mut tree = WidgetTree::new();
5424 let probe = tree.add(EnabledProbe { out: out.clone() });
5425 tree.enabled_when(probe, false);
5426 tree.layout(SizeProposal::exact(100.0, 100.0));
5427 let sig = out.borrow().clone().unwrap();
5428 assert!(!sig.get(), "own enabled_state alone disables");
5429 }
5430
5431 /// The signal must agree with the paint-time bool the render walker
5432 /// computes. If they disagreed, role-driven chrome (which dims from
5433 /// `PaintContext::effective_enabled`) and signal-driven chrome (which dims
5434 /// from this signal) would grey out at different moments.
5435 #[test]
5436 fn agrees_with_the_paint_time_effective_enabled() {
5437 let enabled = Signal::new(true);
5438 let (mut tree, form, sig) = mount_form(enabled.clone());
5439 let probe = tree.children(form)[0];
5440
5441 for value in [false, true, false] {
5442 enabled.set(value);
5443 tree.layout(SizeProposal::exact(100.0, 100.0));
5444 assert_eq!(
5445 sig.get(),
5446 tree.is_enabled(probe),
5447 "signal and the arena's live is_enabled must agree (enabled={value})"
5448 );
5449 }
5450 }
5451
5452 /// Install-or-reuse: asking twice hands back the same signal.
5453 #[test]
5454 fn is_install_or_reuse() {
5455 let out: SignalSlot = Rc::new(RefCell::new(None));
5456 let mut tree = WidgetTree::new();
5457 let id = tree.add(EnabledProbe { out });
5458 let a = tree.effective_enabled_signal(id);
5459 let b = tree.effective_enabled_signal(id);
5460 assert!(
5461 Signal::same(&a, &b),
5462 "must hand back the same signal handle"
5463 );
5464 }
5465}
5466
5467#[cfg(test)]
5468mod density_tests {
5469 use super::*;
5470 use teksilo_tokens::{DensityPolicy, TargetDensity};
5471
5472 /// A fresh tree is Compact — today's behaviour — and reports it.
5473 #[test]
5474 fn a_fresh_tree_is_compact() {
5475 let tree = WidgetTree::new();
5476 assert_eq!(tree.input_density(), TargetDensity::Compact);
5477 assert_eq!(tree.theme().input, teksilo_tokens::InputTokens::default());
5478 assert!(tree.touch_enabled());
5479 assert_eq!(
5480 tree.density_policy(),
5481 DensityPolicy::Fixed(TargetDensity::Compact)
5482 );
5483 }
5484
5485 /// A density switch changes what the tree reports **and** dirties it at the
5486 /// rebuild level — a target size is baked in `build()`, so layout+paint
5487 /// alone cannot re-bake it.
5488 #[test]
5489 fn switching_density_reports_and_dirties_at_rebuild_level() {
5490 let mut tree = WidgetTree::new();
5491 let root = tree.add(crate::test_widgets::FillWidget::new());
5492 tree.layout(SizeProposal::exact(400.0, 300.0));
5493 assert!(
5494 tree.arena.collect_needs_rebuild().is_empty(),
5495 "a laid-out tree starts clean"
5496 );
5497
5498 tree.set_input_density(TargetDensity::Touch);
5499
5500 assert_eq!(tree.input_density(), TargetDensity::Touch);
5501 assert_eq!(tree.theme().input.target_size, 44.0);
5502 assert_eq!(tree.theme().input.grab_size, 16.0);
5503 assert!(
5504 tree.arena.collect_needs_rebuild().contains(&root),
5505 "the root must be marked for rebuild, not merely relayout"
5506 );
5507 }
5508
5509 /// Re-setting the same density must not throw away every widget id in the
5510 /// tree for nothing.
5511 #[test]
5512 fn re_setting_the_same_density_is_a_no_op() {
5513 let mut tree = WidgetTree::new();
5514 let _root = tree.add(crate::test_widgets::FillWidget::new());
5515 tree.layout(SizeProposal::exact(400.0, 300.0));
5516
5517 tree.set_input_density(TargetDensity::Compact);
5518
5519 assert!(tree.arena.collect_needs_rebuild().is_empty());
5520 }
5521
5522 /// The theme signal follows a density switch, so a `theme_signal`-bound
5523 /// widget re-resolves without its own wiring.
5524 #[test]
5525 fn the_theme_signal_follows_a_density_switch() {
5526 let mut tree = WidgetTree::new();
5527 tree.set_input_density(TargetDensity::Comfortable);
5528 assert_eq!(
5529 tree.theme_signal().get().input.density,
5530 TargetDensity::Comfortable
5531 );
5532 assert_eq!(tree.theme_signal().get().input.target_size, 32.0);
5533 }
5534
5535 /// The kill switch is state on the theme, reachable both ways, and does
5536 /// not rebuild — it changes which events are accepted, not a dimension.
5537 #[test]
5538 fn the_touch_kill_switch_round_trips_without_a_rebuild() {
5539 let mut tree = WidgetTree::new();
5540 let _root = tree.add(crate::test_widgets::FillWidget::new());
5541 tree.layout(SizeProposal::exact(400.0, 300.0));
5542
5543 tree.set_touch_enabled(false);
5544
5545 assert!(!tree.touch_enabled());
5546 assert!(!tree.theme().input.touch_enabled);
5547 assert!(!tree.theme_signal().get().input.touch_enabled);
5548 assert!(tree.arena.collect_needs_rebuild().is_empty());
5549
5550 tree.set_touch_enabled(true);
5551 assert!(tree.touch_enabled());
5552 }
5553
5554 /// The policy is stored verbatim and does not itself move the density.
5555 #[test]
5556 fn setting_a_policy_does_not_switch_the_density() {
5557 let mut tree = WidgetTree::new();
5558 let policy = DensityPolicy::FollowLastPointer {
5559 coarse: TargetDensity::Touch,
5560 fine: TargetDensity::Compact,
5561 hysteresis: std::time::Duration::from_secs(1),
5562 };
5563 tree.set_density_policy(policy);
5564
5565 assert_eq!(tree.density_policy(), policy);
5566 assert_eq!(tree.input_density(), TargetDensity::Compact);
5567 }
5568}