Skip to main content

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