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