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_impl;
16mod drag_drop_impl;
17mod event_dispatch_impl;
18mod focus_impl;
19mod gesture_dispatch_impl;
20mod layout_impl;
21mod overlay_impl;
22mod query_impl;
23mod rendering_impl;
24mod test_api;
25
26/// The main widget tree orchestrating arena, layout, events, accessibility, and paint.
27/// Provides both the runtime API and the headless test API.
28struct AnimatedRegistration {
29 weak: crate::signal::WeakAnimatedSignal,
30 owner: WidgetId,
31}
32
33impl AnimatedRegistration {
34 fn same_signal(&self, signal: &crate::signal::Signal<f32>) -> bool {
35 self.weak.same_signal(signal)
36 }
37
38 fn is_alive(&self) -> bool {
39 self.weak.upgrade().is_some()
40 }
41
42 fn take_pending_animation(
43 &self,
44 ) -> Option<(
45 crate::signal::Signal<f32>,
46 crate::animation::AnimationRequest,
47 WidgetId,
48 )> {
49 let signal = self.weak.upgrade()?;
50 let request = signal.take_pending_animation()?;
51 Some((signal, request, self.owner))
52 }
53
54 /// Non-consuming counterpart to [`take_pending_animation`](Self::take_pending_animation),
55 /// for [`WidgetTree::needs_reconcile`] — which must be able to ask
56 /// "is there work here?" without doing any.
57 fn has_pending_animation(&self) -> bool {
58 self.weak
59 .upgrade()
60 .is_some_and(|signal| signal.has_pending_animation())
61 }
62}
63
64#[allow(clippy::type_complexity)]
65pub struct WidgetTree {
66 arena: WidgetArena,
67 /// Current theme value cached for `&Theme` accessors used by layout/paint
68 /// contexts and by widgets that need an immediate read. The reactive source
69 /// of truth is `theme_signal`; both are updated in lockstep by `set_theme`.
70 theme: Theme,
71 /// Reactive theme signal. Widgets that want their visual or derived state
72 /// to track theme changes bind to this signal or build derived signals via
73 /// `zip`/`map`. `set_theme` updates the signal (firing observers) without
74 /// rebuilding the widget tree, so interaction state (focus, scroll, expanded
75 /// panels, …) survives theme switches.
76 theme_signal: crate::signal::Signal<Theme>,
77 /// User-controlled global text-scale factor (`1.0` = 100 %). Layered on top
78 /// of the OS `text_scale_factor`: the two multiply. Set via
79 /// `set_user_text_scale`; persisted by the application through
80 /// `teksilo_settings::TEXT_SCALE_KEY`.
81 user_text_scale: f32,
82 /// Cached projection of `theme` whose `typography` is scaled by
83 /// `user_text_scale * text_scale_factor`. Recomputed by
84 /// `recompute_effective_theme` whenever the theme or either scale factor
85 /// changes; the layout and paint walkers read this instead of `theme` so
86 /// all text grows uniformly. Equal to `theme` when the combined factor is 1.
87 effective_theme: Theme,
88 /// The combined `user_text_scale * text_scale_factor`, cached so the
89 /// layout/paint context construction sites don't recompute it. The single
90 /// scalar published to widgets that size from a source *other* than
91 /// `Theme.typography` (icons, the rich-text engine, calendar constants,
92 /// scene text). Written alongside `effective_theme` in
93 /// `recompute_effective_theme`.
94 effective_text_scale: f32,
95 /// Reactive mirror of `effective_text_scale`, for build-time binders that
96 /// must react to a scale change without a rebuild path of their own (e.g.
97 /// `Calendar` binds this at `Rebuild` level). Fired by
98 /// `recompute_effective_theme`.
99 text_scale_signal: crate::signal::Signal<f32>,
100 /// Reactive window-active state (`focused AND not occluded`), the
101 /// occlusion-aware companion to `WindowState::focused` (which is raw OS
102 /// focus only). The single source of truth for "is this window active",
103 /// read by `is_window_active()` and published to widgets via
104 /// `window_active_signal()` / `BuildContext::window_active*` /
105 /// `PaintContext::window_active`. Drives caret hiding, selection
106 /// desaturation and `DimWhenInactive`. Starts `true` — winit may not send
107 /// `Focused(true)` for the first window, so a window must not be born
108 /// inactive. Mutated only by `set_window_active`.
109 window_active_signal: crate::signal::Signal<bool>,
110 text_backend: Option<Rc<RefCell<dyn teksilo_canvas::TextBackend>>>,
111 focused: Option<WidgetId>,
112 /// Reactive mirror of `focused`. Same pattern as `hovered_signal`
113 /// — kept in sync via `set_focused`. Drives the inspector's Focus
114 /// tab without polling.
115 focused_signal: crate::signal::Signal<Option<WidgetId>>,
116 hovered: Option<WidgetId>,
117 /// Reactive mirror of `hovered`. Set whenever `hovered` changes
118 /// during dispatch / hit-test recovery so external observers
119 /// (notably the debug inspector's hover tooltip) can react without
120 /// polling. Held by handle so the field is a cheap clone.
121 hovered_signal: crate::signal::Signal<Option<WidgetId>>,
122 /// Last known pointer position from `PointerMove`. Used by
123 /// `revalidate_interaction_state` to re-hit-test the hover after
124 /// a rebuild shifts content under a stationary cursor — without
125 /// this, the next `Scroll` event routes to `focused` (or falls
126 /// through to an ancestor scrollable) instead of the item the
127 /// user is actually pointing at.
128 last_pointer_position: Option<teksilo_canvas::Point>,
129 /// A rebuild destroyed the focused widget: the subtree that owned focus,
130 /// remembered so the end of the layout pass can land focus back inside it.
131 ///
132 /// A rebuild allocates fresh `WidgetId`s for its children, so the focused
133 /// node dies and `revalidate_interaction_state` drops focus to `None`.
134 /// Leaving it there kicks the user out of the widget they were in — most
135 /// visibly, a popover that refreshes its content when it opens would throw
136 /// away the very row the popover had just focused, so the menu comes up with
137 /// no keyboard focus at all. Focus is re-entered *after* the layout walk
138 /// (see the tail of `layout_with_ops`), once the fresh children have real
139 /// bounds for the focus-driven scroll-into-view — the same shape as the
140 /// post-layout hover refresh next to it.
141 pending_focus_restore: Option<WidgetId>,
142 last_proposal: SizeProposal,
143 pending_modal_requests: Vec<crate::modal::QueuedModalRequest>,
144 pending_modal_dismissal: bool,
145 shortcut_registry: crate::shortcut::ShortcutRegistry,
146 /// Queue of intents awaiting dispatch. Populated either by the
147 /// keystroke interception path (`dispatch_event` for KeyDown) or
148 /// by handlers calling `ctx.send_intent(...)`. Drained between
149 /// event-handler calls by [`WidgetTree::drain_pending_intents`].
150 /// The tuple carries the source widget (dispatch anchor), the
151 /// intent itself, and the firing shortcut's
152 /// `propagate_when_disabled` policy.
153 pending_intents: Vec<(WidgetId, crate::intent::Intent, bool)>,
154 /// Window-global actions registered via
155 /// [`BuildContext::register_action_global`](crate::BuildContext::register_action_global).
156 /// Consulted as a fallback at the end of every intent dispatch — *after* the
157 /// source→root walk finds no consuming node action — so an app-global command
158 /// is reachable no matter where the intent originated (a menu-bar dropdown
159 /// overlay, deep content, a global shortcut anchored at the root). Each entry
160 /// is owned by the registering widget and torn down on its rebuild/destroy,
161 /// mirroring `register_shortcut_global`.
162 global_actions: Vec<(WidgetId, crate::action::Action)>,
163 /// The widgets that edit text, registered via
164 /// [`BuildContext::register_text_surface`](crate::BuildContext::register_text_surface).
165 ///
166 /// Owned by the registering widget and torn down on its rebuild/destroy,
167 /// exactly like `global_actions` above. Read through
168 /// [`WidgetTree::focused_text_surface`] by a host that has taken a text
169 /// chord — `Ctrl+Z`, `Ctrl+C` — for itself and owes every text widget in the
170 /// tree an answer about what happens to it. See
171 /// [`crate::text_surface`] for why the framework is the only place that
172 /// question can be answered completely.
173 text_surfaces: crate::text_surface::TextSurfaces,
174 /// Currently-armed key-capture slot. `Some` when
175 /// [`WidgetTree::begin_key_capture`] has been called and the
176 /// returned [`CaptureHandle`](crate::shortcut::CaptureHandle)
177 /// is still alive. The slot is shared (via `Rc`) with the handle
178 /// so dropping the handle cancels the capture, and calling
179 /// `begin_key_capture` again creates a fresh slot without
180 /// touching the previous one (whose handle, if dropped later,
181 /// only clears its own orphaned slot).
182 key_capture: Option<crate::shortcut::KeyCaptureSlot>,
183 binding_registry: crate::binding::BindingRegistry,
184 idle_queue: crate::idle::IdleQueue,
185 /// Simulated clock for deterministic time-dependent testing.
186 sim_clock: std::time::Instant,
187 /// Whether [`tick_animations`](Self::tick_animations) has ever driven this
188 /// tree — i.e. whether [`Self::sim_clock`], rather than the wall clock, is
189 /// the one animations are measured against. See [`Self::animation_clock`].
190 sim_driven: bool,
191 /// Overlay manager for tooltips, menus, popovers.
192 pub(crate) overlay_manager: crate::overlay::OverlayManager,
193 /// Tooltip attachments: (anchor_id, content_id, text, delay, hover_start, overlay_id).
194 tooltips: Vec<TooltipEntry>,
195 /// Simulated-clock end of the tooltip "reshow session". While any tip is
196 /// visible, or until this instant after the last tip dismissed, subsequent
197 /// anchors use `MotionTokens::tooltip_reshow_delay` instead of the full
198 /// initial delay (Windows `TTDT_RESHOW` behaviour).
199 tooltip_session_until_sim: Option<std::time::Instant>,
200 /// Real-clock counterpart of [`Self::tooltip_session_until_sim`].
201 tooltip_session_until_real: Option<std::time::Instant>,
202 /// The tooltip currently surfaced by keyboard menu navigation
203 /// (`show_highlight_tooltip`): `(overlay_id, content_id)`. At most one
204 /// is shown at a time; moving the highlight or closing the menu clears
205 /// it. Distinct from the hover/focus tooltip paths — this one is a
206 /// `Manual`-dismiss child of the menu overlay so a single Escape closes
207 /// the menu (and cascades the tooltip) rather than only the tooltip.
208 highlight_tooltip: Option<(crate::overlay::OverlayId, WidgetId)>,
209 /// How the currently focused widget gained focus.
210 focus_origin: Option<crate::focus::FocusOrigin>,
211 /// Input-modality "focus-visible" state: `true` after keyboard input,
212 /// `false` after pointer input. Focus rings (e.g. `StandardItem`'s current
213 /// row) show only while this is `true`, the standard `:focus-visible`
214 /// behaviour — so a mouse click selects without a ring, and keyboard
215 /// navigation reveals it.
216 focus_visible: crate::signal::Signal<bool>,
217 /// Active focus-scope stack during build. A data view pushes its scope
218 /// (`begin_view_focus`) around its row loop so each row reads *its view's*
219 /// focus deterministically — independent of arena parenting, which may not
220 /// be wired yet while rows build (docked / virtualized content). Drives
221 /// focus-aware selection + focus rings in `StandardItem`.
222 view_focus_stack: Vec<crate::signal::Signal<bool>>,
223 /// Layout direction for RTL/LTR support.
224 layout_direction: crate::environment::LayoutDirection,
225 /// Animation scheduler for smooth animated state and signal transitions.
226 animation_scheduler: crate::animation::AnimationScheduler,
227 /// Weakly tracked animated values from both state and signal APIs.
228 animated_values: Vec<AnimatedRegistration>,
229 /// Registry of shader-driven animated quads (opt-in alternative to
230 /// `Signal<f32>::animate_looping` for decorative motion — progress
231 /// sweeps, sprite-atlas frame cycling, future pulse/shimmer). The
232 /// scheduler-style signal path stays for everything else. Per-slot
233 /// `AnimParams` are ticked and attached to every `RenderFrame`
234 /// produced by `render()` — the renderer reads them from there.
235 animated_quads: crate::animated_quad::AnimatedQuadRegistry,
236 /// Per-frame-effect scheduler. Owns the registry of widgets that
237 /// asked for a frame-tick subscription (Pulse, Cycle, …). Sits
238 /// alongside `animation_scheduler` and `animated_quads` as the
239 /// third visibility-aware motion source — they all consult the
240 /// same [`motion_visibility`](crate::motion_visibility) helpers.
241 /// After every `render()` the tree calls
242 /// `FrameTickScheduler::should_arm_frame_tick` and re-arms
243 /// `frame_tick_requested` if any subscriber's owner was painted
244 /// this frame.
245 pub(crate) frame_tick_scheduler: crate::frame_tick_scheduler::FrameTickScheduler,
246 /// Monotonic counter bumped at the start of each `render()` call.
247 /// Each widget's `last_painted_epoch` is set to this value whenever
248 /// the paint pass (or the cache-hit early-out) confirms the widget
249 /// intersects the window viewport. The animation scheduler uses it
250 /// to detect and pause animations for widgets that have scrolled
251 /// off-screen. Starts at `0`, which serves as the "never painted"
252 /// sentinel; tests that only call `layout()` see the gate bypass.
253 paint_epoch: u64,
254 /// Cached accessibility tree update, rebuilt only when something that
255 /// changes the AT tree has happened, not on every layout.
256 cached_a11y: Option<accesskit::TreeUpdate>,
257 /// Whether the accessibility tree needs rebuilding. Set by focus moves,
258 /// overlay changes, widget rebuilds, active↔dormant transitions,
259 /// `AccessibilityOnly` binding flips and `request_accessibility_update()`;
260 /// a plain relayout does not set it.
261 a11y_dirty: bool,
262 /// Snapshot of `shortcut_registry.version()` at the last
263 /// `sync_accessibility` call. When the live version differs the
264 /// AT cache is dirtied, so widgets that bound their announced
265 /// shortcut via `access_shortcut_id(id)` track user rebinds
266 /// without any explicit signaling from the settings UI.
267 last_synced_shortcut_version: u64,
268 /// Snapshot of `locale_signal` at the last `sync_accessibility`
269 /// call. When the locale differs the AT cache is dirtied, so
270 /// `access_label(tr!(...))` (stored as a locale-bound
271 /// `Prop<String>`) re-resolves into the announced node — even on a
272 /// same-direction switch that doesn't rebuild the composite.
273 last_synced_locale: Option<String>,
274 /// Reverse map from synthetic (widget-emitted) AccessKit NodeIds
275 /// to the WidgetId that owns them. Rebuilt on every full
276 /// accessibility walk. `handle_accessibility_actions` uses this
277 /// to route an `ActionRequest` targeting a TextRun child back
278 /// to the owning rich-text editor, since synthetic NodeIds
279 /// can't be decoded back to a WidgetId by value alone.
280 pub(crate) synthetic_parent_map: std::collections::HashMap<accesskit::NodeId, WidgetId>,
281 /// Cached full render frame — reused when no widget needs painting.
282 /// `Rc<RenderFrame>` rather than `RenderFrame` so cache-hit frames
283 /// cost an atomic refcount bump instead of a deep clone of every
284 /// draw-command Vec. `render()` uses `Rc::make_mut` to update
285 /// `anim_params` in place when the tree is the sole owner (the
286 /// common case — the caller usually drops the previous frame
287 /// before calling render() again).
288 cached_frame: Option<std::rc::Rc<RenderFrame>>,
289 /// Widget that has captured the pointer (receives all PointerMove/PointerUp
290 /// regardless of hit-test). Set via `EventContext::capture_pointer()`.
291 pointer_captured_by: Option<WidgetId>,
292 /// Strict ancestors of the captured widget that carry a drag/swipe
293 /// recognizer, armed on `PointerDown` so an ancestor drag can still start
294 /// while a descendant tap holds the capture (tap-vs-drag disambiguation
295 /// across the hit-path). Innermost-first. Drained when a drag latches or
296 /// the pointer sequence ends. See `arm_drag_observers`.
297 drag_observers: Vec<WidgetId>,
298 /// Current cursor selected by hover/interaction routing.
299 current_cursor: crate::widget::CursorIcon,
300 /// Delayed overlay requests (e.g., submenu hover-open delay).
301 pending_delayed_overlays: Vec<PendingDelayedOverlay>,
302 /// Reusable scratch buffer for active-id snapshots taken on hot
303 /// paths that mutate per-widget state inside the loop
304 /// (`tick_gestures_with_ops`, post-render dirty-bit clear,
305 /// post-layout `needs_layout` clear). Cleared and refilled on
306 /// every use via `WidgetArena::fill_active_ids`. Previously these
307 /// sites called the allocating `arena.active_ids()` per frame,
308 /// which `perf record` ranked at ~13 % of CPU on the
309 /// `widget_catalog --tab animations` scene.
310 active_ids_scratch: Vec<WidgetId>,
311 /// Widgets currently carrying a non-`None` `EventHandlers::gesture_arena`.
312 /// Updated on attach (`ensure_gesture_arena` install) and on
313 /// teardown (rebuild / destroy / handler-clear). Every per-frame
314 /// gesture pass (`tick_gestures_with_ops`, `next_gesture_deadline`)
315 /// iterates this set instead of every active widget — most active
316 /// widgets have `gesture_arena = None`, so the savings come from
317 /// not even visiting them. Filtered by `arena.is_active(id)` at
318 /// iteration time so dormant entries don't fire (a widget can be
319 /// dormant while still holding its handlers).
320 gesture_owners: std::collections::HashSet<WidgetId>,
321 /// OS-level accessibility preferences (high contrast, reduced motion, text scale).
322 prefers_high_contrast: bool,
323 prefers_reduced_motion: bool,
324 text_scale_factor: f64,
325 /// Host window HiDPI device scale (physical px per logical px), fed by
326 /// `teksilo-app` before each layout. Surfaced to widgets via
327 /// `LayoutContext::scale_factor`. The widget tree is otherwise fully
328 /// logical (the renderer applies this scale at the vertex stage); this is
329 /// the escape hatch for widgets that must size a device-pixel OS resource
330 /// (e.g. a `WebView`'s native subview). 1.0 in headless / test contexts.
331 device_scale_factor: f32,
332 /// Active drag-and-drop session, if any.
333 pub(crate) active_drag: Option<crate::drag_state::DragSession>,
334 /// Source widget of an in-flight OS (outbound) drag that escalated past
335 /// the window boundary. Set only on the window that *started* the drag.
336 /// The in-app `active_drag` session is torn down at escalation (the OS owns
337 /// the pointer); this remembers who started it so the eventual `DragEnded`
338 /// can fire the source's `on_drag_ended`.
339 pub(crate) outbound_drag_source: Option<WidgetId>,
340 /// True while *this* window currently holds the re-entered internal session
341 /// for an in-flight app-originated OS drag (the OS drag wandered back over
342 /// this window — possibly a different window than the source — and we
343 /// restored the original typed payload). Distinguishes that session from a
344 /// plain internal drag so leaving again re-stashes instead of starting a
345 /// second OS drag, and dropping doesn't double-fire `on_drag_ended`.
346 pub(crate) os_drag_reentered: bool,
347 /// Optional platform host for custom window chrome (set when the
348 /// application opts in via `WindowConfig::custom_chrome(true)`). Stored
349 /// here so that the root-builder closure has access during widget
350 /// construction; the same `Rc` is also held by `WindowManager` so it
351 /// outlives the widget tree if needed.
352 title_bar_host: Option<Rc<dyn crate::PlatformTitleBarHost>>,
353 /// App-level subscription state: registered event source adapter,
354 /// proxy poster, UI-side subscription callbacks. Default is empty;
355 /// teksilo-app installs a populated context when an event source is
356 /// registered on the builder.
357 pub(crate) app_context: Rc<crate::event_source::TreeAppContext>,
358 /// Active locale identifier. Cached for `Option<&str>` accessors; the
359 /// reactive source of truth is `locale_signal`. Both are updated in
360 /// lockstep by `set_locale`.
361 pub(crate) locale: Option<String>,
362 /// Reactive locale signal. Widgets and `LocalizedString` adapters bind to
363 /// this signal to react to locale changes; `set_locale` updates the signal
364 /// without rebuilding the widget tree.
365 pub(crate) locale_signal: crate::signal::Signal<Option<String>>,
366 /// Per-frame delta-seconds signal, advanced by `layout()` **only when
367 /// a widget has explicitly requested a frame** via `request_frame()`.
368 /// This preserves Teksilo's draw-when-needed model: idle trees stay
369 /// idle even if widgets have registered observers on this signal.
370 pub(crate) frame_tick: crate::signal::Signal<f32>,
371 /// Set by `request_frame()`; consumed by `advance_frame_tick()` on
372 /// the next `layout()`. Observers that need another tick after the
373 /// current one must re-request. Stored as `Rc<Cell>` so observers
374 /// fired from inside the layout pass (`ctx.effect` closures on
375 /// `frame_tick`) can chain-request without needing &mut access
376 /// to the tree — see `FrameRequestHandle`.
377 pub(crate) frame_tick_requested: std::rc::Rc<std::cell::Cell<bool>>,
378 /// Debug-only re-entrancy flag: `true` while a focus-change dispatch
379 /// (`FocusGained` / `FocusLost` handlers) is running. Threaded into each
380 /// `EventContext` so `open_window` / `focus_window` can warn if a handler
381 /// changes context merely because a control gained focus (WCAG 3.2.1). A
382 /// shared `Rc<Cell<bool>>` (like `frame_tick_requested`) so the flag is
383 /// readable from an `EventContext` that holds no `&mut` to the tree.
384 pub(crate) in_focus_dispatch: std::rc::Rc<std::cell::Cell<bool>>,
385 /// Shared "accessibility re-walk requested" flag. Set via
386 /// [`request_accessibility_update`](Self::request_accessibility_update)
387 /// (or its `BuildContext` / `EventContext` wrappers) and drained at the
388 /// top of [`sync_accessibility`](Self::sync_accessibility) into
389 /// `a11y_dirty`. A relayout no longer re-walks the AT tree on its own, so
390 /// widgets that restructure their subtree in an AT-affecting way (e.g.
391 /// `SceneView` materialising / destroying scene widgets) need this lever.
392 /// `Rc<Cell>` so the shared `&self` paths can toggle it like
393 /// `frame_tick_requested`.
394 pub(crate) a11y_update_requested: std::rc::Rc<std::cell::Cell<bool>>,
395 /// Delayed frame wake-up deadline. Widgets that need to schedule
396 /// a future frame without pumping at full framerate (caret blink,
397 /// etc.) store the target instant here via
398 /// [`wake_at_handle`](Self::wake_at_handle). `next_timer_deadline`
399 /// rolls it into the event loop's WaitUntil; when reached, the
400 /// next `layout()` automatically re-arms `frame_tick_requested`
401 /// so the frame-tick effects run on the wake-up pass.
402 pub(crate) pending_wake_at: std::rc::Rc<std::cell::Cell<Option<std::time::Instant>>>,
403 /// One-shot post-mount actions enqueued during `build()` via
404 /// [`BuildContext::run_after_mount`](crate::BuildContext::run_after_mount), drained by the app loop (and by
405 /// tests) through [`WidgetTree::run_mount_actions`] with a real
406 /// [`EventContext`] — the only place a widget
407 /// can read the OS parent handle / app-state / poster together after it is
408 /// mounted. Used by widgets that own a native resource needing a window
409 /// handle to initialise (a `WebView`'s engine subview).
410 pub(crate) pending_mount_actions: Vec<Box<dyn FnOnce(&mut crate::widget::EventContext)>>,
411 /// Wall-clock time of the previous `layout()` call (for delta computation).
412 pub(crate) last_frame_time: Option<std::time::Instant>,
413 /// Set by [`EventContext::close_window`] during dispatch; drained
414 /// by the application event loop after each event via
415 /// [`WidgetTree::take_close_window_request`]. A *guarded* close
416 /// request — the app routes it through the window's close guard.
417 pub(crate) close_window_requested: bool,
418 /// Set by [`EventContext::close_window_forced`] during dispatch;
419 /// drained via [`WidgetTree::take_force_close_request`]. An
420 /// *unconditional* close request that bypasses the window's close
421 /// guard.
422 pub(crate) force_close_requested: bool,
423 /// Raised by [`EventContext::set_locale`] during dispatch; drained by
424 /// the application event loop (see
425 /// `WindowManager::drain_pending_locale_requests`) so the switch can be
426 /// routed through the `I18nManager` (active locale + version signal +
427 /// RTL direction). `WidgetTree::set_locale` alone would only update the
428 /// tree's local locale signal — the i18n thread-local would stay put
429 /// and `tr!` lookups would not re-resolve.
430 pub(crate) pending_locale_request: Option<String>,
431 /// Raised by [`EventContext::set_theme`] during dispatch; drained by
432 /// the application event loop (see
433 /// `WindowManager::drain_pending_theme_requests`) so the switch is
434 /// routed through `WindowManager::set_theme`, which fans the new theme
435 /// out to *every* window. Applying via `WidgetTree::set_theme` inline
436 /// would only re-theme the originating window — the rest of the app
437 /// would stay on the old theme. Mirrors `pending_locale_request`.
438 pub(crate) pending_theme_request: Option<crate::styles::Theme>,
439 /// Raised by [`EventContext::follow_system_theme`] during dispatch;
440 /// drained by the application event loop (see
441 /// `WindowManager::drain_pending_follow_system_requests`), which switches
442 /// the app to `ThemeMode::Native` and recomputes the theme from current
443 /// OS colours. Mirrors `pending_theme_request`.
444 pub(crate) pending_follow_system_request: bool,
445 /// Raised by [`EventContext::set_text_scale`] during dispatch; drained by
446 /// the application event loop (see
447 /// `WindowManager::drain_pending_text_scale_requests`) so the change is
448 /// routed through `WindowManager::set_text_scale`, fanning the new factor
449 /// out to *every* window. Mirrors `pending_theme_request`.
450 pub(crate) pending_text_scale_request: Option<f32>,
451 /// Monotonic version counter bumped after every *real* accessibility
452 /// rebuild in [`Self::sync_accessibility`] (cache hits don't bump).
453 /// Mirror of [`crate::shortcut::ShortcutRegistry::version`]: an
454 /// automation / test harness can poll it to know whether the AT tree
455 /// changed without diffing the whole `TreeUpdate`.
456 at_version: crate::signal::Signal<u64>,
457 /// The framework's own live regions, one per politeness level. See
458 /// [`crate::announcer`]: each owns a reserved AccessKit node and cycles it
459 /// in and out of the filtered tree, which is the only mechanism all three
460 /// platform adapters agree announces.
461 announcer_polite: crate::announcer::Announcer,
462 announcer_assertive: crate::announcer::Announcer,
463 /// Ring buffer of captured live-region announcements (see
464 /// [`crate::accessibility::Announcement`]). Filled by a `&mut self`
465 /// post-pass in `sync_accessibility` that diffs `Live::{Polite,
466 /// Assertive}` nodes against `automation_last_text`. Capped at
467 /// [`AUTOMATION_ANNOUNCE_CAP`]; drained by
468 /// [`Self::announcements_since`].
469 automation_announcements: std::collections::VecDeque<crate::accessibility::Announcement>,
470 /// Monotonic sequence number for the next announcement (starts at 0;
471 /// the first announcement is assigned `1`).
472 automation_announce_seq: u64,
473 /// Last announced text per live-region node, so a re-sync only emits a
474 /// new announcement when the text actually changes. Pruned each pass
475 /// to the set of currently-present live nodes, so a node that
476 /// disappears and reappears with the same text re-announces.
477 automation_last_text: std::collections::HashMap<accesskit::NodeId, String>,
478 /// Whether the `WidgetEvent::AccessAction` currently being dispatched was
479 /// consumed by a handler. Written by the dispatcher's `AccessAction` arm,
480 /// read (and reset) by [`Self::dispatch_access_action`], which is the only
481 /// caller that can answer "did anything happen?" to its own caller.
482 ///
483 /// A side channel because `dispatch_event_with_ops` returns `()` for every
484 /// event kind, and routing AT actions through the *same* path as everything
485 /// else is load-bearing (it is what lets an action open a window). The
486 /// alternative — reporting success whenever a live widget merely *existed*
487 /// at the target — is how an unhandled action came to look like a
488 /// successful one to every automation client.
489 access_action_handled: bool,
490 /// The `WindowState` for this tree's hosting window. Populated
491 /// by the app-level window manager when the tree is registered;
492 /// `None` for standalone trees. Cloned into every `EventContext`
493 /// and `BuildContext` so widgets can bind to the current window's
494 /// signals via `ctx.window()`.
495 pub(crate) window_state: Option<crate::window::WindowState>,
496}
497
498/// Maximum number of live-region [`crate::accessibility::Announcement`]s
499/// the [`WidgetTree`] retains. The oldest is evicted when the buffer is
500/// full; `announcements_since` only ever returns the retained tail.
501const AUTOMATION_ANNOUNCE_CAP: usize = 256;
502
503/// How long the shortened reshow delay stays active after the last tooltip
504/// dismisses. Long enough to cover moving between adjacent toolbar icons;
505/// short enough that a later, deliberate hover still pays the full initial
506/// delay. Not a theme token — it is session bookkeeping, not a visual feel.
507const TOOLTIP_SESSION_GRACE: std::time::Duration = std::time::Duration::from_millis(1000);
508
509/// Number of visible steps a sticky-on-dwell tooltip's promotion window is
510/// divided into.
511///
512/// The tree uses this only to decide *how often to wake* while a dwell is
513/// running — one redraw per step boundary rather than a free-run — but it must
514/// match the step count the content widget actually renders, or the indicator
515/// would advance on a different beat from the wake-ups driving it.
516/// `teksilo-widgets`' `DWELL_STEPS` is pinned to this value by a compile-time
517/// assertion; the per-step *duration* is derived from each entry's own
518/// `sticky_after`, so a caller that picks a non-default promotion window still
519/// gets correctly-spaced wake-ups.
520pub const TOOLTIP_DWELL_STEPS: u32 = 4;
521
522/// Max pointer travel (logical px) from the hover-origin before a pending
523/// tooltip timer restarts. Mirrors Windows hover-tracking slop
524/// (`SPI_GETMOUSEHOVERWIDTH` / height, typically ~4 px): the tip waits for a
525/// *paused* pointer, not merely "entered the bounds."
526const TOOLTIP_STATIONARY_SLOP: f32 = 4.0;
527
528/// A tooltip attachment managed by the WidgetTree.
529struct TooltipEntry {
530 anchor_id: WidgetId,
531 content_id: WidgetId,
532 /// The widget whose accessibility node should carry this tooltip's
533 /// description, which is not always the node the overlay hangs off.
534 ///
535 /// A composing control anchors the *overlay* on an inner chrome node it
536 /// built -- the thing with the right bounds to open a tooltip against --
537 /// while its role, its name and its focusability live on its own outer
538 /// node. A description on the inner one is a description an assistive
539 /// technology never reads, because it never lands there.
540 ///
541 /// Recorded by `BuildContext`'s `attach_tooltip*` wrappers as the widget
542 /// that was building at the time. Defaults to `anchor_id`, which is both
543 /// the historic behaviour and the right answer for a widget that anchors
544 /// its tooltip on itself.
545 ///
546 /// Naming an owner is a *claim*, not a guarantee: the accessibility walk
547 /// honours it only where exactly one tooltip claims that node. See
548 /// `WidgetTree::build_accessibility_recursive`.
549 description_owner_id: WidgetId,
550 delay: std::time::Duration,
551 /// Simulated hover start (for deterministic tests via advance_time).
552 hover_start: Option<std::time::Instant>,
553 /// Real hover start (for windowed apps via layout).
554 real_hover_start: Option<std::time::Instant>,
555 /// Pointer position when the current pending hover started. Used to
556 /// restart the delay if the pointer keeps moving inside the anchor
557 /// (stationary-pointer intent filter).
558 hover_origin: Option<teksilo_canvas::Point>,
559 overlay_id: Option<crate::overlay::OverlayId>,
560 /// When set, the tooltip auto-promotes to "sticky" after this
561 /// much elapsed time since it was shown. The entry stays in the
562 /// table and is just flagged sticky — the difference is that
563 /// pointer-leave no longer dismisses it and the overlay's
564 /// dismiss behavior is swapped to `EscapeOrClickOutside`.
565 sticky_after: Option<std::time::Duration>,
566 /// True when the dwell timer reached `sticky_after`. Causes
567 /// `tooltip_pointer_leave` to skip the dismissal and lets the
568 /// overlay survive pointer-leave until the user explicitly
569 /// dismisses it via Escape or a click outside.
570 is_sticky: bool,
571 /// When the overlay was shown (simulated). Together with
572 /// `sticky_after` drives auto-promotion.
573 shown_at_sim: Option<std::time::Instant>,
574 /// When the overlay was shown (real).
575 shown_at_real: Option<std::time::Instant>,
576 /// Optional shared sink the tooltip widget can read from to
577 /// compute its own dwell progress. Mirrors `shown_at_real`:
578 /// set on show, cleared on dismissal. Used by `RichTooltipWidget`
579 /// to drive the dwell indicator without relying on a fragile
580 /// paint-gap heuristic.
581 shown_at_sink: Option<std::rc::Rc<std::cell::Cell<Option<std::time::Instant>>>>,
582 /// True when the tooltip was shown by the keyboard-focus path
583 /// rather than the pointer-hover path. Focus-promoted tooltips
584 /// dismiss when focus moves outside both the anchor and the
585 /// tooltip content subtree (preventing accumulation as the user
586 /// Tabs through a form); pointer-dwelled stickies survive
587 /// focus changes and only dismiss via Escape or click-outside.
588 promoted_by_focus: bool,
589 /// Set while this entry's pending delay was started by keyboard focus
590 /// rather than by the pointer. Decides, at show time, that the surface
591 /// dismisses on `Escape`/click-outside rather than on pointer-leave (there
592 /// is no pointer in the story), and that it counts as focus-shown.
593 armed_by_focus: bool,
594 /// Set when the tip was dismissed while the focus that summoned it is
595 /// still inside its anchor — i.e. Escape on a focus-promoted tooltip.
596 ///
597 /// Escape restores focus to the anchor, and that restore runs the ordinary
598 /// focus path, which ends in `tooltip_focus_enter`. Without this flag the
599 /// tip the user just dismissed re-opens on the same keystroke, because
600 /// `dormant_dismissed_content` has already cleared `overlay_id` by then and
601 /// the entry looks eligible again. Cleared when focus genuinely leaves the
602 /// anchor (`tooltip_focus_leave_outside`), so Tabbing away and back
603 /// re-summons it normally. The hover path needs no equivalent: a stationary
604 /// pointer never re-fires `tooltip_pointer_enter`.
605 suppressed_until_focus_leaves: bool,
606 /// Where the tooltip opens relative to its anchor. `Below` (default)
607 /// for the common case; `Side` for anchors stacked vertically (menu
608 /// items, a vertical tab strip, list/tree rows) so the tooltip does
609 /// not cover the next sibling. Consulted at show time in both the
610 /// hover (`process_tooltips_impl`) and focus (`tooltip_focus_enter`)
611 /// paths.
612 placement: crate::overlay::TooltipPlacement,
613}
614
615/// A delayed overlay request (e.g., submenu hover-open delay).
616struct PendingDelayedOverlay {
617 request: crate::overlay::OverlayRequest,
618 delay: std::time::Duration,
619 focus_target: Option<WidgetId>,
620 /// When the request was made (real time, for windowed apps).
621 real_requested_at: std::time::Instant,
622 /// When the request was made (simulated time, for tests).
623 sim_requested_at: std::time::Instant,
624}
625
626impl WidgetTree {
627 pub fn new() -> Self {
628 let initial_theme = crate::presets::intui::light();
629 // One signal, shared: the field the tree writes and the registry the
630 // application reads must be the same one, or a host mirroring "is the
631 // caret in a text widget" would never see focus move.
632 let focused_signal = crate::signal::Signal::new(None);
633 Self {
634 arena: WidgetArena::new(),
635 theme: initial_theme.clone(),
636 theme_signal: crate::signal::Signal::new(initial_theme.clone()),
637 user_text_scale: 1.0,
638 effective_theme: initial_theme,
639 effective_text_scale: 1.0,
640 text_scale_signal: crate::signal::Signal::new(1.0),
641 // Starts active: winit may not send `Focused(true)` for the first
642 // window, so a window must not be born inactive (caret hidden,
643 // selection muted) before the first focus event arrives.
644 window_active_signal: crate::signal::Signal::new(true),
645 text_backend: None,
646 focused: None,
647 focused_signal: focused_signal.clone(),
648 hovered: None,
649 hovered_signal: crate::signal::Signal::new(None),
650 focus_visible: crate::signal::Signal::new(false),
651 view_focus_stack: Vec::new(),
652 last_pointer_position: None,
653 pending_focus_restore: None,
654 last_proposal: SizeProposal::exact(800.0, 600.0),
655 pending_modal_requests: Vec::new(),
656 pending_modal_dismissal: false,
657 shortcut_registry: crate::shortcut::ShortcutRegistry::new(),
658 pending_intents: Vec::new(),
659 global_actions: Vec::new(),
660 text_surfaces: crate::text_surface::TextSurfaces::new(focused_signal.clone()),
661 key_capture: None,
662 binding_registry: crate::binding::BindingRegistry::new(),
663 idle_queue: crate::idle::IdleQueue::new(),
664 sim_clock: std::time::Instant::now(),
665 sim_driven: false,
666 focus_origin: None,
667 overlay_manager: crate::overlay::OverlayManager::new(),
668 tooltips: Vec::new(),
669 tooltip_session_until_sim: None,
670 tooltip_session_until_real: None,
671 highlight_tooltip: None,
672 layout_direction: crate::environment::LayoutDirection::default(),
673 animation_scheduler: crate::animation::AnimationScheduler::new(),
674 animated_values: Vec::new(),
675 animated_quads: crate::animated_quad::AnimatedQuadRegistry::new(),
676 frame_tick_scheduler: crate::frame_tick_scheduler::FrameTickScheduler::new(),
677 paint_epoch: 0,
678 cached_a11y: None,
679 a11y_dirty: true,
680 last_synced_shortcut_version: 0,
681 last_synced_locale: None,
682 synthetic_parent_map: std::collections::HashMap::new(),
683 cached_frame: None,
684 pointer_captured_by: None,
685 drag_observers: Vec::new(),
686 current_cursor: crate::widget::CursorIcon::Default,
687 pending_delayed_overlays: Vec::new(),
688 active_ids_scratch: Vec::new(),
689 gesture_owners: std::collections::HashSet::new(),
690 prefers_high_contrast: false,
691 prefers_reduced_motion: false,
692 text_scale_factor: 1.0,
693 device_scale_factor: 1.0,
694 active_drag: None,
695 outbound_drag_source: None,
696 os_drag_reentered: false,
697 title_bar_host: None,
698 app_context: Rc::new(crate::event_source::TreeAppContext::empty()),
699 locale: None,
700 locale_signal: crate::signal::Signal::new(None),
701 frame_tick: crate::signal::Signal::new(0.0_f32),
702 frame_tick_requested: std::rc::Rc::new(std::cell::Cell::new(false)),
703 in_focus_dispatch: std::rc::Rc::new(std::cell::Cell::new(false)),
704 a11y_update_requested: std::rc::Rc::new(std::cell::Cell::new(false)),
705 pending_wake_at: std::rc::Rc::new(std::cell::Cell::new(None)),
706 pending_mount_actions: Vec::new(),
707 last_frame_time: None,
708 close_window_requested: false,
709 force_close_requested: false,
710 pending_locale_request: None,
711 pending_theme_request: None,
712 pending_follow_system_request: false,
713 pending_text_scale_request: None,
714 at_version: crate::signal::Signal::new(0),
715 announcer_polite: crate::announcer::Announcer::new(
716 crate::announcer::Politeness::Polite,
717 ),
718 announcer_assertive: crate::announcer::Announcer::new(
719 crate::announcer::Politeness::Assertive,
720 ),
721 automation_announcements: std::collections::VecDeque::new(),
722 automation_announce_seq: 0,
723 automation_last_text: std::collections::HashMap::new(),
724 access_action_handled: false,
725 window_state: None,
726 }
727 }
728
729 /// Construct an [`EventContext`]
730 /// pre-populated with the tree's app-state registry, hosting
731 /// `WindowState`, and a `&mut dyn WindowOps` handle so handlers
732 /// can synchronously reach the multi-window API. Used by every
733 /// dispatch site.
734 pub(crate) fn make_event_context<'ops>(
735 &self,
736 ops: &'ops mut dyn crate::window::WindowOps,
737 ) -> crate::widget::EventContext<'ops> {
738 let drag_is_external = self.active_drag.as_ref().is_some_and(|d| d.is_external);
739 // Read-only snapshot of tree query state that handlers may
740 // need synchronously. Today this carries the last pointer
741 // position and a (content_id, bounds) slice of open overlays
742 // — both read by the safe-triangle submenu hover gate.
743 let overlay_snapshot: Vec<(crate::widget_id::WidgetId, teksilo_canvas::Rect)> = self
744 .overlay_manager
745 .active_content_ids()
746 .into_iter()
747 .filter_map(|cid| {
748 self.overlay_manager
749 .bounds_for_content(cid)
750 .map(|r| (cid, r))
751 })
752 .collect();
753 crate::widget::EventContext::new()
754 .with_app_context(self.app_context.clone())
755 .with_window_context(ops, self.window_state.clone())
756 .with_drag_external(drag_is_external)
757 .with_query_snapshot(self.last_pointer_position, overlay_snapshot)
758 .with_layout_direction(self.layout_direction)
759 .with_window_active(self.is_window_active())
760 .with_focus_dispatch_flag(self.in_focus_dispatch.clone())
761 }
762
763 /// Run a closure with a fresh [`EventContext`] anchored at this
764 /// tree, then collect any pending operations queued through the
765 /// context (intents, modal requests, frame requests, idle
766 /// callbacks…) so they take effect on the next event-loop tick.
767 ///
768 /// Used by the `teksilo-app` event-loop dispatcher to deliver
769 /// async-result callbacks (file dialogs, future background
770 /// tasks) on the main thread with full handler-equivalent
771 /// semantics. There is no source widget for app-level events,
772 /// so intents are anchored at the tree's first root id (or
773 /// silently dropped when the tree is empty).
774 pub fn run_with_event_context<F>(&mut self, ops: &mut dyn crate::window::WindowOps, f: F)
775 where
776 F: FnOnce(&mut crate::widget::EventContext),
777 {
778 let mut ctx = self.make_event_context(ops);
779 f(&mut ctx);
780 let anchor = self.arena.roots().first().copied();
781 if let Some(anchor_id) = anchor {
782 self.collect_from_ctx(ctx, anchor_id);
783 } else {
784 // Empty tree — nothing to anchor intents on. Drop ctx;
785 // its only side effects (frame requests, cursor) are
786 // not meaningful for an empty tree.
787 drop(ctx);
788 }
789 }
790
791 /// Enqueue a one-shot action to run with a real
792 /// [`EventContext`] after the current build,
793 /// once the tree is mounted under its window. Used via
794 /// [`BuildContext::run_after_mount`](crate::BuildContext::run_after_mount). Drained by
795 /// [`Self::run_mount_actions`].
796 pub(crate) fn queue_mount_action(
797 &mut self,
798 action: Box<dyn FnOnce(&mut crate::widget::EventContext)>,
799 ) {
800 self.pending_mount_actions.push(action);
801 }
802
803 /// Whether any post-mount actions are waiting to run.
804 pub fn has_pending_mount_actions(&self) -> bool {
805 !self.pending_mount_actions.is_empty()
806 }
807
808 /// Drain and run every queued post-mount action with a fresh
809 /// [`EventContext`] built over `ops`. The app
810 /// loop calls this each iteration with a real `WindowOps` sink (so
811 /// `ctx.parent_window_handle()` resolves); headless tests call it with a
812 /// `NoopWindowOps`. Actions enqueued *by* an action (rare) are left for the
813 /// next drain rather than run re-entrantly.
814 pub fn run_mount_actions(&mut self, ops: &mut dyn crate::window::WindowOps) {
815 if self.pending_mount_actions.is_empty() {
816 return;
817 }
818 let actions = std::mem::take(&mut self.pending_mount_actions);
819 self.run_with_event_context(ops, move |ctx| {
820 for action in actions {
821 action(ctx);
822 }
823 });
824 }
825
826 /// Attach the [`WindowState`](crate::window::WindowState) for this
827 /// tree's hosting window. Called by `WindowManager::create_window`.
828 pub fn set_window_state(&mut self, state: crate::window::WindowState) {
829 self.window_state = Some(state);
830 }
831
832 pub fn window_state(&self) -> Option<&crate::window::WindowState> {
833 self.window_state.as_ref()
834 }
835
836 /// Clone the shared "frame requested" flag. Widgets stash this
837 /// in their state and call `.set(true)` from inside frame-tick
838 /// closures to chain-request another frame without needing
839 /// mutable access to the tree. See `RichTextEditor` for the
840 /// canonical use (caret blink, drag-select auto-scroll).
841 pub fn frame_request_handle(&self) -> std::rc::Rc<std::cell::Cell<bool>> {
842 self.frame_tick_requested.clone()
843 }
844
845 /// Clone the shared wake-at deadline cell. Widgets stash this in
846 /// their state and call `request_wake_at` from frame-tick effects
847 /// to schedule a one-shot deadline without keeping the event loop
848 /// in `Poll` mode. On the next `layout()` at or past the deadline,
849 /// the tree auto-arms `frame_tick_requested` so the effect runs on
850 /// the wake-up pass. Canonical use: the rich text editor's caret
851 /// blink schedules a 500 ms wake instead of pumping every frame.
852 pub fn wake_at_handle(&self) -> std::rc::Rc<std::cell::Cell<Option<std::time::Instant>>> {
853 self.pending_wake_at.clone()
854 }
855
856 /// Schedule a one-shot frame wake at `at`. Merges with any existing
857 /// deadline — keeps the earlier instant so the most urgent wake
858 /// wins.
859 pub fn request_wake_at(&self, at: std::time::Instant) {
860 let current = self.pending_wake_at.get();
861 let merged = match current {
862 Some(existing) if existing <= at => existing,
863 _ => at,
864 };
865 self.pending_wake_at.set(Some(merged));
866 }
867
868 /// The per-frame delta-seconds signal. Observers fire **only on frames
869 /// the tree was asked to pump** via [`request_frame`](Self::request_frame);
870 /// merely observing the signal does not keep the event loop awake.
871 /// See `BuildContext::frame_tick` for widget-side access and
872 /// `BuildContext::request_frame` for the opt-in request side.
873 pub fn frame_tick(&self) -> crate::signal::Signal<f32> {
874 self.frame_tick.clone()
875 }
876
877 /// Ask the tree to pump exactly one more frame. `needs_redraw()`
878 /// returns true until the request is consumed by the next
879 /// `layout()` call, which fires the per-frame tick signal and
880 /// clears the flag. Observers that still need more frames (drag
881 /// auto-scroll, caret blink, pending document events) must call
882 /// `request_frame()` again from inside their tick closure.
883 ///
884 /// Takes `&self` on purpose: widget handlers and per-frame effects
885 /// receive a shared reference to the tree via `EventContext` /
886 /// `BuildContext`, and the request flag is a `Cell` specifically so
887 /// those shared paths can toggle it without ceremony.
888 pub fn request_frame(&self) {
889 self.frame_tick_requested.set(true);
890 }
891
892 /// Request that the AccessKit tree be re-walked on the next
893 /// [`sync_accessibility`](Self::sync_accessibility). Takes `&self` (the
894 /// flag is a `Cell`) so handlers and `build()` closures reaching the tree
895 /// through a shared reference can request a re-walk without `&mut` access.
896 /// The drain at the top of `sync_accessibility` flips `a11y_dirty`.
897 pub fn request_accessibility_update(&self) {
898 self.a11y_update_requested.set(true);
899 }
900
901 /// Speak `message` to the screen reader, politely.
902 ///
903 /// For anything the user needs told that is not the name of a widget: a
904 /// completed action, a changed count, the result of an undo. The message is
905 /// delivered on the next two accessibility syncs, which this schedules.
906 ///
907 /// Prefer `EventContext::announce` inside a handler and
908 /// `BuildContext::announce` inside a build; this is the tree-level entry
909 /// point both of those reach.
910 ///
911 /// Takes `impl Into<String>`, so `tr!(…)` works directly. See
912 /// [`crate::announcer`] for why it is a `String` and not a
913 /// `LocalizedString`, and for why an announcement beside a `Toast` says
914 /// everything twice.
915 pub fn announce(&mut self, message: impl Into<String>) {
916 self.announce_with(message, crate::announcer::Politeness::Polite);
917 }
918
919 /// Speak `message` to the screen reader at the given urgency.
920 ///
921 /// [`Politeness::Assertive`](crate::announcer::Politeness::Assertive)
922 /// interrupts whatever is being spoken; reserve it for something the user
923 /// must not miss and cannot recover by re-reading the screen.
924 pub fn announce_with(
925 &mut self,
926 message: impl Into<String>,
927 politeness: crate::announcer::Politeness,
928 ) {
929 match politeness {
930 crate::announcer::Politeness::Polite => self.announcer_polite.push(message.into()),
931 crate::announcer::Politeness::Assertive => {
932 self.announcer_assertive.push(message.into())
933 }
934 }
935 // Two syncs are needed per message (expose, then retract), and a sync
936 // only happens on a frame. Without both of these a message queued from
937 // a handler that changed nothing visible would sit unspoken until
938 // something else happened to redraw.
939 self.request_accessibility_update();
940 self.request_frame();
941 }
942
943 /// Clone the shared "accessibility re-walk requested" flag, for the same
944 /// stash-and-toggle pattern as [`frame_request_handle`](Self::frame_request_handle).
945 pub fn a11y_request_handle(&self) -> std::rc::Rc<std::cell::Cell<bool>> {
946 self.a11y_update_requested.clone()
947 }
948
949 /// Whether a frame was explicitly requested. Exposed for tests and
950 /// for the event-loop driver that decides when to schedule the next
951 /// wake-up.
952 pub fn frame_requested(&self) -> bool {
953 self.frame_tick_requested.get()
954 }
955
956 /// The next wake-up deadline for the per-frame-effect path, or
957 /// `None` when no per-frame effect is armed.
958 ///
959 /// This is the **60 Hz cap** for continuous per-frame animations
960 /// (`Pulse`, caret blink, drag auto-scroll, `--cycle` drivers). The
961 /// per-frame-effect path used to force `ControlFlow::Poll`, which
962 /// free-runs at the display's refresh rate — so on a 300 Hz panel a
963 /// single `Pulse`/`Cycle` rendered at 300 fps (measured ~45 % CPU) for
964 /// motion that looks identical at 60 fps. Routing it through a fixed
965 /// 16.667 ms deadline (folded into
966 /// [`next_timer_deadline`](Self::next_timer_deadline)) makes it pace at
967 /// 60 Hz regardless of refresh rate, matching the signal-tween
968 /// [`AnimationScheduler`](crate::animation::AnimationScheduler) and
969 /// shader-quad [`AnimatedQuadRegistry`](crate::animated_quad::AnimatedQuadRegistry),
970 /// which already share the same interval.
971 ///
972 /// A **throttled** subscriber (registered via
973 /// [`FrameTickScheduler::subscribe_throttled`](crate::frame_tick_scheduler::FrameTickScheduler::subscribe_throttled)
974 /// — e.g. `Cycle`, whose visible child only changes once per period)
975 /// stretches the deadline to its own interval: the loop then sleeps to
976 /// the period instead of rendering identical 60 fps frames in between.
977 /// The interval used is the **minimum across all currently-visible
978 /// subscribers**, so a `Cycle` next to a `Pulse` still ticks at 60 Hz
979 /// while a lone `Cycle` sleeps to its period. Raw `request_frame`
980 /// consumers with no subscription fall back to 60 Hz.
981 ///
982 /// Paces from `last_frame_time` so the cadence is drift-free; before
983 /// the first render it fires on the next loop turn.
984 pub fn frame_tick_deadline(&self) -> Option<std::time::Instant> {
985 // 60 Hz fallback for raw `request_frame` consumers (no subscriber).
986 const DEFAULT_INTERVAL: std::time::Duration = std::time::Duration::from_micros(16_667);
987 if !self.frame_tick_requested.get() {
988 return None;
989 }
990 let interval = self
991 .frame_tick_scheduler
992 .min_visible_interval(&self.arena, self.paint_epoch)
993 .unwrap_or(DEFAULT_INTERVAL);
994 Some(match self.last_frame_time {
995 Some(prev) => prev + interval,
996 None => std::time::Instant::now(),
997 })
998 }
999
1000 /// Subscribe `owner` to the per-frame-effect scheduler. The
1001 /// returned [`FrameTickSubscription`](crate::frame_tick_scheduler::FrameTickSubscription)
1002 /// is an RAII guard — drop it (typically by replacing the field on
1003 /// the owning widget on rebuild, or letting the widget's `Drop`
1004 /// run) to remove the subscription. While the guard is alive, the
1005 /// tree will keep arming `frame_tick_requested` after every render
1006 /// in which `owner` was painted, and stop on frames where it
1007 /// wasn't — so a subscribed widget hidden inside a non-selected
1008 /// `Switcher` branch contributes zero idle frames.
1009 ///
1010 /// Apps should not call this directly — use
1011 /// [`BuildContext::subscribe_frame_tick`](crate::build_context::BuildContext::subscribe_frame_tick)
1012 /// from inside `Widget::build`.
1013 pub fn subscribe_frame_tick(
1014 &self,
1015 owner: WidgetId,
1016 ) -> crate::frame_tick_scheduler::FrameTickSubscription {
1017 self.frame_tick_scheduler.subscribe(owner)
1018 }
1019
1020 /// Like [`subscribe_frame_tick`](Self::subscribe_frame_tick), but the
1021 /// owner only needs to wake **at most once per `interval`** while
1022 /// visible. Same visibility gate; between wakes the event loop sleeps
1023 /// to the interval deadline instead of rendering identical 60 fps
1024 /// frames. Use for effects whose visible output changes far less often
1025 /// than 60 Hz — e.g. `Cycle`'s once-per-period index advance.
1026 ///
1027 /// Apps should not call this directly — use
1028 /// [`BuildContext::subscribe_frame_tick_throttled`](crate::build_context::BuildContext::subscribe_frame_tick_throttled)
1029 /// from inside `Widget::build`.
1030 pub fn subscribe_frame_tick_throttled(
1031 &self,
1032 owner: WidgetId,
1033 interval: std::time::Duration,
1034 ) -> crate::frame_tick_scheduler::FrameTickSubscription {
1035 self.frame_tick_scheduler
1036 .subscribe_throttled(owner, interval)
1037 }
1038
1039 /// Advance the frame tick signal when (and only when) a frame was
1040 /// requested. Called by `layout()` before the scheduler tick so the
1041 /// per-frame observers fire on the same frame they asked for.
1042 pub(crate) fn advance_frame_tick(&mut self, now: std::time::Instant) {
1043 if !self.frame_tick_requested.get() {
1044 self.last_frame_time = Some(now);
1045 return;
1046 }
1047 self.frame_tick_requested.set(false);
1048 let delta = match self.last_frame_time {
1049 Some(prev) => {
1050 let d = now.saturating_duration_since(prev).as_secs_f32();
1051 // Clamp absurd deltas (pause/breakpoint) so observers never see a spike.
1052 d.clamp(0.0, 0.1)
1053 }
1054 None => 0.0,
1055 };
1056 self.last_frame_time = Some(now);
1057 self.frame_tick.set(delta);
1058 }
1059
1060 /// Replace the per-tree app context. Called by `teksilo-app` when
1061 /// constructing a window so the widget tree can reach the registered
1062 /// event source adapter and post subscription events through the
1063 /// event-loop proxy.
1064 pub fn set_app_context(&mut self, app_context: Rc<crate::event_source::TreeAppContext>) {
1065 self.app_context = app_context;
1066 }
1067
1068 /// Get the per-tree app context. Used by `BuildContext::subscribe_event`
1069 /// and by the event-loop handler when dispatching incoming
1070 /// `AppEvent::SubscriptionEvent`.
1071 pub fn app_context(&self) -> &Rc<crate::event_source::TreeAppContext> {
1072 &self.app_context
1073 }
1074
1075 /// Switch the tree-level locale at runtime.
1076 ///
1077 /// Updates `locale_signal` (a reactive `Signal<Option<String>>`) and marks
1078 /// all widgets dirty for relayout and repaint. Widgets are **not** rebuilt:
1079 /// per-string reactivity flows through `LocalizedString::to_signal()` which
1080 /// observes the teksilo-i18n manager, and anything else that depends on the
1081 /// tree-level locale can bind to `locale_signal()`.
1082 pub fn set_locale(&mut self, locale: String) {
1083 if self.locale.as_deref() == Some(locale.as_str()) {
1084 return;
1085 }
1086 let new = Some(locale);
1087 self.locale = new.clone();
1088 self.locale_signal.set(new);
1089 self.arena.mark_all_dirty();
1090 }
1091
1092 /// Currently active locale identifier, if any.
1093 pub fn locale(&self) -> Option<&str> {
1094 self.locale.as_deref()
1095 }
1096
1097 /// Reactive handle on the current locale. Mirrors `locale()` but updates
1098 /// observers when `set_locale` is called.
1099 pub fn locale_signal(&self) -> &crate::signal::Signal<Option<String>> {
1100 &self.locale_signal
1101 }
1102
1103 fn pointer_inside_overlay_region(
1104 &self,
1105 overlay_id: crate::overlay::OverlayId,
1106 position: Point,
1107 ) -> bool {
1108 let Some(overlay) = self
1109 .overlay_manager
1110 .stack
1111 .iter()
1112 .find(|overlay| overlay.id == overlay_id)
1113 else {
1114 return false;
1115 };
1116
1117 if self.arena.is_active(overlay.anchor)
1118 && self.arena.bounds(overlay.anchor).contains(position)
1119 {
1120 return true;
1121 }
1122
1123 self.overlay_manager.stack.iter().any(|candidate| {
1124 (candidate.id == overlay_id
1125 || self
1126 .overlay_manager
1127 .is_descendant_of(candidate.id, overlay_id))
1128 && candidate.bounds.contains(position)
1129 })
1130 }
1131
1132 fn update_pointer_leave_overlays(
1133 &mut self,
1134 position: Point,
1135 ops: &mut dyn crate::window::WindowOps,
1136 ) {
1137 let overlay_ids: Vec<crate::overlay::OverlayId> = self
1138 .overlay_manager
1139 .stack
1140 .iter()
1141 .filter(|overlay| {
1142 matches!(
1143 overlay.dismiss,
1144 crate::overlay::DismissBehavior::PointerLeave { .. }
1145 )
1146 })
1147 .map(|overlay| overlay.id)
1148 .collect();
1149
1150 let real_now = std::time::Instant::now();
1151 let sim_now = self.sim_clock;
1152
1153 for overlay_id in overlay_ids {
1154 let inside = self.pointer_inside_overlay_region(overlay_id, position);
1155 if let Some(overlay) = self
1156 .overlay_manager
1157 .stack
1158 .iter_mut()
1159 .find(|overlay| overlay.id == overlay_id)
1160 {
1161 if inside {
1162 overlay.pointer_leave_started_real = None;
1163 overlay.pointer_leave_started_sim = None;
1164 } else if overlay.pointer_leave_started_real.is_none() {
1165 overlay.pointer_leave_started_real = Some(real_now);
1166 overlay.pointer_leave_started_sim = Some(sim_now);
1167 self.arena.mark_needs_paint(overlay.anchor);
1168 }
1169 }
1170 }
1171
1172 self.process_pointer_leave_overlays_real(&mut *ops);
1173 }
1174
1175 fn process_pointer_leave_overlays(&mut self) {
1176 let sim_now = self.sim_clock;
1177 let mut noop = crate::window::NoopWindowOps;
1178 self.process_pointer_leave_overlays_impl(
1179 |overlay| {
1180 overlay
1181 .pointer_leave_started_sim
1182 .map(|started| sim_now.saturating_duration_since(started))
1183 },
1184 &mut noop,
1185 );
1186 }
1187
1188 fn process_pointer_leave_overlays_real(&mut self, ops: &mut dyn crate::window::WindowOps) {
1189 let real_now = std::time::Instant::now();
1190 self.process_pointer_leave_overlays_impl(
1191 |overlay| {
1192 overlay
1193 .pointer_leave_started_real
1194 .map(|started| real_now.saturating_duration_since(started))
1195 },
1196 &mut *ops,
1197 );
1198 }
1199
1200 fn process_auto_dismiss_overlays(&mut self) {
1201 let sim_now = self.sim_clock;
1202 let mut noop = crate::window::NoopWindowOps;
1203 self.process_auto_dismiss_overlays_impl(
1204 |overlay| {
1205 overlay
1206 .auto_dismiss_after
1207 .map(|_| sim_now.saturating_duration_since(overlay.shown_at_sim))
1208 },
1209 &mut noop,
1210 );
1211 }
1212
1213 fn process_auto_dismiss_overlays_real(&mut self, ops: &mut dyn crate::window::WindowOps) {
1214 let real_now = std::time::Instant::now();
1215 self.process_auto_dismiss_overlays_impl(
1216 |overlay| {
1217 overlay
1218 .auto_dismiss_after
1219 .map(|_| real_now.saturating_duration_since(overlay.shown_at_real))
1220 },
1221 &mut *ops,
1222 );
1223 }
1224
1225 /// Drain overlays whose fade-out tween has completed (set up by
1226 /// `OverlayRequest::with_fade`). Same dormant-and-restore-focus
1227 /// flow as the normal dismiss path; called once per layout pass
1228 /// after `process_auto_dismiss_overlays_real` so an overlay that
1229 /// hits its auto-dismiss deadline kicks off its fade-out tween
1230 /// in the same pass.
1231 pub(crate) fn process_overlay_fade_dismissals_real(
1232 &mut self,
1233 ops: &mut dyn crate::window::WindowOps,
1234 ) {
1235 let now = std::time::Instant::now();
1236 let pending = self.overlay_manager.process_pending_fade_dismissals(now);
1237 for (_id, dismissed, focus_restore) in pending {
1238 self.dormant_dismissed_content(&dismissed, &mut *ops);
1239 if let Some(restore_id) = focus_restore
1240 && self.arena.is_active(restore_id)
1241 {
1242 self.focus_ops(restore_id, &mut *ops);
1243 }
1244 }
1245 }
1246
1247 /// Sim-clock variant for headless tests. Same shape as
1248 /// [`process_overlay_fade_dismissals_real`](Self::process_overlay_fade_dismissals_real)
1249 /// but reads `dismissing_started_sim`.
1250 pub(crate) fn process_overlay_fade_dismissals_sim(&mut self) {
1251 let mut noop = crate::window::NoopWindowOps;
1252 let pending = self
1253 .overlay_manager
1254 .process_pending_fade_dismissals_sim(self.sim_clock);
1255 for (_id, dismissed, focus_restore) in pending {
1256 self.dormant_dismissed_content(&dismissed, &mut noop);
1257 if let Some(restore_id) = focus_restore
1258 && self.arena.is_active(restore_id)
1259 {
1260 self.focus_ops(restore_id, &mut noop);
1261 }
1262 }
1263 }
1264
1265 fn process_auto_dismiss_overlays_impl(
1266 &mut self,
1267 elapsed_fn: impl Fn(&crate::overlay::ActiveOverlay) -> Option<std::time::Duration>,
1268 ops: &mut dyn crate::window::WindowOps,
1269 ) {
1270 let mut to_dismiss = Vec::new();
1271
1272 for overlay in self.overlay_manager.stack.iter().rev() {
1273 let Some(delay) = overlay.auto_dismiss_after else {
1274 continue;
1275 };
1276
1277 if to_dismiss
1278 .iter()
1279 .any(|ancestor| self.overlay_manager.is_descendant_of(overlay.id, *ancestor))
1280 {
1281 continue;
1282 }
1283
1284 if let Some(elapsed) = elapsed_fn(overlay)
1285 && elapsed >= delay
1286 {
1287 to_dismiss.push(overlay.id);
1288 }
1289 }
1290
1291 for overlay_id in to_dismiss {
1292 let (dismissed, focus_restore) =
1293 self.overlay_manager.dismiss_with_focus_restore(overlay_id);
1294 self.dormant_dismissed_content(&dismissed, &mut *ops);
1295 if let Some(restore_id) = focus_restore
1296 && self.arena.is_active(restore_id)
1297 {
1298 self.focus_ops(restore_id, &mut *ops);
1299 }
1300 }
1301 }
1302
1303 fn process_pointer_leave_overlays_impl(
1304 &mut self,
1305 elapsed_fn: impl Fn(&crate::overlay::ActiveOverlay) -> Option<std::time::Duration>,
1306 ops: &mut dyn crate::window::WindowOps,
1307 ) {
1308 let mut to_dismiss = Vec::new();
1309
1310 for overlay in self.overlay_manager.stack.iter().rev() {
1311 let crate::overlay::DismissBehavior::PointerLeave { delay } = overlay.dismiss else {
1312 continue;
1313 };
1314
1315 if to_dismiss
1316 .iter()
1317 .any(|ancestor| self.overlay_manager.is_descendant_of(overlay.id, *ancestor))
1318 {
1319 continue;
1320 }
1321
1322 if let Some(elapsed) = elapsed_fn(overlay)
1323 && elapsed >= delay
1324 {
1325 to_dismiss.push(overlay.id);
1326 }
1327 }
1328
1329 for overlay_id in to_dismiss {
1330 let (dismissed, focus_restore) =
1331 self.overlay_manager.dismiss_with_focus_restore(overlay_id);
1332 self.dormant_dismissed_content(&dismissed, &mut *ops);
1333 if let Some(restore_id) = focus_restore
1334 && self.arena.is_active(restore_id)
1335 {
1336 self.focus_ops(restore_id, &mut *ops);
1337 }
1338 }
1339 }
1340
1341 pub fn with_theme(mut self, theme: Theme) -> Self {
1342 // Update both the cached `Theme` AND the reactive
1343 // `theme_signal` — widgets that observe the signal (e.g.
1344 // `TextInputField` resetting the rich-text engine's default
1345 // text colour) would otherwise see the constructor's
1346 // `light_default()` initial value forever, even when
1347 // `TeksiloAppBuilder.theme(crate::presets::intui::dark())` was used.
1348 // `set_theme` already does this; `with_theme` was the
1349 // builder-time analogue that forgot to keep them aligned.
1350 self.theme = theme.clone();
1351 self.theme_signal.set(theme);
1352 self.recompute_effective_theme();
1353 self
1354 }
1355
1356 pub fn with_text_backend(
1357 mut self,
1358 backend: Rc<RefCell<dyn teksilo_canvas::TextBackend>>,
1359 ) -> Self {
1360 self.text_backend = Some(backend);
1361 self
1362 }
1363
1364 /// Attach a platform host for custom window chrome. Set by the
1365 /// `WindowManager` when the application opts in via
1366 /// `WindowConfig::custom_chrome(true)`. Widgets like `TitleBar` retrieve
1367 /// it from inside the root-builder closure via [`Self::title_bar_host`].
1368 pub fn with_title_bar_host(mut self, host: Rc<dyn crate::PlatformTitleBarHost>) -> Self {
1369 self.title_bar_host = Some(host);
1370 self
1371 }
1372
1373 pub fn set_title_bar_host(&mut self, host: Rc<dyn crate::PlatformTitleBarHost>) {
1374 self.title_bar_host = Some(host);
1375 }
1376
1377 /// Get the platform title bar host, if one was attached. Returns `None`
1378 /// when the application did not opt into custom chrome, or when the
1379 /// platform does not support it (X11 without an EWMH-capable window
1380 /// manager, or a headless build).
1381 pub fn title_bar_host(&self) -> Option<Rc<dyn crate::PlatformTitleBarHost>> {
1382 self.title_bar_host.clone()
1383 }
1384
1385 pub fn theme(&self) -> &Theme {
1386 &self.theme
1387 }
1388
1389 /// Reactive handle on the current theme. Updates fire when `set_theme`
1390 /// is called; widgets that want theme-derived values to stay live should
1391 /// build derived signals via `theme_signal.map(...)` or combine with
1392 /// other inputs using `.zip(...)`.
1393 pub fn theme_signal(&self) -> &crate::signal::Signal<Theme> {
1394 &self.theme_signal
1395 }
1396
1397 /// Whether any widget needs layout or paint (i.e., a redraw would be useful).
1398 ///
1399 /// Uses `has_running` rather than `has_active` so that animations
1400 /// parked by the window-inactive gate stop forcing the event loop
1401 /// into `ControlFlow::WaitUntil`. Without this, an unfocused window
1402 /// would still wake at the animation frame interval and the
1403 /// pause would save nothing. Both the signal scheduler AND the
1404 /// shader-driven animated-quad registry are consulted — a
1405 /// ProgressBar::indeterminate whose widget has no pending paint
1406 /// dirt still needs the loop to keep waking at the animation
1407 /// frame interval so its phase advances.
1408 pub fn needs_redraw(&self) -> bool {
1409 self.arena.any_needs_layout()
1410 || self.arena.any_needs_paint()
1411 || self.animation_scheduler.has_running()
1412 || self.animated_quads.has_running()
1413 || self.frame_tick_requested.get()
1414 }
1415
1416 /// Whether a render pass is needed (any widget needs layout or paint).
1417 pub fn needs_render(&self) -> bool {
1418 self.arena.any_needs_layout() || self.arena.any_needs_paint()
1419 }
1420
1421 /// Whether this tree has reactive work that only a `layout()` pass can
1422 /// turn into arena dirt — i.e. whether reconciling it right now could
1423 /// change what [`needs_render`](Self::needs_render) reports.
1424 ///
1425 /// Read-only and cheap: `O(unique bound sources)` `u64` comparisons
1426 /// plus one peek per registered animated signal. No arena walk, no
1427 /// rebuilds, no geometry. Asking does not consume the answer, so it
1428 /// can be asked every dispatch.
1429 ///
1430 /// # Why this is exactly the right question, and no broader
1431 ///
1432 /// `teksilo_app::WindowManager::request_redraw_needing_render` exists
1433 /// for ONE case: a handler in window A wrote a `Signal` that window
1434 /// B's widgets also bind, and B — which never saw the event — must be
1435 /// reconciled before anyone can tell it needs repainting. Every OTHER
1436 /// thing `layout_with_ops` drives already has its own scheduling
1437 /// path and does not need this sweep:
1438 ///
1439 /// - tooltip dwell + sticky steps, delayed overlays, auto-dismiss,
1440 /// overlay fades, the animation scheduler, animated quads,
1441 /// gestures, `wake_at` and the 60 Hz frame tick are all timing
1442 /// driven, and every one of them contributes to
1443 /// [`next_timer_deadline`](Self::next_timer_deadline) — which
1444 /// `request_redraw_due` polls to wake precisely the due windows;
1445 /// - drag ticks follow that window's own pointer stream;
1446 /// - a handler that called `request_rebuild` marked the arena
1447 /// directly, so `needs_render()` is already true without any
1448 /// reconcile.
1449 ///
1450 /// So the two terms below are what the sweep uniquely covers:
1451 /// binding-registry staleness (the whole point), and a *pending*
1452 /// `animate_to` — which the scheduler has not started yet, so it
1453 /// contributes no deadline, and which only `process_pending_animations`
1454 /// (inside `layout`) can promote into one. The second term is
1455 /// belt-and-braces: arming an animation also advances the signal's
1456 /// generation, so a bound animated signal is already covered by the
1457 /// first — but an animated signal registered without being bound
1458 /// would not be, and this makes that impossible to get wrong.
1459 pub fn needs_reconcile(&self) -> bool {
1460 self.binding_registry.any_dirty()
1461 || self
1462 .animated_values
1463 .iter()
1464 .any(AnimatedRegistration::has_pending_animation)
1465 }
1466
1467 /// Register a `Signal<f32>` for animation support. The framework
1468 /// checks registered signals each frame for pending `animate_to`
1469 /// requests. Called automatically by `BuildContext::animated_signal()`
1470 /// — `owner` is `ctx.self_id()` of the widget whose `build()` created
1471 /// the signal. Used by the scheduler to pause/cancel animations when
1472 /// the owning widget is offscreen, dormant, or destroyed.
1473 pub fn register_animated_signal(
1474 &mut self,
1475 signal: &crate::signal::Signal<f32>,
1476 owner: WidgetId,
1477 ) {
1478 self.animated_values
1479 .retain(|registration| registration.is_alive());
1480 if let Some(existing) = self
1481 .animated_values
1482 .iter_mut()
1483 .find(|registration| registration.same_signal(signal))
1484 {
1485 // Signal may have been registered earlier with a placeholder
1486 // owner (e.g. a widget field constructed pre-build and
1487 // re-registered during build()) — prefer the latest owner.
1488 existing.owner = owner;
1489 return;
1490 }
1491 if let Some(weak_signal) = signal.weak_handle() {
1492 self.animated_values.push(AnimatedRegistration {
1493 weak: weak_signal,
1494 owner,
1495 });
1496 }
1497 }
1498
1499 /// Whether any animation is currently running.
1500 pub fn has_active_animations(&self) -> bool {
1501 self.animation_scheduler.has_active()
1502 }
1503
1504 /// The clock a newly promoted animation must be stamped with: the same one
1505 /// the scheduler will later be ticked against.
1506 ///
1507 /// Normally the wall clock. But once [`tick_animations`](Self::tick_animations)
1508 /// has driven this tree, the scheduler is *only* ever ticked at
1509 /// [`Self::sim_clock`] — so an animation stamped `Instant::now()` is measured
1510 /// against a clock that may never reach its start. A headless test
1511 /// interleaving `layout()` (which promotes) with `tick_animations()` (which
1512 /// ticks) advances the two clocks independently: simulated time by whatever
1513 /// the test asks for, real time by however long the test actually takes. The
1514 /// moment real time overtakes simulated time, every animation armed from then
1515 /// on has a start in the scheduler's future and its progress **freezes** —
1516 /// not slowly, completely, and no number of further ticks recovers it.
1517 ///
1518 /// That made animated layout tests fail as a function of machine load rather
1519 /// than of behaviour: green run alone or on a couple of threads, red once the
1520 /// runner filled the cores and each test's wall-clock time stretched past the
1521 /// simulated time it was asking for. The overlay manager already keeps its
1522 /// real and simulated timestamps apart for this reason; animations now agree
1523 /// on one clock the same way.
1524 fn animation_clock(&self) -> std::time::Instant {
1525 if self.sim_driven {
1526 self.sim_clock
1527 } else {
1528 std::time::Instant::now()
1529 }
1530 }
1531
1532 /// Pick up pending `animate_to` requests from registered signals
1533 /// and start them on the animation scheduler.
1534 fn process_pending_animations(&mut self) {
1535 let now = self.animation_clock();
1536 self.process_pending_animations_at(now);
1537 }
1538
1539 /// Pick up pending animations using the given time (for sim clock).
1540 fn process_pending_animations_at(&mut self, now: std::time::Instant) {
1541 let mut pending = Vec::new();
1542 self.animated_values.retain(|registration| {
1543 if let Some(animation) = registration.take_pending_animation() {
1544 pending.push(animation);
1545 true
1546 } else {
1547 registration.is_alive()
1548 }
1549 });
1550
1551 for (signal, req, owner) in pending {
1552 if req.looping {
1553 let start = signal.get();
1554 self.animation_scheduler.animate_looping(
1555 &signal,
1556 owner,
1557 start,
1558 req.target,
1559 req.duration,
1560 req.easing,
1561 req.frame_interval,
1562 req.epsilon,
1563 req.max_duration,
1564 now,
1565 );
1566 } else {
1567 self.animation_scheduler.animate_with_options(
1568 &signal,
1569 owner,
1570 req.target,
1571 req.duration,
1572 req.easing,
1573 req.frame_interval,
1574 req.epsilon,
1575 req.max_duration,
1576 now,
1577 );
1578 }
1579 }
1580 }
1581
1582 /// Mark the owning window as active (focused AND not occluded) or
1583 /// inactive. Propagates to the animation scheduler AND the
1584 /// animated-quad registry so both pause-resume in lockstep — no
1585 /// ticks, no frame wakes, no GPU submits.
1586 ///
1587 /// On an actual state change it also fires `window_active_signal`
1588 /// (so build-time binders and `DimWhenInactive` react) and issues a
1589 /// global paint-only dirty mark, so every widget that reads
1590 /// `PaintContext::window_active` (caret gates, selection bands) repaints
1591 /// once. This is a repaint, not a relayout — geometry never changes when
1592 /// the window's active state flips (the caret keeps its space). Window
1593 /// focus changes are rare and user-driven, so the O(n) mark is cheap and
1594 /// Mark every node paint-dirty (no relayout, no rebuild) so the next
1595 /// render re-runs their `paint()`. This is the paint-cache invalidation an
1596 /// off-thread source needs after posting a [`RepaintWindowRequest`](crate::RepaintWindowRequest):
1597 /// a bare redraw request re-presents the cached frame, so a widget whose
1598 /// content changed off the UI thread (a terminal's PTY output) must be
1599 /// marked dirty for its `paint()` to run again.
1600 pub fn mark_all_needs_paint_only(&mut self) {
1601 self.arena.mark_all_needs_paint_only();
1602 }
1603
1604 /// strictly lighter than `set_theme`'s `mark_all_dirty` (layout + paint).
1605 pub fn set_window_active(&mut self, active: bool) {
1606 let now = std::time::Instant::now();
1607 self.animation_scheduler.set_window_active(active, now);
1608 self.animated_quads.set_window_active(active, now);
1609 if self.window_active_signal.get() != active {
1610 self.window_active_signal.set(active);
1611 self.arena.mark_all_needs_paint_only();
1612 if !active {
1613 // The pointer has left for another window; the OS sends no
1614 // leave event we can rely on, so a tooltip shown at the moment
1615 // of the switch would float over the newly-focused window's
1616 // chrome with nothing left to dismiss it. Retire tips and
1617 // cancel pending dwells — but leave *sticky* ones, which the
1618 // user pinned deliberately and expects to find on return.
1619 self.tooltip_window_deactivated();
1620 // Same reasoning for a held pointer: a widget that captured
1621 // the pointer for a drag (a column-resize grip, a splitter
1622 // divider, a scrollbar thumb, a slider) will never see the
1623 // matching PointerUp — the user releases the button over the
1624 // window that took focus, and this window is told nothing.
1625 // Capture is otherwise cleared only by that Up or by the
1626 // widget going inactive, so leaving it set strands the whole
1627 // window: every subsequent PointerMove is redelivered to the
1628 // abandoned widget instead of hit-testing (killing hover,
1629 // cursor shapes and tooltips everywhere else), and the next
1630 // click's Up is swallowed by it, so the first press on any
1631 // release-activated control silently does nothing.
1632 self.pointer_captured_by = None;
1633 }
1634 }
1635 }
1636
1637 /// Whether the owning window is currently active (`focused AND not
1638 /// occluded`). The reactive companion is [`Self::window_active_signal`].
1639 pub fn is_window_active(&self) -> bool {
1640 self.window_active_signal.get()
1641 }
1642
1643 /// Reactive handle on window-active state. Fires when the window gains or
1644 /// loses active status. Bind at [`BindingLevel::RepaintOnly`] — an
1645 /// active-state flip never affects geometry. Starts `true`.
1646 ///
1647 /// [`BindingLevel::RepaintOnly`]: crate::binding::BindingLevel::RepaintOnly
1648 pub fn window_active_signal(&self) -> crate::signal::Signal<bool> {
1649 self.window_active_signal.clone()
1650 }
1651
1652 /// Register a new animated quad for the currently-building widget.
1653 /// Called by [`crate::build_context::BuildContext::animated_quad`];
1654 /// returns an opaque handle the widget stashes for its `paint()`
1655 /// call.
1656 pub fn register_animated_quad(
1657 &mut self,
1658 owner: WidgetId,
1659 kind: crate::animated_quad::AnimatedQuadKind,
1660 ) -> crate::animated_quad::AnimatedQuadHandle {
1661 self.animated_quads
1662 .register(owner, kind, std::time::Instant::now())
1663 }
1664
1665 /// Active animated-quad slot count. Test / debug helper.
1666 pub fn animated_quad_count(&self) -> usize {
1667 self.animated_quads.active_count()
1668 }
1669
1670 /// Advance time-driven gesture recognizers (currently only
1671 /// [`crate::gesture::LongPressRecognizer`]) across every widget that
1672 /// has a gesture arena. Must be called by the event loop on each
1673 /// wake-up; otherwise long-press will never fire during an idle hold.
1674 ///
1675 /// When a recognizer transitions to `Recognized`, the corresponding
1676 /// handler on the owning widget is invoked with a fresh
1677 /// [`EventContext`], and any commands / overlay requests it emits are
1678 /// collected through the normal post-event path.
1679 pub fn tick_gestures(&mut self, now: std::time::Instant) {
1680 let mut noop = crate::window::NoopWindowOps;
1681 self.tick_gestures_with_ops(now, &mut noop);
1682 }
1683
1684 /// App-facing variant of [`tick_gestures`](Self::tick_gestures)
1685 /// that accepts a real [`WindowOps`](crate::window::WindowOps)
1686 /// sink so gesture-recognized handlers can call the multi-window
1687 /// API synchronously.
1688 pub fn tick_gestures_with_ops(
1689 &mut self,
1690 now: std::time::Instant,
1691 ops: &mut dyn crate::window::WindowOps,
1692 ) {
1693 // Snapshot the gesture-owners set into the reusable scratch.
1694 // Previously this iterated every active widget; in practice
1695 // only a tiny fraction carry a gesture arena, so visiting the
1696 // rest was pure overhead.
1697 // `mem::take` lets the loop borrow `&mut self` for
1698 // `make_event_context` etc. without conflicting with the
1699 // scratch buffer; we put the storage back at the end.
1700 let mut ids = std::mem::take(&mut self.active_ids_scratch);
1701 ids.clear();
1702 ids.extend(
1703 self.gesture_owners
1704 .iter()
1705 .copied()
1706 .filter(|id| self.arena.is_active(*id)),
1707 );
1708 for &id in &ids {
1709 let gesture = match self.arena.get_mut(id) {
1710 Some(node) => node
1711 .handlers
1712 .gesture_arena
1713 .as_mut()
1714 .and_then(|arena| arena.tick(now)),
1715 None => None,
1716 };
1717 let Some(gesture) = gesture else { continue };
1718
1719 let mut ctx = self.make_event_context(&mut *ops);
1720 if let Some(node) = self.arena.get_mut(id) {
1721 Self::dispatch_recognized_gesture(node, gesture, &mut ctx);
1722 }
1723 self.collect_from_ctx(ctx, id);
1724 self.arena.mark_needs_paint(id);
1725 }
1726 self.active_ids_scratch = ids;
1727 }
1728
1729 /// Earliest wall-clock deadline at which any active gesture arena
1730 /// needs [`WidgetTree::tick_gestures`] called — typically a pending
1731 /// long-press timeout. Returns `None` when no recognizer is waiting.
1732 pub fn next_gesture_deadline(&self) -> Option<std::time::Instant> {
1733 // Iterate just the widgets that actually carry a gesture arena.
1734 // `filter` for `is_active` skips dormant entries that may still
1735 // be in the set after a hide-without-detach.
1736 self.gesture_owners
1737 .iter()
1738 .copied()
1739 .filter(|id| self.arena.is_active(*id))
1740 .filter_map(|id| self.arena.get(id))
1741 .filter_map(|node| node.handlers.gesture_arena.as_ref())
1742 .filter_map(|arena| arena.next_deadline())
1743 .min()
1744 }
1745
1746 /// Advance animations by simulated time (for deterministic testing).
1747 /// Pending `animate_to` requests are started at the current sim_clock,
1748 /// then time advances by `duration`, and the scheduler ticks at the new time.
1749 pub fn tick_animations(&mut self, duration: std::time::Duration) {
1750 // From here on this tree is simulation-driven: `layout` must stamp the
1751 // animations it promotes with `sim_clock` too, or they are measured
1752 // against a clock that never reaches them. See `animation_clock`.
1753 self.sim_driven = true;
1754 self.process_pending_animations_at(self.sim_clock);
1755
1756 self.sim_clock += duration;
1757 // Mirror onto the overlay manager so any fade-out tween
1758 // started during this tick stamps its sim-time start in
1759 // lockstep with real time.
1760 self.overlay_manager.set_sim_clock(self.sim_clock);
1761
1762 if self.frame_tick_requested.get() {
1763 self.frame_tick_requested.set(false);
1764 let delta = duration.as_secs_f32().clamp(0.0, 0.1);
1765 self.frame_tick.set(delta);
1766 }
1767
1768 self.animation_scheduler
1769 .tick(self.sim_clock, &self.arena, self.paint_epoch);
1770
1771 // Simulated-time test helper — use NoopWindowOps; tests that
1772 // need a real sink call layout_with_ops / dispatch_event_with_ops
1773 // themselves.
1774 let mut noop = crate::window::NoopWindowOps;
1775 self.process_state_changes(&mut noop);
1776 }
1777
1778 /// Switch the tree-level theme at runtime.
1779 ///
1780 /// Updates `theme_signal` (a reactive `Signal<Theme>`) and marks all widgets
1781 /// dirty for relayout and repaint. Widgets are **not** rebuilt: the
1782 /// `LayoutContext` and `PaintContext` already resolve the current theme on
1783 /// every pass, and any widget that derives state from theme tokens should
1784 /// do so through a `theme_signal()` subscription rather than a build-time
1785 /// capture. Preserves focus, scroll offsets, and other interaction state.
1786 pub fn set_theme(&mut self, theme: Theme) {
1787 self.theme = theme.clone();
1788 self.theme_signal.set(theme);
1789 self.recompute_effective_theme();
1790 self.arena.mark_all_dirty();
1791 }
1792
1793 /// Recompute [`Self::effective_theme`] from the current `theme` and the
1794 /// combined text scale (`user_text_scale * text_scale_factor`). Callers
1795 /// that change either input are responsible for `mark_all_dirty()`.
1796 fn recompute_effective_theme(&mut self) {
1797 let combined = (self.user_text_scale as f64 * self.text_scale_factor) as f32;
1798 self.effective_theme = if (combined - 1.0).abs() < f32::EPSILON {
1799 self.theme.clone()
1800 } else {
1801 let mut t = self.theme.clone();
1802 t.typography = t.typography.scaled(combined);
1803 t
1804 };
1805 // Single source: every downstream consumer (the layout/paint context
1806 // `text_scale` field, the reactive `text_scale_signal`) reads from here.
1807 self.effective_text_scale = combined;
1808 self.text_scale_signal.set(combined);
1809 }
1810
1811 /// The combined effective text scale (`user_text_scale * OS text_scale_factor`).
1812 /// Read by the layout/paint walkers to populate `ctx.text_scale` for widgets
1813 /// that size from a source other than `Theme.typography`.
1814 pub fn effective_text_scale(&self) -> f32 {
1815 self.effective_text_scale
1816 }
1817
1818 /// Reactive handle on [`Self::effective_text_scale`]. Build-time binders that
1819 /// must react to a scale change without their own rebuild path bind this
1820 /// (e.g. `Calendar` binds it at `Rebuild` level so its fixed cell constants
1821 /// recompute). Fires on `set_user_text_scale` / theme / OS-pref change.
1822 pub fn text_scale_signal(&self) -> crate::signal::Signal<f32> {
1823 self.text_scale_signal.clone()
1824 }
1825
1826 /// Set the user-controlled global text-scale factor (`1.0` = 100 %).
1827 ///
1828 /// The factor multiplies with the OS accessibility text-scale preference to
1829 /// produce the rendered scale. Recomputes the effective theme and marks all
1830 /// widgets dirty so every text widget grows on the next pass; no rebuild,
1831 /// so focus/scroll/interaction state survive. Values outside `[0.25, 8.0]`
1832 /// are clamped. Persisted by the application via
1833 /// `teksilo_settings::TEXT_SCALE_KEY`.
1834 pub fn set_user_text_scale(&mut self, factor: f32) {
1835 let clamped = factor.clamp(0.25, 8.0);
1836 if (self.user_text_scale - clamped).abs() < f32::EPSILON {
1837 return;
1838 }
1839 self.user_text_scale = clamped;
1840 self.recompute_effective_theme();
1841 self.arena.mark_all_dirty();
1842 }
1843
1844 /// The current user-controlled text-scale factor (`1.0` = 100 %).
1845 pub fn user_text_scale(&self) -> f32 {
1846 self.user_text_scale
1847 }
1848
1849 /// After a rebuild that destroyed subtrees — or after a `visible_when` /
1850 /// `Switcher` pass parks the focused widget dormant — drop any interaction
1851 /// state (focus, hover) whose target `WidgetId` is no longer active.
1852 ///
1853 /// **FocusLost is load-bearing.** Clearing `self.focused` alone leaves the
1854 /// widget's own `on_focus` / `has_focus` / caret-blink state thinking it is
1855 /// still focused. A rich-text editor in that state keeps scheduling
1856 /// `wake_at` caret toggles and re-arming `frame_request` from its tick
1857 /// effect — and because `frame_tick` observers are **not** gated on
1858 /// dormancy, every open tab's editor (TabWidget mounts them all) still runs
1859 /// on those wakes. Rapid tab switches that park a focused editor without a
1860 /// real focus move (programmatic selection, race with pointer focus) used
1861 /// to accumulate stuck "focused" editors and unbounded frame work. Dispatch
1862 /// `FocusLost` first so widgets clear that state, then drop the tree's
1863 /// focus pointer.
1864 ///
1865 /// Preserves state when the target still exists *and* is active. Called from
1866 /// data-driven rebuild paths (`process_state_changes`) and after every
1867 /// rebuild drain; theme and locale switches no longer rebuild.
1868 pub(crate) fn revalidate_interaction_state(&mut self, ops: &mut dyn crate::window::WindowOps) {
1869 if let Some(id) = self.focused
1870 && !self.arena.is_active(id)
1871 {
1872 let old = self.focused;
1873 // Deliver FocusLost while the node still exists (dormant or about to
1874 // be torn down). Skip if the node is already gone — destroy paths
1875 // take care of bookkeeping without a deliverable target.
1876 if self.arena.get(id).is_some() {
1877 // Direct: no bubble through dormant ancestors, no overlay
1878 // dismiss side-effects — this is a teardown signal, not a
1879 // user-driven focus move.
1880 self.dispatch_to_widget_direct(
1881 id,
1882 &crate::event::WidgetEvent::FocusLost,
1883 &mut *ops,
1884 );
1885 }
1886 self.set_focused(None);
1887 self.focus_origin = None;
1888 self.update_focus_within_signals(old, None);
1889 self.update_view_focus_signals(old, None);
1890 self.a11y_dirty = true;
1891 }
1892 if self.focused.is_none() {
1893 self.focus_origin = None;
1894 }
1895 if let Some(id) = self.hovered
1896 && !self.arena.is_active(id)
1897 {
1898 let old = self.hovered;
1899 self.set_hovered(None);
1900 self.update_hover_within_signals(old, None);
1901 }
1902 // Pointer capture anchored at a destroyed widget would otherwise
1903 // swallow every subsequent Move/Up — dispatch_to_widget rejects
1904 // inactive targets. Drop the capture so events resume normal
1905 // hit-test dispatch. Same for any in-flight drag session whose
1906 // source was torn down: the user sees the drag "stick".
1907 if let Some(id) = self.pointer_captured_by
1908 && !self.arena.is_active(id)
1909 {
1910 self.pointer_captured_by = None;
1911 }
1912 // External (OS) drags have no in-app source widget, so they are never
1913 // torn down by source destruction — only internal drags are salvaged.
1914 let source_gone = self
1915 .active_drag
1916 .as_ref()
1917 .and_then(|s| s.source_widget)
1918 .is_some_and(|sw| !self.arena.is_active(sw));
1919 if source_gone {
1920 // `cancel_active_drag` fires on_drag_leave on the current
1921 // target before cleanup — the same contract as Escape.
1922 self.cancel_active_drag(&mut *ops);
1923 } else {
1924 // The drag *source* survived but its current hover **target** was
1925 // torn down by the rebuild (e.g. a side disabled / collapsed
1926 // mid-drag destroyed the panel under the pointer). Clear the stale
1927 // target id so a subsequent drop doesn't resolve to a destroyed
1928 // widget (and silently vanish); the next move — or the drop's own
1929 // re-hit-test — re-engages a live target.
1930 let stale_target = self
1931 .active_drag
1932 .as_ref()
1933 .and_then(|d| d.current_target)
1934 .is_some_and(|t| !self.arena.is_active(t));
1935 if stale_target && let Some(drag) = self.active_drag.as_mut() {
1936 drag.current_target = None;
1937 }
1938 }
1939 }
1940
1941 /// Rebuild a single composite widget: destroy old children, re-run `build()`,
1942 /// and wire up new children. Called from `process_state_changes()` when a
1943 /// binding at `BindingLevel::Rebuild` fires (data-driven rebuild). Theme
1944 /// and locale changes do **not** rebuild — they update reactive signals
1945 /// that widgets bind to via `theme_signal()` / `locale_signal()`.
1946 /// Test-only: force-mark a widget for rebuild on the next layout
1947 /// pass. Lets regression tests exercise the rebuild path without
1948 /// needing to trip a Signal binding. Exposed cross-crate (not
1949 /// `#[cfg(test)]`-gated) so widget-crate tests in `teksilo-widgets`
1950 /// and elsewhere can also drive rebuilds; the `_for_testing`
1951 /// suffix marks it as not intended for application code.
1952 pub fn arena_mark_needs_rebuild_for_testing(&mut self, id: WidgetId) {
1953 self.arena.mark_needs_rebuild(id);
1954 }
1955
1956 /// Force a [`DeferredSubtree`](crate::deferred_subtree::DeferredSubtree) at
1957 /// `id` to build its content now. A no-op for any other widget.
1958 ///
1959 /// The framework's own door into deferred content, for the case where the
1960 /// decision to show is the tree's rather than a widget's: a tooltip whose
1961 /// dwell has just matured has no open signal anyone could have handed over.
1962 pub(crate) fn materialize_deferred(&mut self, id: WidgetId) {
1963 let forced = self
1964 .arena
1965 .get_mut(id)
1966 .and_then(|n| n.widget.as_any_mut())
1967 .and_then(|any| any.downcast_mut::<crate::deferred_subtree::DeferredSubtree>())
1968 .map(|deferred| {
1969 let needed = !deferred.is_materialized();
1970 deferred.force();
1971 needed
1972 })
1973 .unwrap_or(false);
1974 if forced {
1975 self.rebuild_single_widget(id);
1976 }
1977 }
1978
1979 pub(crate) fn rebuild_single_widget(&mut self, widget_id: WidgetId) {
1980 // Per §9.4.5, drop the source handle first (stops further source-side
1981 // dispatch) and then remove the UI-side callback. Either order gives
1982 // the same user-visible outcome for events that get posted between
1983 // the two steps, but dropping the source handle first stops the
1984 // publisher thread's work sooner.
1985 //
1986 // ⚠ That reasoning is about the two steps below, and it used to be
1987 // read as covering the whole problem. It does not. The dangerous gap
1988 // is not the microseconds between these two lines, it is the whole
1989 // span from *publish* to *dispatch*: a backend event is posted with
1990 // the id its publisher captured and is handled by the UI thread
1991 // frames later, so any rebuild in between used to strand it. The ids
1992 // are therefore carried across into the new build (see
1993 // `BuildContext::reusable_sub_ids`) rather than being retired here.
1994 // Skribisto's Analysis pane hit this every time it was the restored
1995 // view at project open: it starts a long operation in `build()` and
1996 // sets its own `Rebuild`-bound state signal, the operation finished
1997 // inside its own rebuild, and the pane sat on "Reading the
1998 // manuscript…" for the rest of the session with nothing logged.
1999 // Cancel any looping/one-shot animations owned by this widget
2000 // before build() runs. Without this, a widget that creates a
2001 // fresh `animated_signal` in build() would leak the previous
2002 // instance's scheduler entry: the old Signal<f32> clone lives
2003 // in `animations` forever, ticking against an orphaned signal
2004 // (silent CPU waste) and, for looping animations, doubling up
2005 // when the new one registers.
2006 self.animation_scheduler.cancel_by_widget(widget_id);
2007 // Same pattern for shader-driven animated quads: free the
2008 // widget's slot(s) so `build()` can allocate fresh handles.
2009 // The old cached_paint (if any) carries stale slot indices —
2010 // clear it so paint() re-runs and re-emits DrawCommands with
2011 // the newly-allocated slot.
2012 self.animated_quads.cancel_by_widget(widget_id);
2013
2014 let drained_subs = if let Some(node) = self.arena.get_mut(widget_id) {
2015 node.effect_handles.clear();
2016 node.actions.clear();
2017 node.dirty.needs_rebuild = false;
2018 node.cached_paint = None;
2019 node.dirty.needs_paint = true;
2020 // Reset only the OWN handler bucket so `apply_self_handlers`
2021 // during this build's fresh build() starts from empty and
2022 // doesn't stack N-fold handler chains across rebuilds.
2023 // `external_handlers` — set by the `WidgetBuilder` chain at
2024 // creation time or by a composing parent's
2025 // `apply_handlers(child_id, ...)` — persists: those handlers
2026 // come from outside the widget and aren't re-emitted by its
2027 // own `build()`.
2028 //
2029 // `node_focusable` / `node_tab_index` / `node_cursor` /
2030 // `clips_children` / `context_menu_factory` are simple
2031 // values, not accumulating closures. Leave them alone —
2032 // apply_self_handlers rewrites them if the new build
2033 // specifies non-None values; otherwise values from the
2034 // creation site survive the rebuild.
2035 node.handlers = crate::event_handlers::EventHandlers::new();
2036 std::mem::take(&mut node.subscription_handles)
2037 } else {
2038 Vec::new()
2039 };
2040 // Rebuild wiped the OWN handler bucket above (the gesture arena
2041 // lived there), so the widget no longer owns any recognizers.
2042 // The next pointer hit re-runs `ensure_gesture_arena` and
2043 // re-inserts if the new build still wires gesture handlers.
2044 // External handlers (set via the builder chain at creation time)
2045 // persist, but `external_handlers` never carries a gesture arena
2046 // directly — it's always built by `ensure_gesture_arena` into
2047 // the OWN bucket.
2048 self.gesture_owners.remove(&widget_id);
2049 // Shortcuts the widget declared are torn down too — they will
2050 // be re-registered during the upcoming `build()` call. User
2051 // overrides live in a separate map keyed by id, so user
2052 // rebindings survive this round-trip (see ShortcutRegistry
2053 // graveyard semantics).
2054 self.shortcut_registry.unregister_all_for_owner(widget_id);
2055 self.global_actions.retain(|(owner, _)| *owner != widget_id);
2056 self.text_surfaces.remove(widget_id);
2057 // Re-apply `Widget::declare_shortcuts` so the static metadata
2058 // survives the rebuild (the unregister above wiped both
2059 // declared and build-registered entries; build() will refill
2060 // the handler-bearing ones, but it can't be relied on to
2061 // refill the metadata-only declarations).
2062 self.apply_declared_shortcuts(widget_id);
2063 // Drop any signal→widget bindings from the previous build
2064 // cycle so `build()` can re-register a fresh set without
2065 // accumulating duplicates across rebuilds.
2066 self.binding_registry.unregister_for_widget(widget_id);
2067 // Kept, in order, and handed to the upcoming `build()` so it re-subscribes under
2068 // the same ids. A subscription's id is what a publisher captured and posted with;
2069 // minting new ones here would leave every event already queued for this widget
2070 // naming an id nothing answers to. See `BuildContext::reusable_sub_ids`.
2071 let mut reusable_sub_ids = Vec::with_capacity(drained_subs.len());
2072 for (sub_id, handle) in drained_subs {
2073 drop(handle);
2074 self.app_context
2075 .subscription_callbacks
2076 .borrow_mut()
2077 .remove(&sub_id);
2078 self.app_context
2079 .subscription_ctx_callbacks
2080 .borrow_mut()
2081 .remove(&sub_id);
2082 reusable_sub_ids.push(sub_id);
2083 }
2084
2085 // Decide how to treat the existing children. Two modes:
2086 //
2087 // * Default (`preserves_children_on_rebuild() == false`): the widget
2088 // re-derives its whole subtree, so tear down every old child up
2089 // front and let `build()` produce a fresh set.
2090 //
2091 // * Reconcile (`preserves_children_on_rebuild() == true`): the widget
2092 // re-attaches the children it keeps (by id) and drops the rest. We
2093 // snapshot the old children, run `build()`, then destroy only the
2094 // old children the new build did NOT re-attach and did NOT re-parent
2095 // elsewhere. Re-attached children keep their state (focus, scroll,
2096 // text, subscriptions); dropped children are reaped rather than left
2097 // as stranded, still-active orphans.
2098 let preserve_children = self
2099 .arena
2100 .get(widget_id)
2101 .map(|n| n.widget.preserves_children_on_rebuild())
2102 .unwrap_or(false);
2103 let old_children: Vec<WidgetId> = self.arena.children(widget_id).to_vec();
2104 if !preserve_children {
2105 for child_id in &old_children {
2106 self.destroy_subtree(*child_id);
2107 }
2108 }
2109
2110 // The parentless nodes the *previous* build owned. Taken now so
2111 // `build()` records its new set into an empty list, and destroyed after
2112 // it returns — by then the widget's own fields point at the new nodes,
2113 // so tearing the old ones down cannot strand a live id in the widget.
2114 // Both the `preserve_children` reconcile and the plain path want this:
2115 // detached content is rebuilt wholesale either way (it is not addressed
2116 // by id from the outside, so there is nothing to preserve).
2117 let old_detached: Vec<WidgetId> = self
2118 .arena
2119 .get_mut(widget_id)
2120 .map(|node| std::mem::take(&mut node.detached))
2121 .unwrap_or_default();
2122
2123 let mut widget_box = match self.arena.take_widget(widget_id) {
2124 Some(widget) => widget,
2125 None => return,
2126 };
2127
2128 let mut build_ctx = crate::build_context::BuildContext {
2129 tree: self,
2130 composite_id: Some(widget_id),
2131 effect_handles: Vec::new(),
2132 subscription_handles: Vec::new(),
2133 reusable_sub_ids,
2134 };
2135 let new_children = widget_box.build(&mut build_ctx);
2136 let effect_handles = std::mem::take(&mut build_ctx.effect_handles);
2137 let subscription_handles = std::mem::take(&mut build_ctx.subscription_handles);
2138
2139 self.arena.restore_widget(widget_id, widget_box);
2140
2141 for &child_id in &new_children {
2142 if let Some(child_node) = self.arena.get_mut(child_id) {
2143 child_node.parent = Some(widget_id);
2144 }
2145 }
2146
2147 // Reconcile the preserve path: reap any old child the new build
2148 // dropped (not in `new_children`) and did not re-parent elsewhere
2149 // (its `parent` still points here). Authoritative parent pointers mean
2150 // a kept subtree re-parented out of a dropped sibling survives. Runs
2151 // before `node.children` is overwritten so the destroy walk can't see
2152 // the new list. Re-parented survivors already have their new parent by
2153 // now (`ctx.add` builds nested widgets synchronously and re-homes their
2154 // children), so the `parent == widget_id` test correctly excludes them.
2155 if preserve_children {
2156 let new_set: std::collections::HashSet<WidgetId> =
2157 new_children.iter().copied().collect();
2158 for &old_c in &old_children {
2159 if !new_set.contains(&old_c) && self.arena.parent(old_c) == Some(widget_id) {
2160 self.destroy_subtree_inner(old_c, true);
2161 }
2162 }
2163 }
2164
2165 if let Some(node) = self.arena.get_mut(widget_id) {
2166 node.children = new_children;
2167 node.effect_handles = effect_handles;
2168 node.subscription_handles = subscription_handles;
2169 }
2170
2171 // Reap the previous build's parentless content, now that the fresh set
2172 // is recorded and the widget points at it.
2173 for id in old_detached {
2174 self.destroy_subtree_inner(id, false);
2175 }
2176 }
2177
2178 /// Record that `owner` created and owns the parentless node `detached` —
2179 /// pre-built overlay content that is deliberately not a child. See
2180 /// [`BuildContext::add_detached`](crate::build_context::BuildContext::add_detached)
2181 /// and [`WidgetNode::detached`](crate::arena::WidgetNode).
2182 pub(crate) fn record_detached(&mut self, owner: WidgetId, detached: WidgetId) {
2183 if let Some(node) = self.arena.get_mut(owner) {
2184 node.detached.push(detached);
2185 }
2186 }
2187
2188 /// Destroy every parentless node `owner` owns, and forget them.
2189 ///
2190 /// Taken out of the node first: the destroy walk below can re-enter this
2191 /// function (a detached node may own detached nodes of its own — a rich
2192 /// tooltip's cascade children each pre-build their own), and it must not
2193 /// see a list it is halfway through consuming.
2194 fn destroy_detached_of(&mut self, owner: WidgetId) {
2195 let detached = self
2196 .arena
2197 .get_mut(owner)
2198 .map(|node| std::mem::take(&mut node.detached))
2199 .unwrap_or_default();
2200 for id in detached {
2201 self.destroy_subtree_inner(id, false);
2202 }
2203 }
2204
2205 /// Recursively destroy a subtree, dropping per-widget subscription
2206 /// handles and removing their UI-side callbacks. Use this in place of
2207 /// `arena.destroy()` whenever a widget that may have subscribed to
2208 /// events is being torn down.
2209 pub(crate) fn destroy_subtree(&mut self, widget_id: WidgetId) {
2210 self.destroy_subtree_inner(widget_id, false);
2211 }
2212
2213 /// Shared teardown for [`destroy_subtree`](Self::destroy_subtree) and the
2214 /// reconciling rebuild path. When `reparent_aware` is `true`, recursion
2215 /// descends into a child only if that child's `parent` still points at
2216 /// `widget_id`.
2217 ///
2218 /// A reconciling rebuild (a [`preserves_children_on_rebuild`] widget) may
2219 /// re-parent a kept subtree *out* of a dropped sibling and *into* the new
2220 /// tree. The dropped sibling's `children` list still lists that subtree
2221 /// (stale), so following it would tear down a node that is actually alive
2222 /// elsewhere. Following the authoritative `parent` pointer instead stops
2223 /// at the boundary of what genuinely still belongs to the node being
2224 /// destroyed. The per-node teardown ends with `arena.remove_node` (a
2225 /// single-node removal), NOT `arena.destroy` (which would re-recurse the
2226 /// stale `children` list and undo the skip).
2227 ///
2228 /// [`preserves_children_on_rebuild`]: crate::widget::Widget::preserves_children_on_rebuild
2229 fn destroy_subtree_inner(&mut self, widget_id: WidgetId, reparent_aware: bool) {
2230 // See the matching cancel in `rebuild_single_widget` — the
2231 // scheduler holds strong Signal<f32> clones, so the animation
2232 // would outlive its widget without this explicit cancellation.
2233 self.animation_scheduler.cancel_by_widget(widget_id);
2234 // Release the animated-quad slot(s) too.
2235 self.animated_quads.cancel_by_widget(widget_id);
2236 // A tooltip's content widget is parentless (`ctx.add`), so the child
2237 // walk below never reaches it — reap it explicitly or the entry and
2238 // its node outlive the anchor for the lifetime of the tree.
2239 self.retire_tooltips_of_destroyed_anchor(widget_id);
2240 // Same reasoning, one level up: every *other* parentless node this
2241 // widget built (a dropdown menu, a calendar, a tooltip's nested
2242 // cascade children) is unreachable from the child walk and dies here
2243 // or never.
2244 self.destroy_detached_of(widget_id);
2245
2246 let children: Vec<WidgetId> = self.arena.children(widget_id).to_vec();
2247 for child in children {
2248 if reparent_aware && self.arena.parent(child) != Some(widget_id) {
2249 // Re-parented into the surviving tree by this rebuild — leave it.
2250 continue;
2251 }
2252 self.destroy_subtree_inner(child, reparent_aware);
2253 }
2254 let drained_subs = self
2255 .arena
2256 .get_mut(widget_id)
2257 .map(|node| std::mem::take(&mut node.subscription_handles))
2258 .unwrap_or_default();
2259 for (sub_id, handle) in drained_subs {
2260 drop(handle);
2261 self.app_context
2262 .subscription_callbacks
2263 .borrow_mut()
2264 .remove(&sub_id);
2265 self.app_context
2266 .subscription_ctx_callbacks
2267 .borrow_mut()
2268 .remove(&sub_id);
2269 }
2270 // Drop any shortcuts the destroyed widget owned. Unlike
2271 // `rebuild_single_widget`, destruction is permanent; if the
2272 // user had overrides, they stay in the graveyard.
2273 self.shortcut_registry.unregister_all_for_owner(widget_id);
2274 self.global_actions.retain(|(owner, _)| *owner != widget_id);
2275 self.text_surfaces.remove(widget_id);
2276 // Bindings from this widget stop being relevant; clean them
2277 // up so the registry doesn't leak dead entries for the
2278 // lifetime of the app.
2279 self.binding_registry.unregister_for_widget(widget_id);
2280 // Keep `gesture_owners` honest — destroying the widget tears
2281 // down its handlers, so the per-frame gesture pass must stop
2282 // visiting it.
2283 self.gesture_owners.remove(&widget_id);
2284 // If focus pointed at the widget about to disappear, drop it
2285 // so later dispatch doesn't anchor intent walks at a dead id
2286 // (which would silently swallow the intent).
2287 if self.focused == Some(widget_id) {
2288 let old = self.focused;
2289 self.set_focused(None);
2290 self.focus_origin = None;
2291 self.update_focus_within_signals(old, None);
2292 self.update_view_focus_signals(old, None);
2293 }
2294 if self.hovered == Some(widget_id) {
2295 let old = self.hovered;
2296 self.set_hovered(None);
2297 self.update_hover_within_signals(old, None);
2298 }
2299 // Symmetric with focus/hover above: a pointer capture anchored at the
2300 // widget about to disappear would otherwise swallow every subsequent
2301 // Move/Up (dispatch rejects inactive targets) until the next layout
2302 // pass runs `revalidate_interaction_state`. Drop it eagerly so capture
2303 // never outlives its owner, even when a destroy happens mid-gesture.
2304 if self.pointer_captured_by == Some(widget_id) {
2305 self.pointer_captured_by = None;
2306 }
2307 // Single-node removal: this function already recursed into the
2308 // children above (honouring re-parenting when `reparent_aware`).
2309 // `arena.destroy` would re-recurse the now-stale `children` list and
2310 // tear down a survivor re-homed out of this subtree.
2311 self.arena.remove_node(widget_id);
2312 }
2313
2314 /// Set the layout direction (LTR/RTL). Marks all widgets as needing layout.
2315 pub fn set_layout_direction(&mut self, direction: crate::environment::LayoutDirection) {
2316 self.layout_direction = direction;
2317 self.arena.mark_all_dirty();
2318 }
2319
2320 /// The current layout direction.
2321 pub fn layout_direction(&self) -> crate::environment::LayoutDirection {
2322 self.layout_direction
2323 }
2324
2325 /// Set OS-level accessibility preferences.
2326 ///
2327 /// Called by `teksilo-app` after querying the platform layer. Updates the
2328 /// values fed into `PaintContext` and `Environment` on subsequent frames.
2329 /// Marks all widgets dirty so the new preferences take effect immediately.
2330 pub fn set_accessibility_preferences(
2331 &mut self,
2332 high_contrast: bool,
2333 reduced_motion: bool,
2334 text_scale_factor: f64,
2335 ) {
2336 let changed = self.prefers_high_contrast != high_contrast
2337 || self.prefers_reduced_motion != reduced_motion
2338 || (self.text_scale_factor - text_scale_factor).abs() > f64::EPSILON;
2339
2340 if changed {
2341 self.prefers_high_contrast = high_contrast;
2342 self.prefers_reduced_motion = reduced_motion;
2343 self.text_scale_factor = text_scale_factor;
2344 // The OS factor feeds the effective text scale (multiplied with the
2345 // user factor), so refresh the cached scaled typography.
2346 self.recompute_effective_theme();
2347 self.arena.mark_all_dirty();
2348 }
2349 }
2350
2351 /// Whether the OS has requested high-contrast mode.
2352 pub fn prefers_high_contrast(&self) -> bool {
2353 self.prefers_high_contrast
2354 }
2355
2356 /// Whether the OS has requested reduced motion.
2357 pub fn prefers_reduced_motion(&self) -> bool {
2358 self.prefers_reduced_motion
2359 }
2360
2361 /// OS text scaling factor (1.0 = normal).
2362 pub fn text_scale_factor(&self) -> f64 {
2363 self.text_scale_factor
2364 }
2365
2366 /// Set the host window HiDPI device scale (physical px per logical px).
2367 /// Called by `teksilo-app` before each layout from
2368 /// `platform_window.scale_factor()`. Surfaced to widgets via
2369 /// `LayoutContext::scale_factor`. No dirty-marking: it rides the layout
2370 /// pass that follows, and a scale change already triggers a relayout.
2371 pub fn set_device_scale_factor(&mut self, scale_factor: f32) {
2372 self.device_scale_factor = scale_factor;
2373 }
2374
2375 /// The host window HiDPI device scale most recently set (1.0 by default).
2376 pub fn device_scale_factor(&self) -> f32 {
2377 self.device_scale_factor
2378 }
2379
2380 /// Mark a widget as clipping its children to its bounds (scroll areas).
2381 pub fn set_clips_children(&mut self, id: WidgetId, clips: bool) {
2382 self.arena.set_clips_children(id, clips);
2383 }
2384
2385 /// Apply a `HandlerSet` to an existing node in the arena, routed
2386 /// into the rebuild-cleared `handlers` slot (the widget's own
2387 /// self-applied handlers).
2388 /// Register any *bound* builder-level accessibility Props
2389 /// (`access_hidden` / `access_label` / `access_description` /
2390 /// `access_value`) at `BindingLevel::AccessibilityOnly`, so that a change
2391 /// to the underlying signal flips `a11y_dirty` and the AccessKit tree
2392 /// re-walks — re-resolving the announced hidden-state / name / description
2393 /// / value — without a visual relayout. Static Props are ignored by
2394 /// `register_if_bound`. Takes the registry explicitly (rather than `&self`)
2395 /// so insertion-path callers can keep a disjoint `&mut self.arena` borrow
2396 /// on the node alive.
2397 fn register_access_prop_bindings(
2398 access: &crate::widget_builder::AccessibilityOverrides,
2399 id: WidgetId,
2400 registry: &crate::binding::BindingRegistry,
2401 ) {
2402 use crate::binding::BindingLevel::AccessibilityOnly;
2403 if let Some(p) = access.hidden.as_ref() {
2404 p.register_if_bound(id, registry, AccessibilityOnly);
2405 }
2406 if let Some(p) = access.label.as_ref() {
2407 p.register_if_bound(id, registry, AccessibilityOnly);
2408 }
2409 if let Some(p) = access.description.as_ref() {
2410 p.register_if_bound(id, registry, AccessibilityOnly);
2411 }
2412 if let Some(p) = access.value.as_ref() {
2413 p.register_if_bound(id, registry, AccessibilityOnly);
2414 }
2415 }
2416
2417 pub(crate) fn apply_self_handler_set(
2418 &mut self,
2419 id: WidgetId,
2420 mut handler_set: crate::widget_builder::HandlerSet,
2421 ) {
2422 // `visible_when` needs the binding registry (which the arena lacks), so
2423 // pull it out here and apply it via `self.visible_when` after.
2424 let visible_when = handler_set.visible_when.take();
2425 // Same reason for the reactive access Props: the arena can't reach the
2426 // registry, so register them here before handing the set to the arena.
2427 if let Some(access) = handler_set.access.as_ref() {
2428 Self::register_access_prop_bindings(access, id, &self.binding_registry);
2429 }
2430 self.arena
2431 .apply_handler_set(id, handler_set, crate::arena::HandlerScope::Own);
2432 if let Some(prop) = visible_when {
2433 self.visible_when(id, prop);
2434 }
2435 }
2436
2437 /// Apply a `HandlerSet` to an existing node as *external* handlers —
2438 /// the kind attached by a composing parent via
2439 /// `BuildContext::apply_handlers(child_id, ...)` or by the
2440 /// `WidgetBuilder` chain at insertion time. These persist across
2441 /// the target widget's own rebuilds.
2442 pub(crate) fn apply_external_handler_set(
2443 &mut self,
2444 id: WidgetId,
2445 mut handler_set: crate::widget_builder::HandlerSet,
2446 ) {
2447 // See `apply_self_handler_set`: route `visible_when` and the reactive
2448 // access Props through the registry (the arena can't reach it).
2449 let visible_when = handler_set.visible_when.take();
2450 if let Some(access) = handler_set.access.as_ref() {
2451 Self::register_access_prop_bindings(access, id, &self.binding_registry);
2452 }
2453 self.arena
2454 .apply_handler_set(id, handler_set, crate::arena::HandlerScope::External);
2455 if let Some(prop) = visible_when {
2456 self.visible_when(id, prop);
2457 }
2458 }
2459
2460 /// Append an accessibility `labelled_by` relation onto an already-mounted
2461 /// node, *preserving* any overrides the widget already carries — unlike
2462 /// `apply_external_handler_set`, which replaces the whole override struct.
2463 /// Used by container widgets (e.g. `FormLayout`) to name a field after its
2464 /// label once both ids are known. Idempotent-ish: re-adding the same target
2465 /// pushes a duplicate, so call once per pairing.
2466 pub(crate) fn push_access_labelled_by(&mut self, id: WidgetId, label_id: WidgetId) {
2467 if let Some(node) = self.arena.get_mut(id) {
2468 node.access_overrides
2469 .get_or_insert_with(|| {
2470 Box::new(crate::widget_builder::AccessibilityOverrides::default())
2471 })
2472 .labelled_by
2473 .push(label_id);
2474 self.a11y_dirty = true;
2475 }
2476 }
2477
2478 /// Append an accessibility `described_by` relation onto an already-mounted
2479 /// node, preserving existing overrides (the `described_by` counterpart of
2480 /// [`push_access_labelled_by`](Self::push_access_labelled_by)).
2481 pub(crate) fn push_access_described_by(&mut self, id: WidgetId, target_id: WidgetId) {
2482 if let Some(node) = self.arena.get_mut(id) {
2483 node.access_overrides
2484 .get_or_insert_with(|| {
2485 Box::new(crate::widget_builder::AccessibilityOverrides::default())
2486 })
2487 .described_by
2488 .push(target_id);
2489 self.a11y_dirty = true;
2490 }
2491 }
2492
2493 /// Set a per-child alignment override on a widget.
2494 pub fn set_alignment(&mut self, id: WidgetId, alignment: teksilo_tokens::Alignment) {
2495 self.arena.set_alignment_override(id, alignment);
2496 }
2497
2498 /// Get the binding registry for registering State→Widget bindings.
2499 pub fn binding_registry(&self) -> &crate::binding::BindingRegistry {
2500 &self.binding_registry
2501 }
2502
2503 /// Shared access to the shortcut registry. Widgets register their
2504 /// default shortcuts through here during `build()` (via
2505 /// `BuildContext::register_shortcut`); settings UIs and
2506 /// persistence layers read and mutate overrides directly.
2507 pub fn shortcut_registry(&self) -> &crate::shortcut::ShortcutRegistry {
2508 &self.shortcut_registry
2509 }
2510
2511 pub fn shortcut_registry_mut(&mut self) -> &mut crate::shortcut::ShortcutRegistry {
2512 &mut self.shortcut_registry
2513 }
2514
2515 /// Install a one-shot key-capture callback, returning a
2516 /// [`CaptureHandle`](crate::shortcut::CaptureHandle) whose `Drop`
2517 /// cancels the capture if it hasn't already fired. The next
2518 /// `KeyDown` the tree receives bypasses shortcut-registry lookup
2519 /// and invokes the callback with:
2520 /// - the captured [`KeyStroke`](crate::shortcut::KeyStroke)
2521 /// - mutable access to the registry (rebind in-place)
2522 /// - a mutable [`EventContext`] (so the handler can also emit
2523 /// commands, send intents, dismiss overlays, …)
2524 ///
2525 /// Calling this while a previous capture is armed creates a
2526 /// **separate** slot; the prior handle, when eventually dropped,
2527 /// cancels only its own (now-orphaned) slot. The new capture
2528 /// wins.
2529 pub fn begin_key_capture(
2530 &mut self,
2531 callback: impl FnOnce(
2532 crate::shortcut::KeyStroke,
2533 &mut crate::shortcut::ShortcutRegistry,
2534 &mut EventContext,
2535 ) + 'static,
2536 ) -> crate::shortcut::CaptureHandle {
2537 let slot: crate::shortcut::KeyCaptureSlot =
2538 std::rc::Rc::new(std::cell::RefCell::new(Some(Box::new(callback))));
2539 self.key_capture = Some(slot.clone());
2540 crate::shortcut::CaptureHandle::new(slot)
2541 }
2542
2543 /// Cancel any currently-armed key capture without invoking it.
2544 /// Equivalent to dropping the [`CaptureHandle`](crate::shortcut::CaptureHandle),
2545 /// but exposed here so callers that lost the handle (or never
2546 /// kept one) can still bail out.
2547 pub fn cancel_key_capture(&mut self) {
2548 if let Some(slot) = self.key_capture.take() {
2549 slot.borrow_mut().take();
2550 }
2551 }
2552
2553 /// Whether a key-capture callback is currently armed.
2554 pub fn is_capturing_keys(&self) -> bool {
2555 self.key_capture
2556 .as_ref()
2557 .map(|slot| slot.borrow().is_some())
2558 .unwrap_or(false)
2559 }
2560
2561 /// Consume any pending key-capture callback. Used internally by
2562 /// the dispatch path — returns the boxed closure so the caller
2563 /// can invoke it once the KeyStroke has been constructed. Also
2564 /// drops the outer `Option<Rc<...>>` so `is_capturing_keys` goes
2565 /// back to `false`.
2566 pub(crate) fn take_key_capture(&mut self) -> Option<crate::shortcut::KeyCaptureCallback> {
2567 let slot = self.key_capture.take()?;
2568 slot.borrow_mut().take()
2569 }
2570
2571 /// Append an [`Action`](crate::action::Action) to a widget's arena
2572 /// node. Invoked by `BuildContext::register_action`; not meant
2573 /// to be called directly.
2574 /// Record that `widget_id` edits text. Replaces any previous registration
2575 /// from the same widget, so a rebuild re-points rather than accumulating.
2576 pub(crate) fn push_text_surface(
2577 &mut self,
2578 widget_id: WidgetId,
2579 surface: std::rc::Rc<dyn crate::text_surface::TextSurface>,
2580 ) {
2581 self.text_surfaces.insert(widget_id, surface);
2582 }
2583
2584 /// A cloneable view of this tree's text surfaces, for a caller that must ask
2585 /// the question later, without a `&WidgetTree` in hand.
2586 pub fn text_surfaces(&self) -> crate::text_surface::TextSurfaces {
2587 self.text_surfaces.clone()
2588 }
2589
2590 /// The text-editing widget that currently holds the keyboard focus.
2591 ///
2592 /// `None` when focus is elsewhere — or nowhere — which is exactly what a
2593 /// host needs in order to know that a text chord is safe to route itself.
2594 pub fn focused_text_surface(
2595 &self,
2596 ) -> Option<std::rc::Rc<dyn crate::text_surface::TextSurface>> {
2597 self.text_surfaces.focused()
2598 }
2599
2600 /// Is the keyboard focus inside a widget that edits text?
2601 ///
2602 /// The cheap half of [`focused_text_surface`](Self::focused_text_surface),
2603 /// for a host that only needs to decide whether to step aside.
2604 pub fn focused_is_text_surface(&self) -> bool {
2605 self.text_surfaces.focused_is_text_surface()
2606 }
2607
2608 pub(crate) fn push_action(&mut self, widget_id: WidgetId, action: crate::action::Action) {
2609 if let Some(node) = self.arena.get_mut(widget_id) {
2610 node.actions.push(action);
2611 }
2612 }
2613
2614 /// Telemetry dispatch tap. Looks up a registered
2615 /// [`crate::telemetry::TelemetryContext`] in `app_state` and emits
2616 /// an `intent.dispatched` event with the intent's name. No-op when
2617 /// no telemetry is configured. Errors and consent gating are
2618 /// handled inside the reporter — this site only needs to call
2619 /// `record`.
2620 fn tap_intent_dispatched(&self, intent: &crate::intent::Intent) {
2621 let Some(tcx) = self
2622 .app_context()
2623 .app_state::<crate::telemetry::TelemetryContext>()
2624 else {
2625 return;
2626 };
2627 let install_id = tcx.reporter.install_id();
2628 let props = [
2629 crate::telemetry::Prop {
2630 key: "name",
2631 value: crate::telemetry::PropValue::StaticStr(intent.name),
2632 },
2633 crate::telemetry::Prop {
2634 key: "source",
2635 value: crate::telemetry::PropValue::Enum {
2636 variant: intent.source.as_str(),
2637 },
2638 },
2639 ];
2640 let event = crate::telemetry::Event {
2641 name: "intent.dispatched",
2642 category: crate::telemetry::EventCategory::Intent,
2643 timestamp: std::time::SystemTime::now(),
2644 install_id,
2645 session_id: &tcx.session_id,
2646 schema_version: tcx.schema_version,
2647 props: &props,
2648 };
2649 tcx.reporter.record(&event);
2650 }
2651
2652 /// Histogram of widget concrete-type names across the active
2653 /// arena. Used by the `widget.census` telemetry emitter to surface
2654 /// "which widgets does this app actually use" data back to the
2655 /// framework. Keyed by
2656 /// `std::any::type_name::<T>()` of the concrete widget — a
2657 /// dotted, fully-qualified path like
2658 /// `teksilo_widgets::button::Button`.
2659 ///
2660 /// `&'static str` keys: `type_name_of_val` returns a
2661 /// compile-time string, so the histogram preserves the static
2662 /// lifetime all the way to the wire-format prop. This avoids
2663 /// any allocation for the type-name strings themselves.
2664 ///
2665 /// Cost: one `Box<dyn Widget>` indirection per active node plus
2666 /// a `HashMap` insert. Sub-millisecond on arenas with thousands
2667 /// of widgets. Safe to call every frame in tests; in production
2668 /// gate behind a periodic ticker (hourly or on-idle).
2669 pub fn widget_type_histogram(&self) -> std::collections::HashMap<&'static str, u32> {
2670 let mut out = std::collections::HashMap::<&'static str, u32>::new();
2671 for id in self.arena.active_ids_iter() {
2672 if let Some(node) = self.arena.get(id) {
2673 // `Widget::type_name` is monomorphized per impl, so
2674 // calling through the vtable correctly resolves to
2675 // the concrete type — `type_name_of_val(&*widget)`
2676 // alone would collapse to `"dyn teksilo_core::widget::Widget"`.
2677 let name: &'static str = node.widget.type_name();
2678 *out.entry(name).or_insert(0) += 1;
2679 }
2680 }
2681 out
2682 }
2683
2684 /// Number of active widgets in the arena. Cheap; matches the
2685 /// totals returned by `widget_type_histogram` when summed.
2686 pub fn active_widget_count(&self) -> usize {
2687 self.arena.active_ids_iter().count()
2688 }
2689
2690 /// Enqueue an intent for dispatch from `source`. Called from
2691 /// `collect_from_ctx` after a handler runs `ctx.send_intent(...)`
2692 /// and from the KeyDown shortcut-interception path.
2693 pub(crate) fn enqueue_intent(
2694 &mut self,
2695 source: WidgetId,
2696 intent: crate::intent::Intent,
2697 propagate_when_disabled: bool,
2698 ) {
2699 self.pending_intents
2700 .push((source, intent, propagate_when_disabled));
2701 }
2702
2703 /// Dispatch every queued intent. Handlers may call
2704 /// `ctx.send_intent(...)` to enqueue more; the loop consumes
2705 /// those too until the queue drains. No ordering guarantee
2706 /// beyond "first-enqueued is first-dispatched"; the `pop` path
2707 /// uses `remove(0)` to keep that FIFO behavior.
2708 pub(crate) fn drain_pending_intents(&mut self, ops: &mut dyn crate::window::WindowOps) {
2709 while !self.pending_intents.is_empty() {
2710 let (source, intent, propagate) = self.pending_intents.remove(0);
2711 self.dispatch_intent(source, intent, propagate, &mut *ops);
2712 }
2713 }
2714
2715 /// Walk `source → root` invoking any [`Action`](crate::action::Action)
2716 /// whose `intent` name matches. The first enabled, `Handled`
2717 /// response stops the walk. A `Propagated` or disabled action
2718 /// (when the shortcut's `propagate_when_disabled` is true) lets
2719 /// the walk continue. A disabled action with
2720 /// `propagate_when_disabled == false` consumes the intent at that
2721 /// level without invoking a handler.
2722 pub(crate) fn dispatch_intent(
2723 &mut self,
2724 source: WidgetId,
2725 intent: crate::intent::Intent,
2726 propagate_when_disabled: bool,
2727 ops: &mut dyn crate::window::WindowOps,
2728 ) {
2729 // Telemetry tap. Single insertion point catches every intent
2730 // — shortcut-driven, programmatic via `send_intent`, etc. —
2731 // because every dispatch funnels through here. A no-op when
2732 // no `TelemetryContext` is registered.
2733 self.tap_intent_dispatched(&intent);
2734
2735 // Pre-compute the source → root chain so the walk doesn't
2736 // need to hold any arena borrow while invoking handlers.
2737 let chain: Vec<WidgetId> = {
2738 let mut v = vec![source];
2739 let mut current = self.arena.parent(source);
2740 while let Some(id) = current {
2741 v.push(id);
2742 current = self.arena.parent(id);
2743 }
2744 v
2745 };
2746
2747 for id in chain {
2748 if !self.arena.is_active(id) || !self.arena.is_enabled(id) {
2749 continue;
2750 }
2751
2752 // Take out the first matching action by intent name so
2753 // we can invoke its FnMut handler without holding an
2754 // arena-wide borrow. The action is reinserted at its
2755 // original position so declaration order is preserved
2756 // for any follow-on dispatch.
2757 let Some((mut action, idx, enabled)) = self.arena.get_mut(id).and_then(|node| {
2758 let idx = node.actions.iter().position(|a| a.intent == intent.name)?;
2759 let enabled = node.actions[idx].is_enabled();
2760 Some((node.actions.remove(idx), idx, enabled))
2761 }) else {
2762 continue;
2763 };
2764
2765 if !enabled {
2766 // Return the action untouched.
2767 if let Some(node) = self.arena.get_mut(id) {
2768 node.actions.insert(idx, action);
2769 }
2770 if propagate_when_disabled {
2771 continue;
2772 }
2773 return;
2774 }
2775
2776 let mut ctx = self.make_event_context(&mut *ops);
2777 let response = (action.handler)(&intent, &mut ctx);
2778 if let Some(node) = self.arena.get_mut(id) {
2779 node.actions.insert(idx, action);
2780 }
2781 self.collect_from_ctx(ctx, id);
2782
2783 match response {
2784 crate::intent::IntentResponse::Handled => return,
2785 crate::intent::IntentResponse::Propagated => continue,
2786 }
2787 }
2788
2789 // Fallback: window-global actions (registered via
2790 // `register_action_global`). The source→root walk found no consuming
2791 // node action, so consult app-global commands — reachable regardless of
2792 // where the intent originated (menu-bar overlay, content, shortcut).
2793 let mut i = 0;
2794 while i < self.global_actions.len() {
2795 let matches = {
2796 let (_, action) = &self.global_actions[i];
2797 action.intent == intent.name && action.is_enabled()
2798 };
2799 if !matches {
2800 i += 1;
2801 continue;
2802 }
2803 // Take the action out so the FnMut handler can run without holding a
2804 // borrow on `self`; reinsert at its slot afterwards.
2805 let (owner, mut action) = self.global_actions.remove(i);
2806 let mut ctx = self.make_event_context(&mut *ops);
2807 let response = (action.handler)(&intent, &mut ctx);
2808 self.global_actions.insert(i, (owner, action));
2809 self.collect_from_ctx(ctx, owner);
2810 match response {
2811 crate::intent::IntentResponse::Handled => return,
2812 crate::intent::IntentResponse::Propagated => {
2813 i += 1;
2814 continue;
2815 }
2816 }
2817 }
2818 }
2819
2820 /// Register a window-global [`Action`](crate::action::Action) owned by
2821 /// `owner`. Consulted as a dispatch fallback (see [`Self::dispatch_intent`]);
2822 /// torn down when `owner` rebuilds or is destroyed. Backs
2823 /// [`BuildContext::register_action_global`](crate::BuildContext::register_action_global).
2824 pub(crate) fn push_global_action(&mut self, owner: WidgetId, action: crate::action::Action) {
2825 self.global_actions.push((owner, action));
2826 }
2827
2828 // --- Window-close request (drained by the app loop) ---
2829
2830 /// Drain the "close this window" flag set by
2831 /// [`EventContext::close_window`] during dispatch. A *guarded* close
2832 /// — the app routes it through the window's close guard.
2833 pub fn take_close_window_request(&mut self) -> bool {
2834 std::mem::replace(&mut self.close_window_requested, false)
2835 }
2836
2837 /// Drain the "close this window, no questions asked" flag set by
2838 /// [`EventContext::close_window_forced`] during dispatch. An
2839 /// *unconditional* close that bypasses the window's close guard.
2840 pub fn take_force_close_request(&mut self) -> bool {
2841 std::mem::replace(&mut self.force_close_requested, false)
2842 }
2843
2844 /// Drain the pending locale switch raised by
2845 /// [`EventContext::set_locale`] during dispatch. The app layer
2846 /// (`WindowManager::drain_pending_locale_requests`) parses the
2847 /// result and routes it through `WindowManager::set_locale` so the
2848 /// `I18nManager`'s active locale, version signal, and layout
2849 /// direction all stay in sync with the tree.
2850 pub fn take_pending_locale_request(&mut self) -> Option<String> {
2851 self.pending_locale_request.take()
2852 }
2853
2854 /// Drain the pending theme switch raised by
2855 /// [`EventContext::set_theme`] during dispatch. The app layer
2856 /// (`WindowManager::drain_pending_theme_requests`) routes it through
2857 /// `WindowManager::set_theme` so the new theme is applied to every
2858 /// window, not just the one whose handler requested it.
2859 pub fn take_pending_theme_request(&mut self) -> Option<crate::styles::Theme> {
2860 self.pending_theme_request.take()
2861 }
2862
2863 /// Drain the pending "follow OS theme" request raised by
2864 /// [`EventContext::follow_system_theme`] during dispatch. The app layer
2865 /// (`WindowManager::drain_pending_follow_system_requests`) switches to
2866 /// `ThemeMode::Native` and recomputes the theme from the OS for every
2867 /// window. Returns `true` if a request was pending.
2868 pub fn take_pending_follow_system_request(&mut self) -> bool {
2869 std::mem::take(&mut self.pending_follow_system_request)
2870 }
2871
2872 /// Drain the pending text-scale change raised by
2873 /// [`EventContext::set_text_scale`] during dispatch. The app layer
2874 /// (`WindowManager::drain_pending_text_scale_requests`) routes it through
2875 /// `WindowManager::set_text_scale` so the new factor is applied to every
2876 /// window, not just the one whose handler requested it.
2877 pub fn take_pending_text_scale_request(&mut self) -> Option<f32> {
2878 self.pending_text_scale_request.take()
2879 }
2880
2881 /// Drain all pending modal requests recorded during event handling.
2882 ///
2883 /// Each request includes the originating widget so higher layers can
2884 /// resolve routing and focus behavior relative to the source tree.
2885 pub fn drain_pending_modal_requests(&mut self) -> Vec<crate::modal::QueuedModalRequest> {
2886 std::mem::take(&mut self.pending_modal_requests)
2887 }
2888
2889 /// Drain whether the current native modal window should be dismissed.
2890 pub fn drain_pending_modal_dismissal(&mut self) -> bool {
2891 std::mem::replace(&mut self.pending_modal_dismissal, false)
2892 }
2893
2894 // --- Widget insertion ---
2895
2896 /// Walk `Widget::declare_shortcuts` for an already-inserted widget
2897 /// and register every returned shortcut with the registry, owned
2898 /// by `id`. Called at insertion AND at rebuild so the declared
2899 /// metadata survives across rebuilds (which `unregister_all_for_owner`
2900 /// would otherwise wipe). Build-time `ctx.register_shortcut` calls
2901 /// upsert handlers on top; the registry is idempotent on id.
2902 pub(crate) fn apply_declared_shortcuts(&mut self, id: WidgetId) {
2903 let declared = self
2904 .arena
2905 .get(id)
2906 .map(|n| n.widget.declare_shortcuts())
2907 .unwrap_or_default();
2908 for shortcut in declared {
2909 self.shortcut_registry.register_owned(shortcut, id);
2910 }
2911 }
2912
2913 /// Internal: insert a widget, call build(), wire children, register clips.
2914 fn insert_widget(&mut self, widget: Box<dyn Widget>) -> WidgetId {
2915 let id = self.arena.insert(widget);
2916
2917 {
2918 if let Some(mut widget_box) = self.arena.take_widget(id) {
2919 if let Some(handler_set) = widget_box.take_handler_set() {
2920 self.arena.restore_widget(id, widget_box);
2921 if let Some(node) = self.arena.get_mut(id) {
2922 // Handlers attached at the widget's creation site
2923 // are external from its own perspective — keep
2924 // them out of the rebuild-cleared `handlers`
2925 // slot so they survive data-driven rebuilds.
2926 node.external_handlers = handler_set.handlers;
2927 node.node_focusable = handler_set.focusable;
2928 node.node_tab_index = handler_set.tab_index;
2929 node.node_cursor = handler_set.cursor;
2930 // `clips_children` and `event_pass_through` are
2931 // node-level flags on `WidgetNode` — they must
2932 // be mirrored here too. Without this an
2933 // `Inner::new().event_pass_through(true)` chain
2934 // silently no-ops (the flag stays at default
2935 // `false`), and any widget wrapped with it
2936 // catches every pointer event in its bounds.
2937 if let Some(clips) = handler_set.clips_children {
2938 node.clips_children = clips;
2939 }
2940 if let Some(pass_through) = handler_set.event_pass_through {
2941 node.event_pass_through = pass_through;
2942 }
2943 if let Some(dead_zone) = handler_set.gesture_dead_zone {
2944 node.gesture_dead_zone = dead_zone;
2945 }
2946 if let Some(keyboard_capture) = handler_set.keyboard_capture {
2947 node.keyboard_capture = keyboard_capture;
2948 }
2949 if let Some(hit_transparent) = handler_set.hit_transparent {
2950 node.hit_transparent = hit_transparent;
2951 }
2952 if handler_set.context_menu_factory.is_some() {
2953 node.context_menu_factory = handler_set.context_menu_factory;
2954 }
2955 if let Some(sig) = handler_set.focus_within {
2956 node.focus_within_signal = Some(sig);
2957 }
2958 if let Some(sig) = handler_set.hover_within {
2959 node.hover_within_signal = Some(sig);
2960 }
2961 // Builder-chained `visible_when: prop`. Mirror of
2962 // `WidgetTree::visible_when`: register a bound prop at
2963 // Relayout, then store it on the node. (Disjoint field
2964 // borrow, like `access_hidden` below.)
2965 if let Some(prop) = handler_set.visible_when {
2966 prop.register_if_bound(
2967 id,
2968 &self.binding_registry,
2969 crate::binding::BindingLevel::Relayout,
2970 );
2971 node.visible_state = Some(prop);
2972 }
2973 // Builder-level accessibility overrides + subtree
2974 // mode. Mirrored here because this insertion path
2975 // bypasses `apply_handler_set`.
2976 if handler_set.access.is_some() {
2977 // Register any bound access_hidden/label/description/
2978 // value Props at AccessibilityOnly so the AT tree
2979 // re-walks when they flip. (Disjoint field borrow:
2980 // `node` borrows `self.arena`, this reads
2981 // `self.binding_registry`.)
2982 if let Some(access) = handler_set.access.as_ref() {
2983 Self::register_access_prop_bindings(
2984 access,
2985 id,
2986 &self.binding_registry,
2987 );
2988 }
2989 node.access_overrides = handler_set.access;
2990 }
2991 if let Some(mode) = handler_set.access_subtree {
2992 node.access_subtree = mode;
2993 }
2994 }
2995 } else {
2996 self.arena.restore_widget(id, widget_box);
2997 }
2998 }
2999 }
3000
3001 // Walk Widget::declare_shortcuts before build() so the
3002 // declared metadata lands in the registry first; if build()
3003 // also registers the same id with a real on_activate, the
3004 // registry upserts (preserving any user override).
3005 self.apply_declared_shortcuts(id);
3006
3007 {
3008 let mut widget_box = match self.arena.take_widget(id) {
3009 Some(widget) => widget,
3010 None => return id,
3011 };
3012 let mut build_ctx = crate::build_context::BuildContext {
3013 tree: self,
3014 composite_id: Some(id),
3015 effect_handles: Vec::new(),
3016 subscription_handles: Vec::new(),
3017 // A first mount has no previous build to inherit ids from.
3018 reusable_sub_ids: Vec::new(),
3019 };
3020 let built_children = widget_box.build(&mut build_ctx);
3021 let effect_handles = std::mem::take(&mut build_ctx.effect_handles);
3022 let subscription_handles = std::mem::take(&mut build_ctx.subscription_handles);
3023
3024 self.arena.restore_widget(id, widget_box);
3025
3026 // Transfer per-widget handles to the node. Both lists are
3027 // stored unconditionally — a leaf widget that registers an
3028 // effect in its build() still needs its ObserverHandle to
3029 // persist (otherwise the effect unregisters the moment
3030 // BuildContext drops).
3031 if let Some(node) = self.arena.get_mut(id) {
3032 node.subscription_handles = subscription_handles;
3033 node.effect_handles = effect_handles;
3034 }
3035
3036 if !built_children.is_empty() {
3037 for &child_id in &built_children {
3038 if let Some(child_node) = self.arena.get_mut(child_id) {
3039 child_node.parent = Some(id);
3040 }
3041 }
3042 if let Some(node) = self.arena.get_mut(id) {
3043 node.children = built_children;
3044 }
3045 }
3046 }
3047
3048 let clips = self
3049 .arena
3050 .get(id)
3051 .is_some_and(|node| node.widget.clips_children());
3052 if clips {
3053 self.arena.set_clips_children(id, true);
3054 }
3055
3056 id
3057 }
3058
3059 /// Add a widget to the tree.
3060 pub fn add(&mut self, widget: impl Widget + 'static) -> WidgetId {
3061 self.insert_widget(Box::new(widget))
3062 }
3063
3064 /// Add a pre-boxed widget to the tree.
3065 pub fn add_boxed(&mut self, widget: Box<dyn Widget>) -> WidgetId {
3066 self.insert_widget(widget)
3067 }
3068
3069 /// Add a widget as a child of another widget.
3070 pub fn add_child(&mut self, parent: WidgetId, widget: impl Widget + 'static) -> WidgetId {
3071 let boxed: Box<dyn Widget> = Box::new(widget);
3072
3073 let id = self.arena.insert_child(parent, boxed);
3074
3075 {
3076 if let Some(mut widget_box) = self.arena.take_widget(id) {
3077 if let Some(handler_set) = widget_box.take_handler_set() {
3078 self.arena.restore_widget(id, widget_box);
3079 if let Some(node) = self.arena.get_mut(id) {
3080 // Creation-site handlers are external (persist
3081 // across the widget's own rebuilds) — see the
3082 // matching block in `insert_widget`.
3083 node.external_handlers = handler_set.handlers;
3084 node.node_focusable = handler_set.focusable;
3085 node.node_tab_index = handler_set.tab_index;
3086 node.node_cursor = handler_set.cursor;
3087 if let Some(clips) = handler_set.clips_children {
3088 node.clips_children = clips;
3089 }
3090 if let Some(pass_through) = handler_set.event_pass_through {
3091 node.event_pass_through = pass_through;
3092 }
3093 if let Some(dead_zone) = handler_set.gesture_dead_zone {
3094 node.gesture_dead_zone = dead_zone;
3095 }
3096 if let Some(keyboard_capture) = handler_set.keyboard_capture {
3097 node.keyboard_capture = keyboard_capture;
3098 }
3099 if let Some(hit_transparent) = handler_set.hit_transparent {
3100 node.hit_transparent = hit_transparent;
3101 }
3102 if handler_set.context_menu_factory.is_some() {
3103 node.context_menu_factory = handler_set.context_menu_factory;
3104 }
3105 if let Some(sig) = handler_set.focus_within {
3106 node.focus_within_signal = Some(sig);
3107 }
3108 if let Some(sig) = handler_set.hover_within {
3109 node.hover_within_signal = Some(sig);
3110 }
3111 // Builder-chained `visible_when: prop`. Same as in
3112 // `insert_widget`.
3113 if let Some(prop) = handler_set.visible_when {
3114 prop.register_if_bound(
3115 id,
3116 &self.binding_registry,
3117 crate::binding::BindingLevel::Relayout,
3118 );
3119 node.visible_state = Some(prop);
3120 }
3121 // Builder-level accessibility overrides + subtree
3122 // mode. Same rationale as in `insert_widget`.
3123 if handler_set.access.is_some() {
3124 // Register any bound access_hidden/label/description/
3125 // value Props at AccessibilityOnly so the AT tree
3126 // re-walks when they flip. (Disjoint field borrow:
3127 // `node` borrows `self.arena`, this reads
3128 // `self.binding_registry`.)
3129 if let Some(access) = handler_set.access.as_ref() {
3130 Self::register_access_prop_bindings(
3131 access,
3132 id,
3133 &self.binding_registry,
3134 );
3135 }
3136 node.access_overrides = handler_set.access;
3137 }
3138 if let Some(mode) = handler_set.access_subtree {
3139 node.access_subtree = mode;
3140 }
3141 }
3142 } else {
3143 self.arena.restore_widget(id, widget_box);
3144 }
3145 }
3146 }
3147
3148 // Same shortcut-declaration walk as `insert_widget` — keeps
3149 // metadata visible from the moment the child mounts, before
3150 // build() runs.
3151 self.apply_declared_shortcuts(id);
3152
3153 {
3154 if let Some(mut widget_box) = self.arena.take_widget(id) {
3155 let mut build_ctx = crate::build_context::BuildContext {
3156 tree: self,
3157 composite_id: Some(id),
3158 effect_handles: Vec::new(),
3159 subscription_handles: Vec::new(),
3160 // A first mount has no previous build to inherit ids from.
3161 reusable_sub_ids: Vec::new(),
3162 };
3163 let built_children = widget_box.build(&mut build_ctx);
3164 let effect_handles = std::mem::take(&mut build_ctx.effect_handles);
3165 let subscription_handles = std::mem::take(&mut build_ctx.subscription_handles);
3166
3167 self.arena.restore_widget(id, widget_box);
3168
3169 // Transfer per-widget handles to the node. See the
3170 // matching block in `insert_widget` — effect and
3171 // subscription handles must persist for leaf widgets
3172 // too, not only composite ones.
3173 if let Some(node) = self.arena.get_mut(id) {
3174 node.subscription_handles = subscription_handles;
3175 node.effect_handles = effect_handles;
3176 }
3177
3178 if !built_children.is_empty() {
3179 for &child_id in &built_children {
3180 if let Some(child_node) = self.arena.get_mut(child_id) {
3181 child_node.parent = Some(id);
3182 }
3183 }
3184 if let Some(node) = self.arena.get_mut(id) {
3185 node.children = built_children;
3186 }
3187 }
3188 }
3189 }
3190
3191 let clips = self
3192 .arena
3193 .get(id)
3194 .is_some_and(|node| node.widget.clips_children());
3195 if clips {
3196 self.arena.set_clips_children(id, true);
3197 }
3198
3199 id
3200 }
3201
3202 // --- Property bindings ---
3203
3204 /// Bind a widget's visibility to a boolean prop or compatibility state binding.
3205 /// When false, the widget is set dormant; when true, it is activated.
3206 /// Accepts `Signal<bool>`, `Prop<bool>`, compatibility state bindings, or plain `bool`.
3207 pub fn visible_when(&mut self, id: WidgetId, state: impl Into<crate::signal::Prop<bool>>) {
3208 let prop = state.into();
3209 prop.register_if_bound(
3210 id,
3211 &self.binding_registry,
3212 crate::binding::BindingLevel::Relayout,
3213 );
3214 if let Some(node) = self.arena.get_mut(id) {
3215 node.visible_state = Some(prop);
3216 }
3217 }
3218
3219 /// Install (or reuse) the activation signal on a node and return a
3220 /// handle to it. The framework sets it to `false` when the node is
3221 /// parked dormant (`Switcher` / `visible_when`) and `true` when it is
3222 /// re-activated — see [`crate::arena::WidgetArena::set_dormant`] /
3223 /// [`activate`](crate::arena::WidgetArena::activate). The returned
3224 /// signal is initialised to the node's current active state. Used by
3225 /// widgets owning a resource outside the paint pass (a native subview)
3226 /// that must hide/show it in lockstep with framework activation.
3227 pub fn activation_signal(&mut self, id: WidgetId) -> crate::signal::Signal<bool> {
3228 if let Some(node) = self.arena.get_mut(id) {
3229 if let Some(existing) = node.activation_signal.clone() {
3230 return existing;
3231 }
3232 let active = node.activation == crate::arena::ActivationState::Active;
3233 let sig = crate::signal::Signal::new(active);
3234 node.activation_signal = Some(sig.clone());
3235 sig
3236 } else {
3237 // Node missing (shouldn't happen in build) — hand back a
3238 // detached signal so the caller still gets a valid handle.
3239 crate::signal::Signal::new(true)
3240 }
3241 }
3242
3243 /// Fire the `activation_signal` of every node that transitioned
3244 /// Active↔Dormant since the last flush. Called at a well-defined tree-level
3245 /// point (the end of `process_state_changes`), never from inside the arena
3246 /// recursion — so an observer (e.g. a `WebView` calling the engine's
3247 /// `set_visible`) runs after the visibility pass has fully committed,
3248 /// matching the `focus_within` / `hover_within` update discipline.
3249 pub(crate) fn flush_activation_signals(&mut self) {
3250 let changes = self.arena.take_activation_changes();
3251 for (id, _recorded) in changes {
3252 // Re-read the node at flush time; it still exists (the transition
3253 // was recorded in the same synchronous operation).
3254 let Some(node) = self.arena.get(id) else {
3255 continue;
3256 };
3257 let Some(sig) = node.activation_signal.clone() else {
3258 continue;
3259 };
3260 // Fire the node's **current** state, not the value recorded at the
3261 // transition, and only when it differs from what observers last
3262 // saw. `pending_activation_changes` is an append-only queue: a
3263 // node parked and re-activated inside one batch records both
3264 // edges, and replaying them in order hands observers a `false`
3265 // that was never observable — the node is already Active by the
3266 // time anyone is told anything.
3267 //
3268 // The in-tree modal path does exactly that on every open: build
3269 // the content, `set_dormant` it, mount the scrim, `activate` it,
3270 // then move focus in. Both edges land in one batch and flush
3271 // *after* the focus dispatch, so the stale `false` arrives last
3272 // and observers act on a state that has already been superseded.
3273 // For a text editor that meant its dormancy handler wiped the
3274 // `has_focus` it had just been granted, and the dialog opened with
3275 // no caret; a `WebView` would have taken a real `set_visible(false)`
3276 // OS call for a subview that never left the screen.
3277 //
3278 // Collapsing to the final state also makes the flush idempotent
3279 // over duplicate ids: the first iteration syncs the signal, the
3280 // rest find it already equal and skip. `Signal::set` notifies
3281 // unconditionally, so the equality guard is what stops the
3282 // redundant fanout.
3283 let active = node.activation == crate::arena::ActivationState::Active;
3284 if sig.get() != active {
3285 sig.set(active);
3286 }
3287 }
3288 }
3289
3290 /// Bind an opacity multiplier (0..1) to a widget. The render walker
3291 /// emits `SetOpacity(value)` before painting the widget's subtree
3292 /// and `RestoreOpacity` afterwards, so the multiplier composes
3293 /// correctly with ancestor opacity scopes via the canvas's stacked
3294 /// opacity model. Bound at `Repaint` level: opacity changes never
3295 /// trigger relayout. Pass any `Prop<f32>` or `Signal<f32>` source
3296 /// (typically an animated signal driven by a `Fade` wrapper).
3297 pub fn set_opacity(&mut self, id: WidgetId, opacity: impl Into<crate::signal::Prop<f32>>) {
3298 let prop = opacity.into();
3299 prop.register_if_bound(
3300 id,
3301 &self.binding_registry,
3302 crate::binding::BindingLevel::RepaintOnly,
3303 );
3304 if let Some(node) = self.arena.get_mut(id) {
3305 node.opacity_prop = Some(prop);
3306 }
3307 }
3308
3309 /// Bind a 2D affine transform to a widget. The render walker emits
3310 /// `PushTransform(value)` before painting the widget's subtree and
3311 /// `PopTransform` afterwards; the renderer composes the transform
3312 /// onto its stack so nested wrappers and widget-internal canvas
3313 /// transforms compose correctly. Bound at `Repaint` level: visual-
3314 /// only transforms never trigger relayout. Wrappers that want the
3315 /// transform's *value change* to also drive layout (e.g.
3316 /// `Scale::reflow(true)`) must additionally bind the *driver*
3317 /// signal to themselves at `Relayout` level — the transform prop
3318 /// itself stays at Repaint. Pass a `Transform2D`, `Signal<Transform2D>`,
3319 /// or `Prop<Transform2D>`.
3320 pub fn set_transform(
3321 &mut self,
3322 id: WidgetId,
3323 transform: impl Into<crate::signal::Prop<teksilo_canvas::Transform2D>>,
3324 ) {
3325 let prop = transform.into();
3326 prop.register_if_bound(
3327 id,
3328 &self.binding_registry,
3329 crate::binding::BindingLevel::RepaintOnly,
3330 );
3331 if let Some(node) = self.arena.get_mut(id) {
3332 node.transform_prop = Some(prop);
3333 // A plain transform is a *self* transform — clear any prior
3334 // content-transform marker so the flag can never go stale if a
3335 // node switches from `set_content_transform` to `set_transform`.
3336 node.content_transform = false;
3337 }
3338 }
3339
3340 /// Like [`set_transform`](Self::set_transform), but marks the transform as
3341 /// a **content** transform: it positions the node's content within a fixed
3342 /// parent-space viewport (the node's bounds) rather than transforming the
3343 /// node itself. Hit-testing then keeps the whole viewport interactive at
3344 /// any pan / zoom. Used by `SceneView`; see
3345 /// `WidgetNode::content_transform`.
3346 pub fn set_content_transform(
3347 &mut self,
3348 id: WidgetId,
3349 transform: impl Into<crate::signal::Prop<teksilo_canvas::Transform2D>>,
3350 ) {
3351 let prop = transform.into();
3352 prop.register_if_bound(
3353 id,
3354 &self.binding_registry,
3355 crate::binding::BindingLevel::RepaintOnly,
3356 );
3357 if let Some(node) = self.arena.get_mut(id) {
3358 node.transform_prop = Some(prop);
3359 node.content_transform = true;
3360 }
3361 }
3362
3363 /// Bind a Gaussian-equivalent blur radius to a widget. The render
3364 /// walker emits `BeginBlurredSubtree { bounds, radius }` before
3365 /// painting the widget's subtree and `EndBlurredSubtree` afterwards;
3366 /// the renderer redirects drawing into an intermediate texture, runs
3367 /// a dual-Kawase blur chain at the requested radius, and composites
3368 /// the blurred result back into the parent pass. Bound at `Repaint`
3369 /// level: blur radius changes never trigger relayout. Sub-perceptual
3370 /// radii (< 0.5) skip the Begin/End pair entirely so animated
3371 /// enable/disable patterns have zero per-frame cost when fully off.
3372 /// Pass any `Prop<f32>` or `Signal<f32>` source.
3373 pub fn set_blur(&mut self, id: WidgetId, radius: impl Into<crate::signal::Prop<f32>>) {
3374 let prop = radius.into();
3375 prop.register_if_bound(
3376 id,
3377 &self.binding_registry,
3378 crate::binding::BindingLevel::RepaintOnly,
3379 );
3380 if let Some(node) = self.arena.get_mut(id) {
3381 node.blur_prop = Some(prop);
3382 }
3383 }
3384
3385 /// Bind a widget's enabled state to a boolean prop or compatibility state binding.
3386 /// When false, the widget and its entire subtree ignore all events but remain
3387 /// visible. Focus traversal skips disabled subtrees and AccessKit marks their
3388 /// nodes as disabled. Accepts `Signal<bool>`, `Prop<bool>`, compatibility state
3389 /// bindings, or plain `bool`.
3390 ///
3391 /// The bound signal registers at `BindingLevel::SubtreeRepaint`: when
3392 /// it flips, the entire subtree rooted at `id` is marked for repaint
3393 /// (not relayout — geometry doesn't change). Leaves like
3394 /// `IconWidget` then re-resolve their role color
3395 /// using the new `PaintContext::effective_enabled` value, so a
3396 /// disabled subtree's icons and text dim automatically.
3397 pub fn enabled_when(&mut self, id: WidgetId, state: impl Into<crate::signal::Prop<bool>>) {
3398 let prop = state.into();
3399 // SubtreeRepaint propagates the visual dirty mark through the
3400 // disabled subtree so leaves re-resolve their role colors.
3401 prop.register_if_bound(
3402 id,
3403 &self.binding_registry,
3404 crate::binding::BindingLevel::SubtreeRepaint,
3405 );
3406 // AccessibilityOnly is orthogonal — it flips `a11y_dirty` so
3407 // AccessKit's `disabled` flag refreshes on the next a11y sync
3408 // (the accessibility walker reads `arena.is_enabled(id)`,
3409 // which is already correct via the prop, but the tree needs
3410 // to be told to rebuild).
3411 prop.register_if_bound(
3412 id,
3413 &self.binding_registry,
3414 crate::binding::BindingLevel::AccessibilityOnly,
3415 );
3416 if let Some(node) = self.arena.get_mut(id) {
3417 node.enabled_state = Some(prop);
3418 }
3419 }
3420
3421 /// Reactive view of "is this widget effectively enabled?" — the AND
3422 /// of the widget's own `enabled_state` and every ancestor's.
3423 /// [`Self::is_enabled`] is the non-reactive equivalent; this method
3424 /// gives composite widgets a `Signal<bool>` for derived state.
3425 ///
3426 /// Leaves (`IconWidget`, `TextWidget`, `RectWidget`) do NOT need this
3427 /// — they receive the resolved bool via
3428 /// [`crate::widget::PaintContext::effective_enabled`] at paint time.
3429 /// This method is for composites that want to derive cursor / custom
3430 /// paint roles / etc. reactively.
3431 ///
3432 /// Install-or-reuse, exactly like [`Self::activation_signal`]: the signal
3433 /// lives on the node and the framework refreshes it from the live arena
3434 /// once per state-change pass (`flush_effective_enabled_signals`).
3435 ///
3436 /// It is deliberately NOT a signal derived by walking the ancestor chain
3437 /// here. A widget's `parent` is still `None` while its own `build()` runs
3438 /// — `insert_widget` inserts the node parentless and wires the parent link
3439 /// only after `build()` returns — so an ancestor walk performed from
3440 /// inside `build()` (which is how every caller uses this) sees an empty
3441 /// chain and would capture the widget's OWN `enabled` prop as the whole
3442 /// answer, permanently. That was a real bug: a Button inside a disabled
3443 /// form stayed painted as if enabled.
3444 ///
3445 /// The value is seeded from the live arena and corrected on the next
3446 /// flush, so a first-`build()` caller (parent not yet wired) and a
3447 /// rebuild caller (parent wired) both converge before anything paints.
3448 pub fn effective_enabled_signal(&mut self, id: WidgetId) -> crate::signal::Signal<bool> {
3449 if let Some(existing) = self
3450 .arena
3451 .get(id)
3452 .and_then(|n| n.effective_enabled_signal.clone())
3453 {
3454 return existing;
3455 }
3456 // Seed from the live tree. Mid-`build()` the parent is not wired yet,
3457 // so this is the widget's own state only; `flush_effective_enabled_signals`
3458 // corrects it against the fully-wired tree before the first paint.
3459 let seed = self.arena.is_enabled(id);
3460 let sig = crate::signal::Signal::new(seed);
3461 let Some(node) = self.arena.get_mut(id) else {
3462 // Node missing (shouldn't happen in build) — hand back a detached
3463 // handle so the caller still gets a valid signal.
3464 return crate::signal::Signal::new(true);
3465 };
3466 node.effective_enabled_signal = Some(sig.clone());
3467 self.arena.watch_effective_enabled(id);
3468 sig
3469 }
3470
3471 /// Refresh every node-resident `effective_enabled_signal` against the live
3472 /// arena, firing observers only where the value actually changed.
3473 ///
3474 /// Unlike [`Self::flush_activation_signals`] this cannot be driven off a
3475 /// change queue: a node's `enabled_state` is a `Prop<bool>` that may be
3476 /// bound to an app `Signal` which flips without the arena being notified,
3477 /// so there is no mutation site at which to record a transition. Instead
3478 /// this recomputes the (cheap, `O(depth)`) ancestor AND for each opted-in
3479 /// node and diffs. Only nodes that called
3480 /// [`Self::effective_enabled_signal`] are visited, so a tree with no
3481 /// interactive widgets pays nothing.
3482 ///
3483 /// Values are collected first and set afterwards: a `Signal::set` observer
3484 /// may mutate the tree, and must not run while the arena is being walked —
3485 /// the same discipline as `flush_activation_signals` and the
3486 /// `focus_within` / `hover_within` updates.
3487 pub(crate) fn flush_effective_enabled_signals(&mut self) {
3488 self.arena.prune_effective_enabled_watchers();
3489 let mut updates: Vec<(crate::signal::Signal<bool>, bool)> = Vec::new();
3490 for id in self.arena.effective_enabled_watchers() {
3491 let Some(sig) = self
3492 .arena
3493 .get(id)
3494 .and_then(|n| n.effective_enabled_signal.clone())
3495 else {
3496 continue;
3497 };
3498 let now = self.arena.is_enabled(id);
3499 if sig.get() != now {
3500 updates.push((sig, now));
3501 }
3502 }
3503 for (sig, value) in updates {
3504 sig.set(value);
3505 }
3506 }
3507
3508 /// Whether a widget is effectively enabled. Returns `false` if the widget
3509 /// itself or any ancestor has `enabled_state` bound to `false`.
3510 pub fn is_enabled(&self, id: WidgetId) -> bool {
3511 self.arena.is_enabled(id)
3512 }
3513
3514 /// Bind a widget's Tab-key participation to a boolean prop or
3515 /// compatibility state binding. When false, the widget is removed
3516 /// from Tab / Shift+Tab traversal (`cycle_focus`) but remains
3517 /// reachable via `request_focus` and arrow-key navigation that
3518 /// calls `request_focus`. Implements the ARIA roving-tabindex
3519 /// pattern (HTML `tabindex="-1"` semantics). Accepts
3520 /// `Signal<bool>`, `Prop<bool>`, or plain `bool`.
3521 pub fn set_tab_stop(&mut self, id: WidgetId, state: impl Into<crate::signal::Prop<bool>>) {
3522 let prop = state.into();
3523 // Bind at the lightest level — tab-stop changes never affect
3524 // layout or paint; cycle_focus reads the current value on
3525 // each Tab keypress.
3526 prop.register_if_bound(
3527 id,
3528 &self.binding_registry,
3529 crate::binding::BindingLevel::RepaintOnly,
3530 );
3531 if let Some(node) = self.arena.get_mut(id) {
3532 node.tab_stop = Some(prop);
3533 }
3534 }
3535
3536 /// Current Tab-key participation for a widget. Returns the value
3537 /// of the `tab_stop` prop if bound, or `true` (the default) when
3538 /// no binding is present. Mirrors the filter used by
3539 /// `cycle_focus` — primarily for tests asserting the
3540 /// roving-tabindex contract.
3541 pub fn tab_stop(&self, id: WidgetId) -> bool {
3542 self.arena
3543 .get(id)
3544 .and_then(|node| node.tab_stop.as_ref())
3545 .map(|prop| prop.get())
3546 .unwrap_or(true)
3547 }
3548
3549 /// Declare `id` as a **traversal-scope boundary** with the given policy.
3550 /// `cycle_focus` then treats the node's subtree as an independent Tab
3551 /// group: `tab_index` values inside it are scoped (they never collide
3552 /// with sibling scopes) and `policy` governs Tab at the scope's ends.
3553 ///
3554 /// The scope node is forced non-focusable — it is a transparent boundary,
3555 /// never itself a Tab stop. Called from `BuildContext::set_traversal_scope`
3556 /// (which the `FocusScope` wrapper widget invokes during `build`), and
3557 /// directly usable from tests with no dependency on the widgets crate.
3558 pub fn set_traversal_scope(
3559 &mut self,
3560 id: WidgetId,
3561 policy: crate::focus::TraversalScopePolicy,
3562 ) {
3563 if let Some(node) = self.arena.get_mut(id) {
3564 node.node_traversal_scope = Some(policy);
3565 node.node_focusable = Some(false);
3566 }
3567 }
3568
3569 /// Remove a previously set traversal-scope marker from `id` (rebuild
3570 /// paths where a `FocusScope` is replaced by a non-scope widget). Leaves
3571 /// `node_focusable` untouched — a later handler-set application resets it.
3572 pub fn clear_traversal_scope(&mut self, id: WidgetId) {
3573 if let Some(node) = self.arena.get_mut(id) {
3574 node.node_traversal_scope = None;
3575 }
3576 }
3577
3578 /// Current traversal-scope policy on `id`, if any. For tests asserting
3579 /// the scope marker contract.
3580 pub fn traversal_scope(&self, id: WidgetId) -> Option<crate::focus::TraversalScopePolicy> {
3581 self.arena
3582 .get(id)
3583 .and_then(|node| node.node_traversal_scope)
3584 }
3585
3586 // --- Theme override ---
3587
3588 /// Set a theme override on a widget. All descendants of this widget
3589 /// will see the modified theme during layout and paint.
3590 /// The override function receives a mutable `Theme` to modify.
3591 ///
3592 /// ```
3593 /// # use teksilo_core::{Widget, LayoutResponse, LayoutContext, widget_tree::WidgetTree};
3594 /// # use teksilo_canvas::{Size, SizeProposal};
3595 /// # use teksilo_tokens::ColorTokens;
3596 /// # #[derive(Debug)] struct MinWidget;
3597 /// # impl Widget for MinWidget {
3598 /// # fn layout_response(&self, _: SizeProposal, _: &LayoutContext) -> LayoutResponse {
3599 /// # Size::new(0.0, 0.0).into()
3600 /// # }
3601 /// # }
3602 /// # let mut tree = WidgetTree::new();
3603 /// # let panel_id = tree.add(MinWidget);
3604 /// tree.set_theme_override(panel_id, |theme| {
3605 /// theme.colors = ColorTokens::dark_default();
3606 /// });
3607 /// ```
3608 pub fn set_theme_override(
3609 &mut self,
3610 id: WidgetId,
3611 f: impl Fn(&mut crate::styles::Theme) + 'static,
3612 ) {
3613 let had_override = self
3614 .arena
3615 .get(id)
3616 .is_some_and(|n| n.theme_override.is_some());
3617 if let Some(node) = self.arena.get_mut(id) {
3618 node.theme_override = Some(crate::environment::ThemeOverride { func: Box::new(f) });
3619 node.dirty.needs_layout = true;
3620 node.dirty.needs_paint = true;
3621 }
3622 if !had_override {
3623 self.arena.theme_override_count += 1;
3624 }
3625 }
3626
3627 /// Get the resolved theme for a specific widget (applying ancestor overrides).
3628 pub fn resolved_theme(&self, id: WidgetId) -> crate::styles::Theme {
3629 self.arena.resolve_theme(id, &self.theme).into_owned()
3630 }
3631}
3632
3633impl Default for WidgetTree {
3634 fn default() -> Self {
3635 Self::new()
3636 }
3637}
3638
3639#[cfg(test)]
3640mod activation_signal_tests {
3641 use super::*;
3642 use crate::build_context::BuildContext;
3643 use crate::signal::Signal;
3644 use crate::widget::{LayoutContext, LayoutResponse, Widget};
3645 use teksilo_canvas::SizeProposal;
3646
3647 /// A leaf that, on build, opts into its activation signal and mirrors it
3648 /// into an out-of-band signal the test can read.
3649 #[derive(Debug)]
3650 struct ActivationProbe {
3651 log: Signal<Vec<bool>>,
3652 }
3653
3654 impl Widget for ActivationProbe {
3655 fn build(&mut self, ctx: &mut BuildContext) -> Vec<WidgetId> {
3656 let id = ctx.self_id();
3657 let vis = ctx.activation_signal(id);
3658 let log = self.log.clone();
3659 ctx.effect(&vis, move |active| {
3660 let mut v = log.get();
3661 v.push(*active);
3662 log.set(v);
3663 });
3664 Vec::new()
3665 }
3666
3667 fn layout_response(&self, proposal: SizeProposal, _ctx: &LayoutContext) -> LayoutResponse {
3668 proposal.resolve(10.0, 10.0).into()
3669 }
3670 }
3671
3672 /// A widget that enqueues a post-mount action via `run_after_mount` has it
3673 /// run exactly once, with a real `EventContext`, when the tree drains
3674 /// (`run_mount_actions`) — and `has_pending_mount_actions` reflects the
3675 /// queue state.
3676 #[derive(Debug)]
3677 struct MountActionProbe {
3678 ran: Signal<u32>,
3679 }
3680
3681 impl Widget for MountActionProbe {
3682 fn build(&mut self, ctx: &mut BuildContext) -> Vec<WidgetId> {
3683 let ran = self.ran.clone();
3684 ctx.run_after_mount(move |_ectx| ran.set(ran.get() + 1));
3685 Vec::new()
3686 }
3687
3688 fn layout_response(&self, proposal: SizeProposal, _ctx: &LayoutContext) -> LayoutResponse {
3689 proposal.resolve(10.0, 10.0).into()
3690 }
3691 }
3692
3693 #[test]
3694 fn run_after_mount_runs_once_on_drain() {
3695 let mut tree = WidgetTree::new();
3696 let ran = Signal::new(0_u32);
3697 tree.add(MountActionProbe { ran: ran.clone() });
3698 tree.layout(SizeProposal::exact(100.0, 100.0));
3699
3700 // Queued during build, not yet run.
3701 assert!(tree.has_pending_mount_actions());
3702 assert_eq!(ran.get(), 0);
3703
3704 // Drain with a Noop sink (as headless callers do).
3705 tree.run_mount_actions(&mut crate::window::NoopWindowOps);
3706 assert_eq!(ran.get(), 1);
3707 assert!(!tree.has_pending_mount_actions());
3708
3709 // Draining again is a no-op (the queue is empty).
3710 tree.run_mount_actions(&mut crate::window::NoopWindowOps);
3711 assert_eq!(ran.get(), 1);
3712 }
3713
3714 #[test]
3715 fn activation_signal_fires_on_dormant_and_reactivate() {
3716 let mut tree = WidgetTree::new();
3717 let log = Signal::new(Vec::<bool>::new());
3718 let probe = tree.add(ActivationProbe { log: log.clone() });
3719
3720 // Gate the probe's visibility on a signal.
3721 let visible = Signal::new(true);
3722 tree.visible_when(probe, visible.clone());
3723 tree.layout(SizeProposal::exact(100.0, 100.0));
3724
3725 // Initially active: effect registration alone fires nothing.
3726 assert_eq!(log.get(), Vec::<bool>::new());
3727
3728 // Hide → dormant → activation signal false.
3729 visible.set(false);
3730 tree.layout(SizeProposal::exact(100.0, 100.0));
3731 assert_eq!(log.get(), vec![false]);
3732
3733 // Show → active → activation signal true.
3734 visible.set(true);
3735 tree.layout(SizeProposal::exact(100.0, 100.0));
3736 assert_eq!(log.get(), vec![false, true]);
3737
3738 // Redundant relayout while active fires nothing new.
3739 tree.layout(SizeProposal::exact(100.0, 100.0));
3740 assert_eq!(log.get(), vec![false, true]);
3741 }
3742
3743 /// **A node parked and re-woken before the flush never looks dormant.**
3744 ///
3745 /// `pending_activation_changes` is an append-only queue, so this records
3746 /// two edges; replaying them in order would hand observers a `false` that
3747 /// was already superseded — for a state signal that is a lie, not a
3748 /// history. `present_in_tree_modal_request` takes exactly this route on
3749 /// every dialog (build the content, park it, mount the scrim, wake it,
3750 /// *then* move focus in), and the stale `false` landed after the focus
3751 /// dispatch: a text editor's dormancy handler wiped the focus it had just
3752 /// been granted and the dialog opened with no caret.
3753 #[test]
3754 fn a_park_and_wake_inside_one_batch_fires_nothing() {
3755 let mut tree = WidgetTree::new();
3756 let log = Signal::new(Vec::<bool>::new());
3757 let probe = tree.add(ActivationProbe { log: log.clone() });
3758 tree.layout(SizeProposal::exact(100.0, 100.0));
3759 assert_eq!(log.get(), Vec::<bool>::new());
3760
3761 tree.set_dormant(probe);
3762 tree.activate(probe);
3763 tree.layout(SizeProposal::exact(100.0, 100.0));
3764 assert_eq!(
3765 log.get(),
3766 Vec::<bool>::new(),
3767 "a node that ends the batch where it started never observably \
3768 changed — firing the intermediate `false` makes observers act on \
3769 a state that was never visible",
3770 );
3771
3772 // The converse still reports: a batch with a *net* transition fires
3773 // once, with the state the node actually ended in.
3774 tree.activate(probe);
3775 tree.set_dormant(probe);
3776 tree.layout(SizeProposal::exact(100.0, 100.0));
3777 assert_eq!(
3778 log.get(),
3779 vec![false],
3780 "a net Active→Dormant batch must still report, exactly once",
3781 );
3782
3783 tree.activate(probe);
3784 tree.layout(SizeProposal::exact(100.0, 100.0));
3785 assert_eq!(log.get(), vec![false, true]);
3786 }
3787}
3788
3789#[cfg(test)]
3790mod visible_when_builder_tests {
3791 use super::*;
3792 use crate::signal::{Prop, Signal};
3793 use crate::widget_builder::WidgetBuilder;
3794
3795 /// `.visible_when(signal)` on any widget builder threads a *bound*
3796 /// visibility prop onto the inserted node — so `teksu!`'s property form
3797 /// (`Widget { visible_when: sig }`) reaches the same `node.visible_state`
3798 /// slot as the imperative `ctx.visible_when(id, sig)`.
3799 #[test]
3800 fn visible_when_builder_binds_node_visibility() {
3801 let mut tree = WidgetTree::new();
3802 let shown = Signal::new(false);
3803 let id = tree.add(crate::test_widgets::FillWidget::new().visible_when(shown.clone()));
3804
3805 let node = tree.arena.get(id).expect("node exists");
3806 assert!(
3807 matches!(node.visible_state, Some(Prop::Bound(_))),
3808 "`.visible_when(Signal)` must store a bound visibility prop"
3809 );
3810 }
3811
3812 /// A static `bool` is accepted too (`Prop::Static`), matching
3813 /// `ctx.visible_when` / `access_hidden` semantics.
3814 #[test]
3815 fn visible_when_builder_accepts_static_bool() {
3816 let mut tree = WidgetTree::new();
3817 let id = tree.add(crate::test_widgets::FillWidget::new().visible_when(false));
3818
3819 let node = tree.arena.get(id).expect("node exists");
3820 assert!(matches!(node.visible_state, Some(Prop::Static(false))));
3821 }
3822}
3823
3824#[cfg(test)]
3825mod text_scale_tests {
3826 use super::*;
3827
3828 #[test]
3829 fn effective_theme_starts_equal_to_theme() {
3830 let tree = WidgetTree::new();
3831 assert_eq!(
3832 tree.effective_theme.typography.body.size,
3833 tree.theme.typography.body.size
3834 );
3835 assert_eq!(tree.user_text_scale(), 1.0);
3836 }
3837
3838 #[test]
3839 fn effective_text_scale_and_signal_track_the_combined_factor() {
3840 let mut tree = WidgetTree::new();
3841 assert_eq!(tree.effective_text_scale(), 1.0);
3842 assert_eq!(tree.text_scale_signal().get(), 1.0);
3843
3844 tree.set_user_text_scale(1.5);
3845 assert!((tree.effective_text_scale() - 1.5).abs() < 0.001);
3846 assert!((tree.text_scale_signal().get() - 1.5).abs() < 0.001);
3847
3848 // OS preference multiplies in.
3849 tree.set_accessibility_preferences(false, false, 2.0);
3850 assert!((tree.effective_text_scale() - 3.0).abs() < 0.01);
3851 assert!((tree.text_scale_signal().get() - 3.0).abs() < 0.01);
3852 }
3853
3854 #[test]
3855 fn set_user_text_scale_scales_effective_typography() {
3856 let mut tree = WidgetTree::new();
3857 let base = tree.theme.typography.body.size;
3858 tree.set_user_text_scale(1.5);
3859 assert!((tree.effective_theme.typography.body.size - base * 1.5).abs() < 0.001);
3860 // The unscaled base theme is untouched.
3861 assert_eq!(tree.theme.typography.body.size, base);
3862 }
3863
3864 #[test]
3865 fn set_theme_preserves_existing_user_scale() {
3866 let mut tree = WidgetTree::new();
3867 tree.set_user_text_scale(2.0);
3868 let dark = crate::presets::intui::dark();
3869 let dark_base = dark.typography.body.size;
3870 tree.set_theme(dark);
3871 assert!((tree.effective_theme.typography.body.size - dark_base * 2.0).abs() < 0.001);
3872 }
3873
3874 #[test]
3875 fn os_text_scale_multiplies_with_user_scale() {
3876 let mut tree = WidgetTree::new();
3877 let base = tree.theme.typography.body.size;
3878 tree.set_user_text_scale(1.5);
3879 // OS preference reports 1.2 → combined 1.8.
3880 tree.set_accessibility_preferences(false, false, 1.2);
3881 assert!((tree.effective_theme.typography.body.size - base * 1.8).abs() < 0.01);
3882 }
3883
3884 #[test]
3885 fn same_scale_is_a_noop_and_factor_is_clamped() {
3886 let mut tree = WidgetTree::new();
3887 tree.set_user_text_scale(1.5);
3888 // Re-setting the same value should not panic / change anything.
3889 tree.set_user_text_scale(1.5);
3890 assert_eq!(tree.user_text_scale(), 1.5);
3891 // Out-of-range clamps into [0.25, 8.0].
3892 tree.set_user_text_scale(100.0);
3893 assert_eq!(tree.user_text_scale(), 8.0);
3894 }
3895}
3896
3897/// Covers the `WidgetTree`-level facts
3898/// `teksilo_app::WindowManager::request_redraw_needing_render` (the
3899/// targeted cross-window redraw added for shared-`Signal` dispatch
3900/// fan-out) relies on. Neither test touches windows at all — they exist
3901/// to pin down `needs_render()`'s contract in isolation, since
3902/// teksilo-app cannot stand up a real `PlatformWindow` in a unit test.
3903#[cfg(test)]
3904mod cross_window_redraw_signal_tests {
3905 use super::*;
3906 use crate::signal::Signal;
3907 use crate::test_widgets::{FillWidget, StackWidget};
3908 use teksilo_canvas::SizeProposal;
3909
3910 /// The premise the fix acts on, AND the trap a naive fix would fall
3911 /// into. A `Signal` shared by two independent trees (standing in for
3912 /// two windows) is supposed to dirty both when mutated, even though
3913 /// only one of them is the tree whose dispatch made the mutation —
3914 /// but `Signal::set` only flips a dirty flag on the signal itself and
3915 /// in the `BindingRegistry`; nothing walks that into a tree's
3916 /// `needs_layout` / `needs_paint` bits (what `needs_render()` reads)
3917 /// except that tree's OWN `process_state_changes`, run at the top of
3918 /// its OWN `layout()`. So immediately after the mutation, with
3919 /// neither tree having re-run `layout()`, BOTH read clean — a naive
3920 /// "just check `needs_render()`" cross-window redraw would see
3921 /// nothing to do and stay a permanent no-op. Once tree B's `layout()`
3922 /// runs (what `request_redraw_needing_render` does for every window
3923 /// before checking it), the same mutation is finally visible there.
3924 ///
3925 /// Each tree wraps its gated leaf in a `StackWidget` parent (rather
3926 /// than gating a bare root leaf) so the fact under test — an ACTIVE
3927 /// widget ending up dirty — is unambiguous: `any_needs_layout()` /
3928 /// `any_needs_paint()` only ever look at `Active` nodes, and a leaf
3929 /// that itself goes dormant is deliberately excluded from both (a
3930 /// hidden widget has nothing to paint). What must go dirty here is
3931 /// the STILL-ACTIVE stack, via `mark_ancestors_need_layout` — the
3932 /// same mechanism that makes a real window's content re-flow around
3933 /// a child that just appeared or disappeared.
3934 #[test]
3935 fn a_shared_signal_mutation_only_shows_up_after_that_trees_own_layout_reconciles_it() {
3936 let shared = Signal::new(true);
3937
3938 let mut tree_a = WidgetTree::new();
3939 let stack_a = tree_a.add(StackWidget::new());
3940 let id_a = tree_a.add_child(stack_a, FillWidget::new());
3941 tree_a.visible_when(id_a, shared.clone());
3942
3943 let mut tree_b = WidgetTree::new();
3944 let stack_b = tree_b.add(StackWidget::new());
3945 let id_b = tree_b.add_child(stack_b, FillWidget::new());
3946 tree_b.visible_when(id_b, shared.clone());
3947
3948 let proposal = SizeProposal::exact(100.0, 100.0);
3949
3950 // Bring both to the same clean baseline a real event loop reaches
3951 // after its initial layout + paint.
3952 tree_a.layout(proposal);
3953 tree_a.render();
3954 tree_b.layout(proposal);
3955 tree_b.render();
3956 assert!(!tree_a.needs_render(), "precondition: tree A starts clean");
3957 assert!(!tree_b.needs_render(), "precondition: tree B starts clean");
3958
3959 // Simulate a handler mutating the shared Signal during tree A's
3960 // dispatch. Neither tree re-runs layout() here yet.
3961 shared.set(false);
3962
3963 assert!(
3964 !tree_a.needs_render(),
3965 "the mutation alone does not retroactively dirty tree A either — \
3966 a Signal write cannot poke an arena directly, only the next \
3967 process_state_changes (inside layout()) can"
3968 );
3969 assert!(
3970 !tree_b.needs_render(),
3971 "and tree B reads exactly as clean as tree A does at this point — \
3972 checking needs_render() without reconciling first cannot tell them apart"
3973 );
3974
3975 // ...but they are NOT indistinguishable to `needs_reconcile()`,
3976 // which is what `request_redraw_needing_render` actually gates
3977 // its reconcile on. Both trees observe the shared Signal, so
3978 // both report pending reactive work here — and asking is
3979 // read-only, so asking tree A first does not answer for tree B.
3980 assert!(
3981 tree_a.needs_reconcile() && tree_b.needs_reconcile(),
3982 "both trees must report pending reactive work from the shared write"
3983 );
3984
3985 // This is what `request_redraw_needing_render` does for a window
3986 // whose gate is open — reconcile at the window's OWN current
3987 // size, which is what walks a pending Signal-driven change into
3988 // the arena.
3989 tree_b.layout(proposal);
3990
3991 assert!(
3992 tree_b.needs_render(),
3993 "tree B, which merely OBSERVES the shared Signal, is now dirty — \
3994 this is the cross-tree fan-out request_redraw_needing_render \
3995 exists to notice (via its own reconcile-then-check) and repaint"
3996 );
3997 assert!(
3998 !tree_b.needs_reconcile(),
3999 "and having reconciled, tree B's gate closes again"
4000 );
4001 assert!(
4002 tree_a.needs_reconcile(),
4003 "while tree A — which has NOT reconciled — is still waiting; one \
4004 window's reconcile must never close another's gate"
4005 );
4006 }
4007
4008 /// The gate `request_redraw_needing_render` gained must stay SHUT for
4009 /// a window with nothing reactive pending, or it saves nothing: that
4010 /// method runs after every dispatched event, and an open gate costs
4011 /// a full `layout_with_ops` — a dozen per-frame passes (pending
4012 /// animations, frame tick, scheduler tick, drag tick,
4013 /// `process_state_changes`, tooltips, four overlay passes) before it
4014 /// reaches the geometry short-circuit, for every open window, on
4015 /// every event of a fast mouse-move stream.
4016 #[test]
4017 fn needs_reconcile_is_false_for_an_idle_tree() {
4018 let shared = Signal::new(true);
4019 let mut idle = WidgetTree::new();
4020 let stack = idle.add(StackWidget::new());
4021 let leaf = idle.add_child(stack, FillWidget::new());
4022 idle.visible_when(leaf, shared.clone());
4023 idle.layout(SizeProposal::exact(100.0, 100.0));
4024 idle.render();
4025
4026 assert!(!idle.needs_reconcile(), "nothing written — gate shut");
4027 assert!(!idle.needs_reconcile(), "and asking does not open it");
4028
4029 shared.set(false);
4030 assert!(idle.needs_reconcile(), "a write opens it");
4031 idle.layout(SizeProposal::exact(100.0, 100.0));
4032 assert!(!idle.needs_reconcile(), "reconciling closes it again");
4033 }
4034
4035 /// A *pending* `animate_to` contributes no scheduler deadline until
4036 /// `process_pending_animations` promotes it, so `next_timer_deadline`
4037 /// (and therefore `request_redraw_due`) cannot see it. The gate must,
4038 /// or arming an animation from another window's handler would leave
4039 /// it parked until something unrelated woke the window.
4040 #[test]
4041 fn needs_reconcile_sees_an_animation_armed_but_not_yet_started() {
4042 let mut tree = WidgetTree::new();
4043 let id = tree.add(FillWidget::new());
4044 tree.layout(SizeProposal::exact(50.0, 50.0));
4045 tree.render();
4046
4047 // Registered but deliberately NOT bound to any widget, so the
4048 // binding-registry term cannot be what notices it.
4049 let anim = Signal::new_animated(0.0_f32);
4050 tree.register_animated_signal(&anim, id);
4051 assert!(!tree.needs_reconcile(), "precondition: nothing armed yet");
4052
4053 anim.animate_to(
4054 1.0,
4055 std::time::Duration::from_millis(200),
4056 teksilo_tokens::Easing::Linear,
4057 );
4058 assert!(
4059 tree.needs_reconcile(),
4060 "an armed-but-unstarted animation is reactive work only layout() can pick up"
4061 );
4062 assert!(
4063 anim.has_pending_animation(),
4064 "and asking must not have consumed the request"
4065 );
4066
4067 tree.layout(SizeProposal::exact(50.0, 50.0));
4068 assert!(
4069 !anim.has_pending_animation(),
4070 "the reconcile promoted it into the scheduler"
4071 );
4072 }
4073
4074 /// An animation armed *after* the wall clock has overtaken the simulated one
4075 /// must still run.
4076 ///
4077 /// `layout` promotes a pending `animate_to` into the scheduler; once
4078 /// `tick_animations` is driving the tree, the scheduler is only ever ticked at
4079 /// `sim_clock`. Stamping the promotion with `Instant::now()` therefore put the
4080 /// start in the scheduler's *future* the moment a test's real time outran the
4081 /// simulated time it had asked for — and a start in the future does not run
4082 /// slow, it does not run at all. That made animated headless tests a function
4083 /// of machine load: green run alone, frozen once a full suite filled the cores
4084 /// and stretched each test's wall-clock time past its simulated budget.
4085 ///
4086 /// The two clocks below are the shape of that: 90 ms simulated against at
4087 /// least 100 ms real, so simulated time never catches up. Under the old
4088 /// behaviour the animation stays pinned at its start value forever.
4089 #[test]
4090 fn an_animation_armed_after_real_time_outran_the_sim_clock_still_runs() {
4091 let mut tree = WidgetTree::new();
4092 let id = tree.add(FillWidget::new());
4093 tree.layout(SizeProposal::exact(50.0, 50.0));
4094
4095 // Put the tree in simulated time, then let the wall clock get ahead of it.
4096 tree.tick_animations(std::time::Duration::from_millis(10));
4097 std::thread::sleep(std::time::Duration::from_millis(100));
4098
4099 let anim = Signal::new_animated(0.0_f32);
4100 tree.register_animated_signal(&anim, id);
4101 anim.animate_to(
4102 1.0,
4103 std::time::Duration::from_millis(50),
4104 teksilo_tokens::Easing::Linear,
4105 );
4106 tree.layout(SizeProposal::exact(50.0, 50.0));
4107
4108 // 80 ms of simulated time against a 50 ms animation: comfortably finished
4109 // on the only clock the scheduler is ever ticked with, and still short of
4110 // the ~100 ms of real time that has passed.
4111 tree.tick_animations(std::time::Duration::from_millis(80));
4112
4113 assert_eq!(
4114 anim.get(),
4115 1.0,
4116 "the animation must be measured against the clock it is ticked with, \
4117 not the wall clock that has already run past it"
4118 );
4119 assert!(
4120 !tree.has_active_animations(),
4121 "and having reached its target it must be off the scheduler"
4122 );
4123 }
4124
4125 /// `needs_render()` (paint/layout dirt only) must stay `false` while a
4126 /// per-frame `Signal<f32>` animation is merely *running*, with nothing
4127 /// new to paint. `request_redraw_needing_render` filters on
4128 /// `needs_render()`, not the broader `needs_redraw()`, precisely so a
4129 /// window with a live animation isn't forced into an extra immediate
4130 /// redraw on every sibling-window event — that would defeat the 60 Hz
4131 /// `WaitUntil` pacing those animations already get elsewhere and
4132 /// reintroduce the uncapped free-running redraw bug that pacing was
4133 /// written to remove.
4134 #[test]
4135 fn needs_render_excludes_a_running_animation_with_no_dirty_paint() {
4136 let mut tree = WidgetTree::new();
4137 let id = tree.add(FillWidget::new());
4138 tree.layout(SizeProposal::exact(50.0, 50.0));
4139 tree.render();
4140 assert!(!tree.needs_render(), "precondition: tree starts clean");
4141 assert!(!tree.needs_redraw(), "precondition: nothing running yet");
4142
4143 let anim = Signal::new_animated(0.0_f32);
4144 tree.register_animated_signal(&anim, id);
4145 anim.animate_to(
4146 1.0,
4147 std::time::Duration::from_millis(200),
4148 teksilo_tokens::Easing::Linear,
4149 );
4150 // `process_pending_animations` (which picks up the pending
4151 // `animate_to` and starts it on the scheduler) runs inside `layout`.
4152 tree.layout(SizeProposal::exact(50.0, 50.0));
4153
4154 assert!(
4155 tree.needs_redraw(),
4156 "an animation just started, so needs_redraw() (has_running()) must be true"
4157 );
4158 assert!(
4159 !tree.needs_render(),
4160 "but nothing is actually dirty for paint/layout — needs_render() must stay false, \
4161 which is the whole point of using it (not needs_redraw()) as the cross-window filter"
4162 );
4163 }
4164}
4165
4166#[cfg(test)]
4167mod effective_enabled_signal_tests {
4168 use super::*;
4169 use crate::build_context::BuildContext;
4170 use crate::signal::Signal;
4171 use crate::widget::{LayoutContext, LayoutResponse, Widget};
4172 use std::cell::RefCell;
4173 use std::rc::Rc;
4174 use teksilo_canvas::SizeProposal;
4175
4176 type SignalSlot = Rc<RefCell<Option<Signal<bool>>>>;
4177
4178 /// A leaf that opts into `effective_enabled_signal` from inside its own
4179 /// `build()` — the only way real widgets use it, and the case that was
4180 /// broken. It publishes the handle so the test can read the live value.
4181 #[derive(Debug)]
4182 struct EnabledProbe {
4183 out: SignalSlot,
4184 }
4185
4186 impl Widget for EnabledProbe {
4187 fn build(&mut self, ctx: &mut BuildContext) -> Vec<WidgetId> {
4188 let id = ctx.self_id();
4189 let sig = ctx.effective_enabled_signal(id);
4190 // Also pins that the signal is *mutable*: the previous derived
4191 // implementation panicked here with "observe() is only supported
4192 // on mutable signals", which is why widgets could not use
4193 // `ctx.effect` to react to being disabled.
4194 ctx.effect(&sig, |_| {});
4195 *self.out.borrow_mut() = Some(sig);
4196 Vec::new()
4197 }
4198
4199 fn layout_response(&self, proposal: SizeProposal, _ctx: &LayoutContext) -> LayoutResponse {
4200 proposal.resolve(10.0, 10.0).into()
4201 }
4202 }
4203
4204 /// A composite that adds the probe through the ordinary `ctx.add` idiom, so
4205 /// the child is inserted PARENTLESS and builds before its parent link is
4206 /// wired — the exact situation that defeated the old
4207 /// walk-the-ancestors-at-call-time implementation.
4208 #[derive(Debug)]
4209 struct Form {
4210 enabled: Signal<bool>,
4211 out: SignalSlot,
4212 }
4213
4214 impl Widget for Form {
4215 fn build(&mut self, ctx: &mut BuildContext) -> Vec<WidgetId> {
4216 let id = ctx.self_id();
4217 ctx.enabled_when(id, self.enabled.clone());
4218 vec![ctx.add(EnabledProbe {
4219 out: self.out.clone(),
4220 })]
4221 }
4222
4223 fn layout_response(&self, proposal: SizeProposal, _ctx: &LayoutContext) -> LayoutResponse {
4224 proposal.resolve(10.0, 10.0).into()
4225 }
4226 }
4227
4228 fn mount_form(enabled: Signal<bool>) -> (WidgetTree, WidgetId, Signal<bool>) {
4229 let out: SignalSlot = Rc::new(RefCell::new(None));
4230 let mut tree = WidgetTree::new();
4231 let form = tree.add(Form {
4232 enabled,
4233 out: out.clone(),
4234 });
4235 tree.layout(SizeProposal::exact(100.0, 100.0));
4236 let sig = out.borrow().clone().expect("probe published its signal");
4237 (tree, form, sig)
4238 }
4239
4240 /// THE REGRESSION. A widget whose own `enabled` is untouched must still
4241 /// report disabled when an ANCESTOR is disabled. This failed before the
4242 /// signal became node-resident: `insert_widget` inserts the node with
4243 /// `parent: None` and wires the parent only after `build()` returns, so an
4244 /// ancestor walk done during `build()` saw an empty chain and captured
4245 /// "enabled" for the widget's whole life.
4246 #[test]
4247 fn tracks_an_ancestor_disabled_before_mount() {
4248 let (_tree, _form, sig) = mount_form(Signal::new(false));
4249 assert!(
4250 !sig.get(),
4251 "a child of a disabled ancestor must report effectively-disabled"
4252 );
4253 }
4254
4255 /// The live case: the ancestor's bound signal flips after mount. The child
4256 /// must follow, in both directions, with no rebuild.
4257 #[test]
4258 fn follows_an_ancestor_flipping_after_mount() {
4259 let enabled = Signal::new(true);
4260 let (mut tree, _form, sig) = mount_form(enabled.clone());
4261 assert!(sig.get(), "starts enabled");
4262
4263 enabled.set(false);
4264 tree.layout(SizeProposal::exact(100.0, 100.0));
4265 assert!(!sig.get(), "child follows the ancestor going disabled");
4266
4267 enabled.set(true);
4268 tree.layout(SizeProposal::exact(100.0, 100.0));
4269 assert!(sig.get(), "and follows it coming back");
4270 }
4271
4272 /// A widget's own `enabled_state` still works on its own.
4273 #[test]
4274 fn honours_the_widgets_own_state() {
4275 let out: SignalSlot = Rc::new(RefCell::new(None));
4276 let mut tree = WidgetTree::new();
4277 let probe = tree.add(EnabledProbe { out: out.clone() });
4278 tree.enabled_when(probe, false);
4279 tree.layout(SizeProposal::exact(100.0, 100.0));
4280 let sig = out.borrow().clone().unwrap();
4281 assert!(!sig.get(), "own enabled_state alone disables");
4282 }
4283
4284 /// The signal must agree with the paint-time bool the render walker
4285 /// computes. If they disagreed, role-driven chrome (which dims from
4286 /// `PaintContext::effective_enabled`) and signal-driven chrome (which dims
4287 /// from this signal) would grey out at different moments.
4288 #[test]
4289 fn agrees_with_the_paint_time_effective_enabled() {
4290 let enabled = Signal::new(true);
4291 let (mut tree, form, sig) = mount_form(enabled.clone());
4292 let probe = tree.children(form)[0];
4293
4294 for value in [false, true, false] {
4295 enabled.set(value);
4296 tree.layout(SizeProposal::exact(100.0, 100.0));
4297 assert_eq!(
4298 sig.get(),
4299 tree.is_enabled(probe),
4300 "signal and the arena's live is_enabled must agree (enabled={value})"
4301 );
4302 }
4303 }
4304
4305 /// Install-or-reuse: asking twice hands back the same signal.
4306 #[test]
4307 fn is_install_or_reuse() {
4308 let out: SignalSlot = Rc::new(RefCell::new(None));
4309 let mut tree = WidgetTree::new();
4310 let id = tree.add(EnabledProbe { out });
4311 let a = tree.effective_enabled_signal(id);
4312 let b = tree.effective_enabled_signal(id);
4313 assert!(
4314 Signal::same(&a, &b),
4315 "must hand back the same signal handle"
4316 );
4317 }
4318}