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