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