Skip to main content

teksilo_core/
arena.rs

1// SPDX-License-Identifier: MPL-2.0
2// SPDX-FileCopyrightText: 2026 FernTech
3
4use slotmap::SlotMap;
5
6use crate::environment::ThemeOverride;
7use crate::event_handlers::EventHandlers;
8use crate::event_source::{SubscriptionHandle, SubscriptionId};
9use crate::gesture::MultiContact;
10use crate::pointer::hit_slop::{HitCandidate, HitContext};
11use crate::pointer::touch_action::{PanClaim, TouchAction};
12use crate::signal::{ObserverHandle, Prop, Signal};
13use crate::widget::{CursorIcon, Widget};
14use crate::widget_id::WidgetId;
15use teksilo_canvas::RenderFrame;
16
17/// Minimal placeholder widget used during composite rebuild and ID reservation.
18#[derive(Debug)]
19pub(crate) struct PlaceholderWidget;
20
21impl Widget for PlaceholderWidget {
22    fn layout_response(
23        &self,
24        _proposal: teksilo_canvas::SizeProposal,
25        _ctx: &crate::widget::LayoutContext,
26    ) -> crate::widget::LayoutResponse {
27        teksilo_canvas::Size::ZERO.into()
28    }
29}
30
31/// Activation state for a widget in the arena.
32#[derive(Debug, Clone, Copy, PartialEq, Eq)]
33pub enum ActivationState {
34    Active,
35    Dormant,
36    Destroyed,
37}
38
39/// Where a `HandlerSet` should land on the node: handlers the widget
40/// attaches to itself (cleared on rebuild) vs handlers attached from
41/// outside (persist across rebuilds).
42#[derive(Debug, Clone, Copy, PartialEq, Eq)]
43pub(crate) enum HandlerScope {
44    /// Handlers registered during the widget's own `build()` via
45    /// `BuildContext::apply_self_handlers`.
46    Own,
47    /// Handlers attached externally — at insertion time via
48    /// `WidgetBuilder::on_tap` et al., or by a composing parent's
49    /// `BuildContext::apply_handlers(child_id, ...)`.
50    External,
51}
52
53/// Dirty flags for a widget.
54#[derive(Debug, Clone, Copy, Default)]
55pub struct DirtyFlags {
56    pub needs_layout: bool,
57    pub needs_paint: bool,
58    /// When true, the widget's `build()` should be re-run to regenerate children.
59    /// Set by `BindingLevel::Rebuild` bindings (data-driven widgets).
60    pub needs_rebuild: bool,
61}
62
63/// One node's resolved hit-test geometry: which point tests its own bounds,
64/// which point its children receive, its bounds, and how much its own transform
65/// scales a local distance.
66///
67/// Shared by the exact pass, the outset pre-pass and the slop candidate walk so
68/// the three cannot disagree about where a transformed node actually is.
69struct HitSpace {
70    bounds_point: teksilo_canvas::Point,
71    child_point: teksilo_canvas::Point,
72    bounds: teksilo_canvas::Rect,
73    /// The minimum singular value of this node's own transform (`1.0` when it
74    /// has none) — the factor that turns a distance in its local space into one
75    /// in its parent's.
76    scale: f32,
77}
78
79/// `0.0` for a non-finite or negative inset, so a widget that computes an
80/// outset from a `NaN` measurement cannot inflate a rectangle into nonsense.
81fn finite(v: f32) -> f32 {
82    if v.is_finite() && v > 0.0 { v } else { 0.0 }
83}
84
85/// A node in the widget arena storing a widget and its metadata.
86pub struct WidgetNode {
87    pub widget: Box<dyn Widget>,
88    pub parent: Option<WidgetId>,
89    pub children: Vec<WidgetId>,
90    pub activation: ActivationState,
91    /// Whether this node is dormant **on its own account** — parked by a
92    /// direct [`WidgetArena::set_dormant`] rather than swept along by an
93    /// ancestor going dormant.
94    ///
95    /// This is the ungated twin of `visible_state`, and [`WidgetArena::activate`]
96    /// honours the two identically: a self-parked child is left asleep when an
97    /// ancestor wakes, because the ancestor's dormancy was never why it was
98    /// asleep. Cleared the moment a caller activates this node *by id*, which is
99    /// exactly how pre-registered overlay content is shown.
100    ///
101    /// Without it, every widget that pre-builds hidden content as a child with
102    /// `ctx.add(..)` + `ctx.set_dormant(..)` — `SplitButton`'s dropdown,
103    /// `MenuBar`'s menus, `Popover`, `Snackbar`, the date editors' calendars —
104    /// spilled that content onto the screen as soon as any ancestor completed a
105    /// dormancy cycle, laid out inline with no overlay behind it.
106    pub(crate) self_dormant: bool,
107    pub dirty: DirtyFlags,
108    pub bounds: teksilo_canvas::Rect,
109    pub(crate) theme_override: Option<ThemeOverride>,
110    pub(crate) visible_state: Option<Prop<bool>>,
111    pub(crate) enabled_state: Option<Prop<bool>>,
112    /// Reactive Tab-key participation. When bound and evaluates to
113    /// `false`, the widget is excluded from Tab / Shift+Tab traversal
114    /// (`cycle_focus`) — but remains reachable via `request_focus`
115    /// and arrow-key navigation that calls `request_focus`. This
116    /// implements the ARIA roving-tabindex pattern (HTML
117    /// `tabindex="-1"` semantics). `None` means "always a Tab stop
118    /// when focusable" — the default. The selected `TabHeader` is the
119    /// canonical user.
120    pub(crate) tab_stop: Option<Prop<bool>>,
121    /// What a data view's `Space` should do when the row containing this node
122    /// holds the keyboard cursor.
123    ///
124    /// A `ListView` / `TreeView` row is deliberately not focusable — the
125    /// container is — and the view takes the row subtree out of the Tab order,
126    /// because a listbox is one Tab stop and a per-row stop would make the Tab
127    /// order track the virtualization window. That leaves a checkbox inside a
128    /// row with no keyboard route, so the row publishes one here and the view
129    /// calls it. Carrying the *action* rather than the target's id keeps the
130    /// views from having to know what kind of control it is.
131    ///
132    /// `StandardListItem` / `StandardTreeItem` set it on the checkbox they
133    /// embed, so the common path needs no wiring; a hand-written delegate
134    /// calls `BuildContext::set_keyboard_toggle`.
135    #[allow(clippy::type_complexity)]
136    pub(crate) keyboard_toggle: Option<std::rc::Rc<dyn Fn(&mut crate::widget::EventContext)>>,
137    /// User-bound signal that the framework sets to `true` whenever
138    /// the focused widget is a strict descendant of this node, and
139    /// `false` otherwise. Used by `Panel` / `Card` / composite
140    /// widgets that want a unified focus halo without per-child
141    /// `on_focus` plumbing. See `WidgetBuilder::focus_within`.
142    pub(crate) focus_within_signal: Option<Signal<bool>>,
143    /// Framework-managed signal, lazily attached to a focusable node, set to
144    /// `true` whenever the focus is this node **or** a descendant (i.e. the node
145    /// is an *inclusive* ancestor of the focused widget). Unlike
146    /// `focus_within_signal` (strict descendants), this includes the node being
147    /// focused itself — so a data view that holds focus directly reads `true`.
148    /// Powers focus-aware selection (`BuildContext::view_focus_active`).
149    pub(crate) view_focus_signal: Option<Signal<bool>>,
150    /// User-bound signal that the framework sets to `true` whenever
151    /// the hovered widget is a strict descendant of this node.
152    /// Symmetric to `focus_within_signal`. See
153    /// `WidgetBuilder::hover_within`.
154    pub(crate) hover_within_signal: Option<Signal<bool>>,
155    /// User-bound signal that the framework sets to `true` while this
156    /// node is `ActivationState::Active` and `false` while it is
157    /// `Dormant`. Opted into via `BuildContext::activation_signal`.
158    /// Unlike every other widget — which is hidden automatically when
159    /// the paint pass skips a dormant subtree — a widget that owns a
160    /// resource living *outside* the wgpu pass (a native OS subview: a
161    /// `WebView` engine surface) has no other way to learn it was parked
162    /// dormant by a `Switcher` / `visible_when` gate, so it cannot hide
163    /// that resource. This signal is that notification. Set only on an
164    /// actual Active↔Dormant transition. See `set_dormant` / `activate`.
165    pub(crate) activation_signal: Option<Signal<bool>>,
166    /// Framework-written press visual: `true` while this node holds a pointer
167    /// press that has not slid off, been claimed by a peer, or been cancelled.
168    /// Opted into via `BuildContext::pressed_signal`, and written by the
169    /// router — see [`crate::press`] for why the widget cannot maintain this
170    /// from its own handlers.
171    pub(crate) pressed_signal: Option<Signal<bool>>,
172    /// Framework-written mirror of [`WidgetArena::is_enabled`] for this node —
173    /// the AND of its own `enabled_state` and every ancestor's. Opted into via
174    /// `BuildContext::effective_enabled_signal`.
175    ///
176    /// This has to be a *node-resident* signal that the framework refreshes,
177    /// rather than a signal derived by walking ancestors at call time, because
178    /// a widget's `parent` is still `None` while its own `build()` runs — the
179    /// parent link is wired only after `build()` returns (see
180    /// `WidgetTree::insert_widget`). A signal derived during `build()` would
181    /// therefore capture an empty ancestor chain and report only the widget's
182    /// own `enabled` prop, forever. Refreshed in
183    /// `WidgetTree::flush_effective_enabled_signals`.
184    pub(crate) effective_enabled_signal: Option<Signal<bool>>,
185    pub(crate) alignment_override: Option<teksilo_tokens::Alignment>,
186    /// When true, the paint pass clips child rendering to this widget's bounds.
187    /// Set by scroll areas and overflow-hidden containers.
188    pub clips_children: bool,
189    /// Optional OS input-method (IME) descriptor. `Some(..)` declares this
190    /// node a text-input surface — the platform enables the OS IME (with the
191    /// descriptor's purpose) while the node is focused. `None` (the default)
192    /// means no OS IME: enabling IME changes how text arrives, so the safe
193    /// common-case default is off. The platform reads the focused node's
194    /// descriptor at focus-change time. See [`crate::ime`].
195    pub ime: Option<crate::ime::ImeContext>,
196    /// When true, hit-testing skips this node — pointer events fall
197    /// through to whatever sits behind it. Descendants are still
198    /// hit-tested normally (the recursion walks into children before
199    /// the pass-through check), so an interactive subtree under a
200    /// pass-through wrapper stays usable. Used by the debug inspector's
201    /// `HighlightLayer` and `HoverProbe` to paint over the user's
202    /// content without absorbing clicks. Default `false`.
203    pub event_pass_through: bool,
204    /// When `true`, a pointer press anywhere in this widget's subtree must
205    /// NOT arm a drag/swipe recognizer on any ancestor **above** this node —
206    /// the subtree is a *gesture dead zone* for ancestor gestures. Used so
207    /// interactive controls (buttons, a `⋮` menu) placed inside a draggable /
208    /// swipeable container (a dock-panel header, a card, a list row) can be
209    /// clicked without a few px of pointer jitter starting the ancestor's drag.
210    /// The boundary is honored by `PointerSequence` member enrolment. Mirrors Electron's
211    /// `-webkit-app-region: no-drag`. Default `false`. See the `DeadZone`
212    /// wrapper widget.
213    pub gesture_dead_zone: bool,
214    /// What a **hold** on this node's subtree means when the widget itself does
215    /// not say — the selector for the tree-owned long-press route. Default
216    /// `LongPressRole::Auto`. Set via `.long_press_role(..)`. A node's own
217    /// `on_long_press` always takes precedence over this, and a mouse never
218    /// consults it. See [`crate::widget_tree::touch_route`].
219    pub long_press_role: crate::widget_tree::touch_route::LongPressRole,
220    /// What a direct pointer (touch, pen) is permitted to do to this node's
221    /// subtree. Intersected with every ancestor's on the way down by
222    /// `WidgetTree::effective_touch_action` — an ancestor can only narrow
223    /// what a descendant permits, never widen it. Default
224    /// [`TouchAction::AUTO`] (everything permitted). Set via
225    /// `.touch_action(..)`. A mouse never consults this field. Read at press
226    /// time, to gate pan claimants and the two-contact pinch — see
227    /// [`crate::pointer::touch_action`].
228    pub touch_action: TouchAction,
229    /// This node's declaration that it is a **pan surface** — it wants to
230    /// consume a direct pointer's drag as content panning. `None` (the
231    /// default) means the node makes no such claim. `WidgetTree::
232    /// pan_candidates` collects every claim from a target up to the root.
233    /// Set via `.pan_claim(..)` or the `.scroll_container(..)` sugar. Read at
234    /// press time to build the chain a synthesised pan walks — see
235    /// [`crate::pointer::touch_action`].
236    pub pan_claim: Option<PanClaim>,
237    /// Whether this node absorbs a scroll it cannot use, or lets it chain to
238    /// the next scrollable outward — the CSS `overscroll-behavior` model.
239    ///
240    /// Read by `WidgetTree::deliver_pan` when it walks the claimant chain: an
241    /// [`OverscrollBehavior::Contain`](crate::OverscrollBehavior::Contain)
242    /// claimant **stops** the chain even when it absorbed nothing, so a
243    /// self-contained panel never lets a boundary pan escape into the page
244    /// behind it. Default
245    /// [`Chain`](crate::OverscrollBehavior::Chain). Set via
246    /// `.overscroll_behavior(..)`.
247    ///
248    /// Declared on the node rather than left inside each scrollable's own
249    /// `on_scroll` closure because the *chain* has to read it, and the chain
250    /// runs in the router, above every handler.
251    pub overscroll_behavior: crate::OverscrollBehavior,
252    /// When a drag on this node may begin relative to the press that starts
253    /// it. [`DragActivation::Auto`](teksilo_tokens::DragActivation::Auto) — the
254    /// default — resolves to `Immediate`
255    /// for a precise pointer (today's behaviour, unchanged) and to
256    /// `AfterLongPress` for a coarse pointer whose axis is already claimed by
257    /// a pan surface. Set via `.drag_activation(..)`, read by the arbitration
258    /// when the node is enrolled as a sequence member.
259    pub drag_activation: teksilo_tokens::DragActivation,
260    /// How many simultaneous contacts this node's gesture recognizers serve.
261    /// Default [`MultiContact::First`] — one press at a time, which is what
262    /// every widget written before the touch programme assumes. Under it a
263    /// *second* contact arriving while the first is live is terminated at this
264    /// node: not delivered to it, and not bubbled to an ancestor either, so two
265    /// fingers on a button inside a scroll area cannot start a pan with the
266    /// second finger. Set via `.multi_contact(..)`.
267    pub multi_contact: MultiContact,
268    /// When `true` and this widget holds keyboard focus, a `KeyDown` is
269    /// delivered straight to it **without** first running shortcut →
270    /// intent → action resolution. The node is a *keyboard capture*
271    /// surface: it wants every keystroke (including chords the host app
272    /// binds as `Shortcut`s — `Ctrl+C`, `Ctrl+W`, `Alt+<letter>`, …).
273    /// Used by a terminal emulator (which must forward `Ctrl+C` to the
274    /// child process, not trigger the app's copy shortcut), a game
275    /// viewport, or a vim-mode editor. Honored by `dispatch_event_impl`,
276    /// which skips the shortcut block for a focused capture node.
277    ///
278    /// **`Ctrl+Tab` / `Ctrl+Shift+Tab` are reserved**: `dispatch_event_impl`
279    /// cycles focus on that chord before dispatching to a focused capture
280    /// node, so no capture surface can trap the keyboard (WCAG 2.1.2).
281    /// Escape is not reserved — overlay back-navigation runs ahead of the
282    /// check only while an overlay is open, so a capture surface below no
283    /// overlay does see Escape. Default `false`.
284    pub keyboard_capture: bool,
285    /// When `true`, this widget AND its entire subtree are invisible to
286    /// hit-testing: the recursion returns immediately without descending
287    /// into children, so the point falls through to whatever sits
288    /// behind. Unlike [`event_pass_through`](Self::event_pass_through)
289    /// (which is per-node — descendants stay hittable), this excludes
290    /// the whole subtree. Use for purely decorative overlays whose
291    /// children are themselves widgets — a count badge over a button, a
292    /// watermark, a status dot — so they never steal clicks meant for
293    /// the control underneath. Default `false`.
294    pub hit_transparent: bool,
295    /// Per-node override of the *miss-only* slop this node may earn, set via
296    /// `.hit_slop(..)`. Second link of the precedence chain — it beats the
297    /// widget's own `Widget::hit_slop` and the density default, and loses only
298    /// to [`no_hit_slop`](Self::no_hit_slop). `None` (the default) defers to
299    /// the widget, then to the density.
300    pub hit_slop: Option<crate::pointer::hit_slop::HitSlop>,
301    /// When `true`, this node is excluded from **both** hit-widening
302    /// mechanisms: it earns no slop outset in the miss-only pass, and its
303    /// `Widget::hit_outset` is ignored inside the exact pass. The head of the
304    /// precedence chain, set via `.no_hit_slop()`.
305    ///
306    /// Per-node, not per-subtree: a descendant may still widen. Excluding a
307    /// whole subtree from hit-testing is
308    /// [`hit_transparent`](Self::hit_transparent)'s job, and excluding a region
309    /// that hosts foreign content (a `WebView` surface) is exactly this flag on
310    /// that one node. Default `false`.
311    pub no_hit_slop: bool,
312    /// Optional opacity multiplier (0..1) applied to this widget's
313    /// entire subtree during paint. The render walker emits
314    /// `SetOpacity(value)` before walking the widget's own paint and
315    /// children, then `RestoreOpacity` afterwards — so the multiplier
316    /// composes with ancestor opacity scopes via the canvas's
317    /// already-stacked opacity model. Bound at `Repaint` level: opacity
318    /// changes never trigger relayout. `None` means "no opacity scope"
319    /// (the default for almost every widget). The `Fade` widget sets
320    /// this on its own node to drive an animated visibility tween.
321    pub(crate) opacity_prop: Option<Prop<f32>>,
322    /// Optional 2D affine transform applied to this widget's entire
323    /// subtree during paint. The render walker emits
324    /// `PushTransform(value)` before walking the widget's own paint
325    /// and children, then `PopTransform` afterwards — the renderer
326    /// composes it onto its transform stack so nested wrappers and
327    /// widget-internal canvas transforms compose correctly. Bound at
328    /// `Repaint` level by default (visual-only); a wrapper that wants
329    /// the transform to drive layout (e.g. `Scale::reflow(true)`)
330    /// must additionally bind its driver signal at `Relayout`.
331    /// `None` means "no transform scope" (the default for almost every
332    /// widget). The `Scale` and `Rotate` widgets set this on their own
333    /// node.
334    pub(crate) transform_prop: Option<Prop<teksilo_canvas::Transform2D>>,
335    /// Whether [`transform_prop`](Self::transform_prop) transforms this node's
336    /// **content** within a fixed parent-space viewport (`true`), versus
337    /// transforming the **node itself** (`false`, the default).
338    ///
339    /// `Scale` / `Rotate` are *self* transforms: the node's own bounds move
340    /// with the transform, so hit-testing inverse-applies the transform before
341    /// the bounds test (a click lands where the scaled/rotated visual is).
342    ///
343    /// `SceneView` is a *content* transform: its bounds are a fixed screen
344    /// viewport and the pan/zoom only moves its content, so hit-testing must
345    /// test the bounds in parent space (keeping the whole visible viewport
346    /// interactive at any pan) and apply the transform only when descending
347    /// into children. Set via `BuildContext::set_content_transform`.
348    pub(crate) content_transform: bool,
349    /// Optional Gaussian-equivalent blur radius applied to this widget's
350    /// entire subtree during paint. The render walker emits
351    /// `BeginBlurredSubtree { bounds, radius }` before walking the
352    /// widget's own paint and children, then `EndBlurredSubtree`
353    /// afterwards — the renderer redirects drawing into an intermediate
354    /// texture, runs a dual-Kawase blur chain at the requested radius,
355    /// and composites the blurred result back into the parent pass.
356    /// Bound at `Repaint` level: blur radius changes never trigger
357    /// relayout. `None` (or `Some(radius < 0.5)`) means "no blur scope"
358    /// — the walker skips the Begin/End pair entirely so disabled blur
359    /// has zero per-frame cost. The `Blur` widget sets this on its own
360    /// node.
361    pub(crate) blur_prop: Option<Prop<f32>>,
362    /// Cached paint output for this widget (excludes children).
363    /// Reused when `needs_paint` is false to avoid re-running `paint()`.
364    pub(crate) cached_paint: Option<RenderFrame>,
365    /// Cached foreground output for widgets that override
366    /// [`Widget::post_paint`] — the
367    /// draws emitted *after* this widget's children. Separate frame from
368    /// `cached_paint` because it lands at a different position in
369    /// `draw_order` (after the child subtree). Reused on the same
370    /// `needs_paint` gate.
371    pub(crate) cached_post_paint: Option<RenderFrame>,
372    /// The ambient raster scale `cached_paint` / `cached_post_paint`
373    /// were baked at (the paint walker's accumulated transform scale,
374    /// quantized). Glyph quads in those frames reference bitmaps of
375    /// that density; when the walker's current scale differs (a scene
376    /// zoom crossed a quantization bucket), the cached frames are
377    /// treated as `needs_paint` even though the widget itself is clean.
378    pub(crate) paint_raster_scale: f32,
379    /// The `WidgetTree::paint_epoch` at which this widget's bounds were
380    /// last observed inside the window viewport by the paint pass.
381    /// The animation scheduler uses this to pause looping animations
382    /// for offscreen widgets: an animation whose
383    /// `last_painted_epoch + 1 < tree.paint_epoch` is considered
384    /// off-screen and skipped. `0` means "not yet painted"; visibility is
385    /// waived wholesale while `tree.paint_epoch` is itself `0`, which keeps
386    /// headless tests (no `render()` call) from regressing.
387    pub last_painted_epoch: u64,
388    /// The `WidgetTree::paint_epoch` of the last full render that ran this
389    /// widget's `paint()`. Unlike `last_painted_epoch`, which is stamped as
390    /// soon as the walker reaches the node, this one moves only when the
391    /// paint actually ran, so the end-of-render clear can tell a dirty node
392    /// that repainted from one the walker skipped (clipped out, or under a
393    /// sub-perceptual opacity): the skipped one must drop its stale caches.
394    pub(crate) paint_consumed_epoch: u64,
395    /// The off-thread wake state of the `RepaintTrigger`s attached to this
396    /// widget, if any: the paint walker takes its repaint flag right before
397    /// `paint()`, and activation takes its relayout flag.
398    pub(crate) repaint_wake: Option<std::sync::Arc<crate::off_thread::NodeWakeState>>,
399
400    // --- V2 fields ---
401    /// Event handlers the widget attached to itself during its own
402    /// `build()` via `BuildContext::apply_self_handlers`. Cleared on
403    /// rebuild so accumulating `apply_self_handlers` calls across
404    /// rebuilds don't stack N-fold handler chains.
405    pub(crate) handlers: EventHandlers,
406    /// Event handlers attached *externally* — either via the
407    /// `WidgetBuilder` chain at the widget's creation site
408    /// (`SomeWidget::new().on_tap(...)`) or by a parent's
409    /// `BuildContext::apply_handlers(child_id, ...)`. These survive
410    /// rebuilds: the widget didn't register them and shouldn't decide
411    /// when they go away.
412    pub(crate) external_handlers: EventHandlers,
413    /// Focusable override set via HandlerSet. The only source of a node's
414    /// focusability — `WidgetTree::is_node_focusable` reads this field and
415    /// nothing else, so `None` means not focusable.
416    pub(crate) node_focusable: Option<bool>,
417    /// Tab index override set via HandlerSet.
418    pub(crate) node_tab_index: Option<i32>,
419    /// Traversal-scope marker. When `Some(policy)`, `cycle_focus` treats this
420    /// node's subtree as an independent Tab group: `tab_index` numbering is
421    /// scoped to its descendants (so sibling scopes never interleave) and
422    /// `policy` governs what Tab does at the scope's ends. `None` (default)
423    /// means the node is transparent to traversal scoping. Set by the
424    /// `FocusScope` wrapper via `BuildContext::set_traversal_scope`. A node
425    /// carrying this marker is forced non-focusable (it is a boundary, never a
426    /// Tab stop). See [`crate::focus::TraversalScopePolicy`].
427    pub(crate) node_traversal_scope: Option<crate::focus::TraversalScopePolicy>,
428    /// Cursor override set via HandlerSet.
429    pub(crate) node_cursor: Option<CursorIcon>,
430    /// RAII observer handles for effects registered during build().
431    /// Dropped on rebuild or widget destruction.
432    pub(crate) effect_handles: Vec<ObserverHandle>,
433    /// Backend-event subscriptions registered during build() via
434    /// `BuildContext::subscribe_event`. Each entry pairs a subscription id
435    /// (used to remove the UI-side callback from `TreeAppContext`) with the
436    /// opaque source-side handle whose `Drop` removes the subscriber from
437    /// the source's internal registry.
438    pub(crate) subscription_handles: Vec<(SubscriptionId, SubscriptionHandle)>,
439    /// Parentless nodes this widget created during `build()` and still owns —
440    /// pre-built overlay content (a menu, a calendar, a tooltip's nested
441    /// cascade children) that is deliberately *not* a child.
442    ///
443    /// Such content cannot be a child: activation and the paint walk both
444    /// descend through `children`, so a dormant popup parked there wakes with
445    /// its host and paints inline at zero size. Keeping it parentless fixes
446    /// that and creates the opposite problem — no teardown walk reaches it, so
447    /// every rebuild of the host strands another copy in the arena for the
448    /// lifetime of the process. This list is the missing ownership edge:
449    /// [`WidgetTree::destroy_subtree`](crate::widget_tree::WidgetTree) reaps it
450    /// with the owner, and a rebuild reaps the previous generation. Recorded
451    /// via `BuildContext::add_detached`.
452    pub(crate) detached: Vec<WidgetId>,
453    /// Context menu factory — invoked on right-click to produce overlay content.
454    pub(crate) context_menu_factory: Option<crate::widget_builder::ContextMenuFactory>,
455    /// Intent-bound actions attached by this widget during `build()`.
456    /// Consulted during intent dispatch (source-widget → root walk).
457    /// Cleared on rebuild in the same pass that clears handlers.
458    pub(crate) actions: Vec<crate::action::Action>,
459    /// Builder-level accessibility overrides (`access_label`,
460    /// `access_role`, etc.). Mirrored from the wrapper's `HandlerSet`
461    /// at insertion via `apply_handler_set`. Applied by the
462    /// accessibility tree walker after the inner widget's
463    /// `accessibility(&self, builder)` runs. Action callbacks
464    /// (`actions`, `custom_actions` inside this struct) are dispatched
465    /// by `pointer_router.rs` when handling
466    /// `WidgetEvent::AccessAction`.
467    pub(crate) access_overrides: Option<Box<crate::widget_builder::AccessibilityOverrides>>,
468    /// Subtree visibility / merge mode (`access_exclude_subtree` /
469    /// `access_merge_subtree`). Mirrored from the wrapper's
470    /// `HandlerSet`.
471    pub(crate) access_subtree: crate::widget_builder::AccessSubtreeMode,
472}
473
474impl std::fmt::Debug for WidgetNode {
475    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
476        f.debug_struct("WidgetNode")
477            .field("widget", &self.widget)
478            .field("parent", &self.parent)
479            .field("children", &self.children)
480            .field("activation", &self.activation)
481            .field("dirty", &self.dirty)
482            .field("bounds", &self.bounds)
483            .field("has_gesture_arena", &self.handlers.gesture_arena.is_some())
484            .field("has_theme_override", &self.theme_override.is_some())
485            .field("has_visible_state", &self.visible_state.is_some())
486            .field("has_enabled_state", &self.enabled_state.is_some())
487            .finish()
488    }
489}
490
491impl WidgetNode {
492    /// Construct a fresh node wrapping `widget`, parented at `parent`
493    /// (`None` for a root). All other fields take their insertion defaults;
494    /// the caller wires up `children` / parent back-links afterward.
495    pub(crate) fn new(widget: Box<dyn Widget>, parent: Option<WidgetId>) -> Self {
496        WidgetNode {
497            widget,
498            parent,
499            children: Vec::new(),
500            activation: ActivationState::Active,
501            self_dormant: false,
502            dirty: DirtyFlags {
503                needs_layout: true,
504                needs_paint: true,
505                needs_rebuild: false,
506            },
507            bounds: teksilo_canvas::Rect::ZERO,
508            theme_override: None,
509            visible_state: None,
510            enabled_state: None,
511            tab_stop: None,
512            keyboard_toggle: None,
513            focus_within_signal: None,
514            view_focus_signal: None,
515            hover_within_signal: None,
516            activation_signal: None,
517            pressed_signal: None,
518            effective_enabled_signal: None,
519            alignment_override: None,
520            clips_children: false,
521            ime: None,
522            event_pass_through: false,
523            gesture_dead_zone: false,
524            long_press_role: crate::widget_tree::touch_route::LongPressRole::Auto,
525            touch_action: TouchAction::AUTO,
526            pan_claim: None,
527            overscroll_behavior: crate::OverscrollBehavior::Chain,
528            drag_activation: teksilo_tokens::DragActivation::Auto,
529            multi_contact: MultiContact::First,
530            keyboard_capture: false,
531            hit_transparent: false,
532            hit_slop: None,
533            no_hit_slop: false,
534            opacity_prop: None,
535            transform_prop: None,
536            content_transform: false,
537            blur_prop: None,
538            cached_paint: None,
539            cached_post_paint: None,
540            paint_raster_scale: 1.0,
541            last_painted_epoch: 0,
542            paint_consumed_epoch: 0,
543            repaint_wake: None,
544            handlers: EventHandlers::new(),
545            external_handlers: EventHandlers::new(),
546            node_focusable: None,
547            node_tab_index: None,
548            node_traversal_scope: None,
549            node_cursor: None,
550            effect_handles: Vec::new(),
551            subscription_handles: Vec::new(),
552            detached: Vec::new(),
553            context_menu_factory: None,
554            actions: Vec::new(),
555            access_overrides: None,
556            access_subtree: crate::widget_builder::AccessSubtreeMode::default(),
557        }
558    }
559
560    /// Does EITHER handler slot (own or external) have a handler of the
561    /// requested kind? Use this when deciding whether to build a gesture
562    /// arena, mark the node as a drop target, etc.
563    pub(crate) fn any_handler<F>(&self, f: F) -> bool
564    where
565        F: Fn(&EventHandlers) -> bool,
566    {
567        f(&self.handlers) || f(&self.external_handlers)
568    }
569}
570
571/// One widget's handler space: how a window-logical point maps into the
572/// space its handlers receive positions in, and back out.
573///
574/// Built by [`WidgetArena::local_frame`]. Kept as the transform, its inverse
575/// and the origin rather than folded into one matrix, so that
576/// [`to_local`](Self::to_local) performs exactly the arithmetic the dispatcher
577/// always has — a composed matrix rounds differently — and
578/// [`to_window`](Self::to_window) undoes it step for step.
579#[derive(Clone, Copy, Debug, PartialEq)]
580pub(crate) struct LocalFrame {
581    /// From the frame's pre-transform space to window space: the node's
582    /// effective transform, or its parent's for a content-transform node.
583    to_window: teksilo_canvas::Transform2D,
584    /// The inverse of `to_window`, `None` when that is singular. A singular
585    /// transform collapses the subtree, so nothing can aim inside it; both
586    /// directions then apply no transform, as localisation always has, and
587    /// stay each other's inverse.
588    from_window: Option<teksilo_canvas::Transform2D>,
589    /// The bounds origin local points are relative to — zero for a
590    /// content-transform node, whose handlers receive its parent's space.
591    origin: teksilo_canvas::Point,
592}
593
594impl LocalFrame {
595    /// The handler-space point for a window-logical one.
596    pub(crate) fn to_local(self, window: teksilo_canvas::Point) -> teksilo_canvas::Point {
597        let p = match &self.from_window {
598            Some(inverse) => inverse.apply_point(window),
599            // Degenerate transform: fall back to the raw point rather than
600            // dropping the event.
601            None => window,
602        };
603        teksilo_canvas::Point::new(p.x - self.origin.x, p.y - self.origin.y)
604    }
605
606    /// The window-logical point whose handler-space point is `local`: the
607    /// inverse of [`to_local`](Self::to_local).
608    pub(crate) fn to_window(self, local: teksilo_canvas::Point) -> teksilo_canvas::Point {
609        let p = teksilo_canvas::Point::new(local.x + self.origin.x, local.y + self.origin.y);
610        match &self.from_window {
611            Some(_) => self.to_window.apply_point(p),
612            None => p,
613        }
614    }
615}
616
617/// Flat arena storage for all widgets, using SlotMap for O(1) access.
618pub struct WidgetArena {
619    nodes: SlotMap<WidgetId, WidgetNode>,
620    /// Number of nodes with theme overrides. When zero, resolve_theme is O(1).
621    pub(crate) theme_override_count: usize,
622    /// Cached root widget IDs (widgets with no parent).
623    cached_roots: Vec<WidgetId>,
624    /// Whether the cached_roots list needs rebuilding.
625    roots_dirty: bool,
626    /// Per-pass memoization of `Widget::layout_response`, keyed by
627    /// `(WidgetId, ProposalKey)`. Cleared once at the start of every layout
628    /// pass (see `clear_layout_cache`). Height-for-width negotiation queries
629    /// each child along the main axis and again along the cross axis, so
630    /// without this the cost compounds super-linearly with nesting depth;
631    /// with it, each `(id, proposal)` is computed at most once per pass.
632    /// `RefCell` because layout runs through shared `&WidgetArena` borrows.
633    layout_cache: std::cell::RefCell<
634        std::collections::HashMap<(WidgetId, ProposalKey), crate::widget::LayoutResponse>,
635    >,
636    /// Widgets whose box moved without changing size since the last
637    /// accessibility walk, and by how much.
638    ///
639    /// A move is the one geometry change the accessibility tree can absorb
640    /// without being rebuilt: nothing about a widget's *content* depends
641    /// on where it sits, so its node and every text run under it can be
642    /// re-placed in the cached tree by the same delta. A scroll frame
643    /// moves every descendant of the scroll area, so this is the common
644    /// case and re-walking for it was what made the AT tree go stale
645    /// instead — the walk was too expensive to run per frame, so it was
646    /// not run at all and every node's bounds drifted.
647    a11y_moved: std::collections::HashMap<WidgetId, teksilo_canvas::Point>,
648    /// Set when any widget's box changed *size* since the last
649    /// accessibility walk.
650    ///
651    /// A resize is not absorbable: a wrapped label re-wraps, so its lines —
652    /// and therefore its text runs — are a different set, not the same set
653    /// somewhere else.
654    a11y_resized: bool,
655    /// True while [`measure_intrinsic`](Self::measure_intrinsic) is running.
656    /// In this mode `cached_layout_response` measures even dormant widgets
657    /// (and their dormant subtrees) and bypasses the cache, so an adaptive
658    /// container can size an item it intends to keep hidden without that size
659    /// leaking into the normal per-pass cache.
660    measuring: std::cell::Cell<bool>,
661    /// Active↔Dormant transitions of nodes carrying an `activation_signal`,
662    /// recorded by [`set_dormant`](Self::set_dormant) / [`activate`](Self::activate)
663    /// and drained by `WidgetTree::flush_activation_signals` *after* the
664    /// mutation completes. Signals are fired at the tree level, never from
665    /// inside the arena recursion — mirroring how `focus_within` /
666    /// `hover_within` are updated from `WidgetTree` methods rather than mid
667    /// mutation, so an observer (e.g. a `WebView`'s `set_visible`, which on a
668    /// real backend is an OS call) never runs while the arena is being walked.
669    /// Only nodes with a signal contribute, so the buffer is empty for the
670    /// overwhelming majority of trees.
671    pending_activation_changes: Vec<(WidgetId, bool)>,
672    /// Widgets whose activation took a relayout a `RepaintTrigger` had
673    /// requested while they slept. One woken inside a layout walk by a
674    /// culling parent was measured before it was woken, possibly at the size
675    /// before the request, so the walk's end marks it for layout again.
676    pub(crate) relayout_rewake: Vec<WidgetId>,
677    /// Every node that installed an `effective_enabled_signal`, so the
678    /// per-pass refresh visits only opted-in nodes instead of the whole arena.
679    /// Unlike `pending_activation_changes` this is NOT a change queue: an
680    /// ancestor's `enabled` prop is a `Signal` that can flip at any time
681    /// without the arena being told, so there is no single mutation site to
682    /// record a transition at. The refresh recomputes and diffs instead —
683    /// see `WidgetTree::flush_effective_enabled_signals`. Dead ids are pruned
684    /// there, so a destroyed widget cannot leak.
685    effective_enabled_watchers: Vec<WidgetId>,
686}
687
688/// Hashable key for a [`teksilo_canvas::SizeProposal`] used by the per-pass
689/// layout cache. Each axis is encoded to a `u64`: `None` → a sentinel
690/// distinct from any finite `f32`, `Some(v)` → the canonicalized `f32` bits
691/// (`-0.0` folded to `0.0`, all NaNs folded to one pattern) so two equal
692/// proposals always hash and compare equal.
693#[derive(Clone, Copy, PartialEq, Eq, Hash, Debug)]
694struct ProposalKey([u64; 2]);
695
696impl ProposalKey {
697    fn from_proposal(p: teksilo_canvas::SizeProposal) -> Self {
698        fn axis_bits(v: Option<f32>) -> u64 {
699            match v {
700                // `f32::to_bits()` widens into 0..=u32::MAX, so u64::MAX is a
701                // safe sentinel that no `Some(_)` can collide with.
702                None => u64::MAX,
703                Some(f) => {
704                    let canon = if f == 0.0 {
705                        0.0
706                    } else if f.is_nan() {
707                        f32::NAN
708                    } else {
709                        f
710                    };
711                    canon.to_bits() as u64
712                }
713            }
714        }
715        Self([axis_bits(p.width), axis_bits(p.height)])
716    }
717}
718
719impl WidgetArena {
720    pub fn new() -> Self {
721        Self {
722            nodes: SlotMap::with_key(),
723            theme_override_count: 0,
724            cached_roots: Vec::new(),
725            roots_dirty: true,
726            layout_cache: std::cell::RefCell::new(std::collections::HashMap::new()),
727            measuring: std::cell::Cell::new(false),
728            a11y_moved: std::collections::HashMap::new(),
729            a11y_resized: false,
730            pending_activation_changes: Vec::new(),
731            relayout_rewake: Vec::new(),
732            effective_enabled_watchers: Vec::new(),
733        }
734    }
735
736    /// Record what a bounds change means for the accessibility tree.
737    ///
738    /// Called by the layout pass at each of its two bounds writers, after
739    /// the node has been updated. Same size = a move the cached tree can
740    /// absorb; any size change = a rebuild.
741    pub(crate) fn note_bounds_change(
742        &mut self,
743        id: WidgetId,
744        previous: teksilo_canvas::Rect,
745        current: teksilo_canvas::Rect,
746    ) {
747        if previous.width != current.width || previous.height != current.height {
748            self.a11y_resized = true;
749            self.a11y_moved.remove(&id);
750            return;
751        }
752        let delta = teksilo_canvas::Point::new(current.x - previous.x, current.y - previous.y);
753        // A widget can move several times between two walks; the cached
754        // tree only ever sees the total.
755        let entry = self
756            .a11y_moved
757            .entry(id)
758            .or_insert(teksilo_canvas::Point::new(0.0, 0.0));
759        entry.x += delta.x;
760        entry.y += delta.y;
761    }
762
763    /// Whether any widget changed size since the last accessibility walk,
764    /// clearing the flag.
765    pub(crate) fn take_a11y_resized(&mut self) -> bool {
766        std::mem::take(&mut self.a11y_resized)
767    }
768
769    /// The widgets that moved since the last accessibility walk, clearing
770    /// the record.
771    pub(crate) fn take_a11y_moved(
772        &mut self,
773    ) -> std::collections::HashMap<WidgetId, teksilo_canvas::Point> {
774        std::mem::take(&mut self.a11y_moved)
775    }
776
777    /// Clear the per-pass layout memoization cache. Called once at the start of
778    /// each layout pass — geometry (and therefore `layout_response` results)
779    /// may change between passes, so the cache is valid only within one pass.
780    pub(crate) fn clear_layout_cache(&self) {
781        self.layout_cache.borrow_mut().clear();
782    }
783
784    /// Compute a widget's layout response, memoized per `(id, proposal)` for
785    /// the current layout pass. Returns `None` if the id is missing or
786    /// dormant. Widgets that opt out via `Widget::cacheable_layout() == false`
787    /// (e.g. the inspector's bounds tracker, which deliberately mutates signals
788    /// in `layout_response`) bypass the cache so their side effect fires on
789    /// every call.
790    ///
791    /// The key is `(id, proposal)` only: `layout_response` also reads the
792    /// `LayoutContext` (resolved theme, layout direction, text backend), but
793    /// those are a stable function of `id` within a single pass, so the pair
794    /// uniquely determines the input.
795    pub(crate) fn cached_layout_response(
796        &self,
797        id: WidgetId,
798        proposal: teksilo_canvas::SizeProposal,
799        ctx: &crate::widget::LayoutContext,
800    ) -> Option<crate::widget::LayoutResponse> {
801        let node = self.nodes.get(id)?;
802        let measuring = self.measuring.get();
803        if node.activation != ActivationState::Active && !measuring {
804            return None;
805        }
806        // While measuring intrinsic sizes (incl. of dormant subtrees), bypass
807        // the cache entirely so a dormant widget's size never pollutes the
808        // normal per-pass cache.
809        if measuring || !node.widget.cacheable_layout() {
810            return Some(node.widget.layout_response(proposal, ctx));
811        }
812        let key = (id, ProposalKey::from_proposal(proposal));
813        // Scope the shared borrow so it is released before `layout_response`
814        // runs — that call recurses into children, which borrow the same
815        // `layout_cache` (read, then write) and would otherwise alias.
816        {
817            if let Some(cached) = self.layout_cache.borrow().get(&key) {
818                return Some(*cached);
819            }
820        }
821        let resp = node.widget.layout_response(proposal, ctx);
822        self.layout_cache.borrow_mut().insert(key, resp);
823        Some(resp)
824    }
825
826    /// Measure a widget's intrinsic `layout_response` size for `proposal`,
827    /// **regardless of activation** — including dormant/collapsed widgets and
828    /// their dormant subtrees. Returns `None` only if the id is absent.
829    ///
830    /// Adaptive containers (e.g. an overflow [`Toolbar`](crate) that collapses
831    /// items into a menu) use this to size an item they intend to keep hidden,
832    /// so they can decide when to show it again as space grows — something
833    /// `child_layout_response` cannot do, since it returns `None` for inactive
834    /// widgets.
835    ///
836    /// Runs uncached (a dormant widget's size never enters the per-pass cache)
837    /// and is re-entrant-safe (saves/restores the measuring flag). Calls
838    /// `layout_response`, which must be idempotent (see
839    /// [`Widget::cacheable_layout`]).
840    pub(crate) fn measure_intrinsic(
841        &self,
842        id: WidgetId,
843        proposal: teksilo_canvas::SizeProposal,
844        ctx: &crate::widget::LayoutContext,
845    ) -> Option<teksilo_canvas::Size> {
846        if !self.nodes.contains_key(id) {
847            return None;
848        }
849        let prev = self.measuring.replace(true);
850        // `cached_layout_response` (and every nested child query during this
851        // call) sees `measuring == true`, so it bypasses the active check and
852        // the cache for the whole subtree.
853        let resp = self.cached_layout_response(id, proposal, ctx);
854        self.measuring.set(prev);
855        resp.map(|r| r.size)
856    }
857
858    /// Insert a widget into the arena as a root-level widget.
859    pub fn insert(&mut self, widget: Box<dyn Widget>) -> WidgetId {
860        self.roots_dirty = true;
861        let children = widget.children();
862        let id = self.nodes.insert(WidgetNode::new(widget, None));
863        // Set up parent-child for declared children
864        for &child_id in &children {
865            if let Some(child_node) = self.nodes.get_mut(child_id) {
866                child_node.parent = Some(id);
867            }
868        }
869        if let Some(node) = self.nodes.get_mut(id) {
870            node.children = children;
871        }
872        id
873    }
874
875    /// Insert a widget as a child of the given parent.
876    pub fn insert_child(&mut self, parent: WidgetId, widget: Box<dyn Widget>) -> WidgetId {
877        assert!(
878            self.nodes.contains_key(parent),
879            "insert_child() called with invalid parent WidgetId {parent:?}"
880        );
881        self.roots_dirty = true;
882        let children = widget.children();
883        let id = self.nodes.insert(WidgetNode::new(widget, Some(parent)));
884        // Set up parent-child for declared children
885        for &child_id in &children {
886            if let Some(child_node) = self.nodes.get_mut(child_id) {
887                child_node.parent = Some(id);
888            }
889        }
890        if let Some(node) = self.nodes.get_mut(id) {
891            node.children = children;
892        }
893        if let Some(parent_node) = self.nodes.get_mut(parent) {
894            parent_node.children.push(id);
895        }
896        id
897    }
898
899    pub fn get(&self, id: WidgetId) -> Option<&WidgetNode> {
900        self.nodes.get(id)
901    }
902
903    pub fn get_mut(&mut self, id: WidgetId) -> Option<&mut WidgetNode> {
904        self.nodes.get_mut(id)
905    }
906
907    pub fn children(&self, id: WidgetId) -> &[WidgetId] {
908        self.nodes
909            .get(id)
910            .map(|n| n.children.as_slice())
911            .unwrap_or(&[])
912    }
913
914    pub fn parent(&self, id: WidgetId) -> Option<WidgetId> {
915        self.nodes.get(id).and_then(|n| n.parent)
916    }
917
918    pub fn bounds(&self, id: WidgetId) -> teksilo_canvas::Rect {
919        self.nodes
920            .get(id)
921            .map(|n| n.bounds)
922            .unwrap_or(teksilo_canvas::Rect::ZERO)
923    }
924
925    /// The accumulated 2D affine transform that maps `id`'s pre-transform
926    /// local-space points to screen space — equivalent to the renderer's
927    /// `transform_stack` top by the time it begins painting `id`. Used by
928    /// hit-testing and any consumer that needs to project a node's
929    /// pre-transform bounds into screen space (e.g. teksilo-scene's a11y
930    /// bounds projection of view-transformed scene items).
931    ///
932    /// **Composition order.** Mirrors `crates/teksilo-render/src/renderer.rs`'s
933    /// `PushTransform` handling: each push composes as
934    /// `new_top = device_t.then(prev_top)`, so the deepest (innermost)
935    /// transform is applied **first** to a local point and outer ancestors
936    /// compose afterward. Walking root→leaf, each ancestor's
937    /// `transform_prop` is folded in via `t.then(effective)` (NOT
938    /// `effective.then(t)`).
939    ///
940    /// Returns `Transform2D::IDENTITY` if no ancestor sets a non-identity
941    /// transform, which is the common case (90%+ of widgets).
942    pub fn effective_transform(&self, id: WidgetId) -> teksilo_canvas::Transform2D {
943        // Collect leaf→root, then iterate root→leaf. Composition is
944        // `t_new.then(effective_so_far)` so the outer ancestor is applied
945        // *after* the deeper push — matching the renderer's stack semantic
946        // (`device_t.then(prev_top)` at PushTransform).
947        let mut chain: Vec<WidgetId> = Vec::new();
948        let mut current = Some(id);
949        while let Some(c) = current {
950            chain.push(c);
951            current = self.parent(c);
952        }
953        let mut effective = teksilo_canvas::Transform2D::IDENTITY;
954        for node_id in chain.iter().rev() {
955            if let Some(node) = self.nodes.get(*node_id)
956                && let Some(p) = node.transform_prop.as_ref()
957            {
958                let t = p.get();
959                if !t.is_identity() {
960                    effective = t.then(&effective);
961                }
962            }
963        }
964        effective
965    }
966
967    /// Convert a **window-space** pointer position into the **widget-local**
968    /// coordinate space of `id`'s event handlers — i.e. relative to `id`'s
969    /// top-left, after undoing any transform scopes between the window and
970    /// `id`. This is the single conversion the dispatcher applies before
971    /// handing a position to `on_tap` / `on_drag` / `on_pointer_event`, so
972    /// every handler sees positions in its own local space.
973    ///
974    /// The transform handling mirrors `Self::hit_test_recursive` so the
975    /// position a handler receives is in the same space the hit-test used
976    /// to pick it:
977    /// * A **content** transform node (`content_transform`, e.g.
978    ///   `SceneView`) owns its transform and maps its content itself. The
979    ///   framework feeds such a node positions in its **parent-effective**
980    ///   space (the same space `hit_test_recursive` passes through
981    ///   `inv(transform)`), with **no** bounds-origin subtraction — the
982    ///   node's `view_transform` already accounts for its placement.
983    /// * Any other node (the 90%+ identity case, plus `Scale` / `Rotate`
984    ///   self-transforms) receives widget-local coordinates: undo the full
985    ///   transform chain including its own, then subtract its bounds
986    ///   origin so the result is relative to its top-left.
987    ///
988    /// In the common no-transform case this collapses to
989    /// `window_point - bounds.origin`.
990    pub fn local_pointer_position(
991        &self,
992        id: WidgetId,
993        window_point: teksilo_canvas::Point,
994    ) -> teksilo_canvas::Point {
995        self.local_frame(id).to_local(window_point)
996    }
997
998    /// The frame [`local_pointer_position`](Self::local_pointer_position)
999    /// localises into for `id`, which also maps back out of it. One walk up
1000    /// the tree, so a caller with several points to convert (a gesture's,
1001    /// a batch's) pays it once.
1002    pub(crate) fn local_frame(&self, id: WidgetId) -> LocalFrame {
1003        let content_transform = self.get(id).map(|n| n.content_transform).unwrap_or(false);
1004        let (to_window, origin) = if content_transform {
1005            // Parent-effective space, no origin subtraction (the node's
1006            // own transform consumes these coordinates).
1007            let to_parent = self
1008                .parent(id)
1009                .map(|p| self.effective_transform(p))
1010                .unwrap_or(teksilo_canvas::Transform2D::IDENTITY);
1011            (to_parent, teksilo_canvas::Point::ZERO)
1012        } else {
1013            let bounds = self.bounds(id);
1014            (
1015                self.effective_transform(id),
1016                teksilo_canvas::Point::new(bounds.x, bounds.y),
1017            )
1018        };
1019        LocalFrame {
1020            from_window: to_window.inverse(),
1021            to_window,
1022            origin,
1023        }
1024    }
1025
1026    /// Get all root-level widget IDs (widgets with no parent).
1027    pub fn roots(&self) -> Vec<WidgetId> {
1028        if self.roots_dirty {
1029            // Fall back to scanning when cache is stale.
1030            // refresh_roots() should be called from layout() for the fast path.
1031            return self
1032                .nodes
1033                .iter()
1034                .filter(|(_, node)| node.parent.is_none())
1035                .map(|(id, _)| id)
1036                .collect();
1037        }
1038        self.cached_roots.clone()
1039    }
1040
1041    /// Refresh the cached roots list. Call once per frame from layout().
1042    pub fn refresh_roots(&mut self) {
1043        if self.roots_dirty {
1044            self.cached_roots = self
1045                .nodes
1046                .iter()
1047                .filter(|(_, node)| node.parent.is_none())
1048                .map(|(id, _)| id)
1049                .collect();
1050            self.roots_dirty = false;
1051        }
1052    }
1053
1054    /// Walk the active widget tree at `point` and return the deepest
1055    /// widget under it (the front-most hit, last child wins). Honors
1056    /// `event_pass_through` (such nodes pass through to whatever sits
1057    /// behind them but their descendants are still hit-testable). Does
1058    /// not consider overlays — for the full pointer-routing hit-test
1059    /// see `WidgetTree::hit_test`.
1060    ///
1061    /// `exclude`: if `Some(id)`, that widget (and any descendants
1062    /// within its subtree) are skipped during the walk. Used by the
1063    /// debug inspector's picker tool to ignore the picker overlay
1064    /// itself, and by drag-and-drop to ignore the drag preview.
1065    pub fn hit_test_at(
1066        &self,
1067        point: teksilo_canvas::Point,
1068        exclude: Option<WidgetId>,
1069    ) -> Option<WidgetId> {
1070        self.hit_test_at_with(point, exclude, &HitContext::mouse())
1071    }
1072
1073    /// [`hit_test_at`](Self::hit_test_at) on behalf of a named pointer.
1074    ///
1075    /// The **exact** pass only: `Widget::hit_outset` is consulted (so a grip
1076    /// wins over what it overlaps for the kind that asked), but no slop
1077    /// re-attribution happens. Callers that want re-attribution too use
1078    /// [`hit_test_at_with_slop`](Self::hit_test_at_with_slop).
1079    pub fn hit_test_at_with(
1080        &self,
1081        point: teksilo_canvas::Point,
1082        exclude: Option<WidgetId>,
1083        hit: &HitContext<'_>,
1084    ) -> Option<WidgetId> {
1085        self.hit_test_roots_with(&self.roots(), point, exclude, hit)
1086    }
1087
1088    /// [`hit_test_at_with`](Self::hit_test_at_with) over `roots` alone, which
1089    /// is a subset of [`roots`](Self::roots) in the same order.
1090    fn hit_test_roots_with(
1091        &self,
1092        roots: &[WidgetId],
1093        point: teksilo_canvas::Point,
1094        exclude: Option<WidgetId>,
1095        hit: &HitContext<'_>,
1096    ) -> Option<WidgetId> {
1097        // Roots take the outset pre-pass too, so a grip that happens to be a
1098        // top-level node behaves like one nested anywhere else. The window is
1099        // its "parent", and the window does not clip — and, having no widget,
1100        // it vetoes nothing.
1101        let no_veto = |_: WidgetId| false;
1102        if let Some(grip) = self.outset_hit(roots, point, exclude, hit, &no_veto) {
1103            return Some(grip);
1104        }
1105        for &root in roots.iter().rev() {
1106            if let Some(found) = self.hit_test_recursive(root, point, exclude, hit) {
1107                return Some(found);
1108            }
1109        }
1110        None
1111    }
1112
1113    /// The full two-stage hit test: the exact pass, then — **only when it found
1114    /// nothing eligible** — the nearest-candidate slop pass.
1115    ///
1116    /// Returns whatever the exact pass returned unless a slop candidate is
1117    /// strictly closer than the bubble owner's uninflated shape. See
1118    /// [`hit_candidates`](Self::hit_candidates) for the eligibility rules and
1119    /// `docs/density-and-targets.md` for the prose.
1120    ///
1121    /// For a mouse this is [`hit_test_at`](Self::hit_test_at): the mouse slop
1122    /// radius is `0.0` at every density, so the second stage short-circuits
1123    /// before it walks anything.
1124    pub fn hit_test_at_with_slop(
1125        &self,
1126        point: teksilo_canvas::Point,
1127        exclude: Option<WidgetId>,
1128        hit: &HitContext<'_>,
1129    ) -> Option<WidgetId> {
1130        self.hit_test_roots_with_slop(self.roots(), point, exclude, hit)
1131    }
1132
1133    /// [`hit_test_at_with_slop`](Self::hit_test_at_with_slop) over `roots`
1134    /// alone, which is a subset of [`roots`](Self::roots) in the same order:
1135    /// neither pass looks inside a root left out.
1136    pub(crate) fn hit_test_roots_with_slop(
1137        &self,
1138        roots: Vec<WidgetId>,
1139        point: teksilo_canvas::Point,
1140        exclude: Option<WidgetId>,
1141        hit: &HitContext<'_>,
1142    ) -> Option<WidgetId> {
1143        let exact = self.hit_test_roots_with(&roots, point, exclude, hit);
1144        self.apply_slop(roots, point, exclude, hit, exact)
1145    }
1146
1147    /// [`hit_test_in_subtree`](Self::hit_test_in_subtree) with the slop pass,
1148    /// scoped so candidates never leave `start`'s subtree.
1149    ///
1150    /// This is what restricts the pass to the topmost overlay layer the exact
1151    /// pass entered: the tree calls it with the overlay's content root, so a
1152    /// press inside a menu can never be re-attributed to a control on the page
1153    /// behind it.
1154    pub fn hit_test_in_subtree_with_slop(
1155        &self,
1156        start: WidgetId,
1157        point: teksilo_canvas::Point,
1158        exclude: Option<WidgetId>,
1159        hit: &HitContext<'_>,
1160    ) -> Option<WidgetId> {
1161        let exact = self.hit_test_recursive(start, point, exclude, hit);
1162        self.apply_slop(vec![start], point, exclude, hit, exact)
1163    }
1164
1165    /// Hit-test starting from a specific subtree root rather than the
1166    /// arena's top-level roots. Same semantics as
1167    /// [`hit_test_at`](Self::hit_test_at) but scoped — useful when
1168    /// callers want to ignore everything outside a known subtree
1169    /// (e.g. the inspector's picker hit-tests inside the user-root
1170    /// subtree so it never resolves to its own chrome).
1171    pub fn hit_test_in_subtree(
1172        &self,
1173        start: WidgetId,
1174        point: teksilo_canvas::Point,
1175    ) -> Option<WidgetId> {
1176        self.hit_test_recursive(start, point, None, &HitContext::mouse())
1177    }
1178
1179    /// Like [`hit_test_in_subtree`](Self::hit_test_in_subtree) but also
1180    /// excludes a widget (and its descendants) from the walk. Lets the
1181    /// overlay / drag-and-drop hit-test reuse the single canonical recursion
1182    /// in `hit_test_recursive` instead of duplicating it.
1183    pub fn hit_test_in_subtree_excluding(
1184        &self,
1185        start: WidgetId,
1186        point: teksilo_canvas::Point,
1187        exclude: Option<WidgetId>,
1188    ) -> Option<WidgetId> {
1189        self.hit_test_recursive(start, point, exclude, &HitContext::mouse())
1190    }
1191
1192    /// [`hit_test_in_subtree_excluding`](Self::hit_test_in_subtree_excluding)
1193    /// on behalf of a named pointer. Exact pass only.
1194    pub fn hit_test_in_subtree_with(
1195        &self,
1196        start: WidgetId,
1197        point: teksilo_canvas::Point,
1198        exclude: Option<WidgetId>,
1199        hit: &HitContext<'_>,
1200    ) -> Option<WidgetId> {
1201        self.hit_test_recursive(start, point, exclude, hit)
1202    }
1203
1204    fn hit_test_recursive(
1205        &self,
1206        id: WidgetId,
1207        point: teksilo_canvas::Point,
1208        exclude: Option<WidgetId>,
1209        hit: &HitContext<'_>,
1210    ) -> Option<WidgetId> {
1211        if !self.is_active(id) || Some(id) == exclude {
1212            return None;
1213        }
1214        // Decorative subtree: skip this node and ALL its descendants so
1215        // the point falls through to whatever is painted behind. Checked
1216        // before descending into children (the difference from
1217        // `event_pass_through`, which is applied only after the children
1218        // miss).
1219        if self.get(id).map(|n| n.hit_transparent).unwrap_or(false) {
1220            return None;
1221        }
1222        let space = self.hit_space(id, point)?;
1223        let HitSpace {
1224            bounds_point,
1225            child_point,
1226            bounds,
1227            ..
1228        } = space;
1229        if !bounds.contains(bounds_point) {
1230            return None;
1231        }
1232        // Shape rejection: a widget with a non-rectangular silhouette (an
1233        // ellipse / cloud scene node, a circular handle) can reject a point
1234        // that is inside its bounding box but outside its actual shape via
1235        // `Widget::hit_shape`. Returning None here lets the caller's
1236        // reverse-sibling loop fall through to whatever is painted
1237        // underneath — the same path `event_pass_through` takes, but
1238        // shape-aware (only the rejected sub-region falls through, not the
1239        // whole widget). Default `hit_shape` returns true, so rectangular
1240        // widgets take this branch for free with no behavior change.
1241        if let Some(node) = self.get(id)
1242            && !node.widget.hit_shape(bounds_point, bounds)
1243        {
1244            return None;
1245        }
1246        let pass_through = self.get(id).map(|n| n.event_pass_through).unwrap_or(false);
1247        let children: Vec<WidgetId> = self.children(id).to_vec();
1248        // A child that declares a `Widget::hit_outset` is offered the point
1249        // BEFORE the ordinary reverse-sibling walk, so a thin grip wins over
1250        // whatever it overlaps rather than losing to whichever neighbour is
1251        // painted on top of it. Only the ring OUTSIDE a child's own bounds is
1252        // resolved here — a point genuinely inside a child falls through to the
1253        // normal walk below, which resolves descendants and honours
1254        // `hit_shape`, so declaring an outset never changes where an in-bounds
1255        // press lands.
1256        // A parent that owns a second picking system over the same area gets
1257        // to veto a child for this point — see `Widget::accepts_child_hit`.
1258        // Resolved once here and threaded into `outset_hit`, so a grip cannot
1259        // sneak past a veto the ordinary walk would have honoured.
1260        let parent = self.get(id);
1261        let vetoes = |child: WidgetId| {
1262            parent.is_some_and(|node| !node.widget.accepts_child_hit(child, child_point))
1263        };
1264        if let Some(grip) = self.outset_hit(&children, child_point, exclude, hit, &vetoes) {
1265            return Some(grip);
1266        }
1267        for &child in children.iter().rev() {
1268            if vetoes(child) {
1269                continue;
1270            }
1271            if let Some(found) = self.hit_test_recursive(child, child_point, exclude, hit) {
1272                return Some(found);
1273            }
1274        }
1275        if pass_through {
1276            return None;
1277        }
1278        Some(id)
1279    }
1280
1281    /// The outset pre-pass over one parent's children.
1282    ///
1283    /// A child that declares an outset is offered the point against its
1284    /// **inflated** bounds, ahead of the ordinary reverse-sibling walk, so a
1285    /// thin grip wins over whatever is painted on top of it — both in its ring
1286    /// and in its own body, which is the whole point of a splitter gutter lying
1287    /// under two panes.
1288    ///
1289    /// Ordering is by distance to the child's own uninflated rectangle, so two
1290    /// adjacent grips whose rings overlap split the difference at the midpoint
1291    /// rather than letting sibling order decide; ties go to the later sibling,
1292    /// which is the one painted on top.
1293    ///
1294    /// A candidate is resolved through the ordinary recursion first, so a
1295    /// descendant inside the grip still wins and `hit_shape` is still honoured;
1296    /// only a point genuinely in the ring — outside the child's real bounds —
1297    /// resolves to the child itself. A candidate that resolves to nothing hands
1298    /// over to the next-nearest, and finally to the normal walk.
1299    ///
1300    /// `vetoes` is the parent's own per-point rejection
1301    /// ([`Widget::accepts_child_hit`]),
1302    /// applied here as well as in the ordinary walk — a grip must not win a
1303    /// point the parent has already refused for it.
1304    fn outset_hit(
1305        &self,
1306        children: &[WidgetId],
1307        point: teksilo_canvas::Point,
1308        exclude: Option<WidgetId>,
1309        hit: &HitContext<'_>,
1310        vetoes: &dyn Fn(WidgetId) -> bool,
1311    ) -> Option<WidgetId> {
1312        // Almost every parent has no outset-declaring child at all, so the
1313        // common case allocates nothing and returns on the first loop.
1314        let mut candidates: Vec<(WidgetId, f32, bool)> = Vec::new();
1315        // Walked topmost-first so that, after a STABLE ascending sort, two
1316        // grips at exactly the same distance are resolved in paint order.
1317        for &child in children.iter().rev() {
1318            if !self.is_active(child) || Some(child) == exclude {
1319                continue;
1320            }
1321            let Some(node) = self.get(child) else {
1322                continue;
1323            };
1324            // A decorative or pass-through node never absorbs a press, so
1325            // widening it would only punch a hole in whatever is behind it.
1326            // `no_hit_slop` is the head of the precedence chain and turns off
1327            // BOTH widening mechanisms.
1328            if node.hit_transparent || node.event_pass_through || node.no_hit_slop {
1329                continue;
1330            }
1331            let outset = node.widget.hit_outset(hit.kind(), hit.tokens());
1332            let (top, bottom) = (finite(outset.top), finite(outset.bottom));
1333            let (leading, trailing) = (finite(outset.leading), finite(outset.trailing));
1334            if top <= 0.0 && bottom <= 0.0 && leading <= 0.0 && trailing <= 0.0 {
1335                continue;
1336            }
1337            // The parent's per-point veto applies here too: a grip that the
1338            // ordinary walk would refuse must not win by being offered first.
1339            //
1340            // Asked **after** the zero-outset test, not before. Almost no child
1341            // declares an outset, and this predicate is a real per-point query
1342            // (the `SceneView`'s is a snapshot scan), so asking it first made
1343            // every hit test on a vetoing parent pay it twice per child — once
1344            // here for children that were about to be skipped anyway, and once
1345            // in the ordinary walk. The order does not change the answer: a
1346            // child that survives to `candidates` is exactly one this used to
1347            // reach.
1348            if vetoes(child) {
1349                continue;
1350            }
1351            let Some(space) = self.hit_space(child, point) else {
1352                continue;
1353            };
1354            // Reading order → screen edges.
1355            let (left, right) = match hit.layout_direction() {
1356                crate::environment::LayoutDirection::LeftToRight => (leading, trailing),
1357                crate::environment::LayoutDirection::RightToLeft => (trailing, leading),
1358            };
1359            let inflated = teksilo_canvas::Rect::new(
1360                space.bounds.x - left,
1361                space.bounds.y - top,
1362                space.bounds.width + left + right,
1363                space.bounds.height + top + bottom,
1364            );
1365            if !inflated.contains(space.bounds_point) {
1366                continue;
1367            }
1368            let inside = space.bounds.contains(space.bounds_point);
1369            let distance =
1370                crate::pointer::hit_slop::rect_distance(space.bounds, space.bounds_point);
1371            candidates.push((child, distance, inside));
1372        }
1373        if candidates.is_empty() {
1374            return None;
1375        }
1376        candidates.sort_by(|a, b| a.1.partial_cmp(&b.1).unwrap_or(std::cmp::Ordering::Equal));
1377        for (child, _, inside) in candidates {
1378            if let Some(found) = self.hit_test_recursive(child, point, exclude, hit) {
1379                return Some(found);
1380            }
1381            // The ring: the point is outside the child's real bounds, so the
1382            // ordinary recursion could never have found it, and the outset is
1383            // the whole reason it is being offered.
1384            if !inside {
1385                return Some(child);
1386            }
1387            // Inside the bounds but the recursion declined (a `hit_shape`
1388            // rejection, an empty pass-through): the outset has nothing to add,
1389            // so hand back to the normal walk.
1390        }
1391        None
1392    }
1393
1394    /// Resolve one node's transform for hit-testing: the point to test its own
1395    /// bounds against, the point to hand its children, and its bounds.
1396    ///
1397    /// The input point arrives in this node's parent-effective space. A
1398    /// `set_transform` scope is composed by the render walker around this
1399    /// node's subtree, so hit-testing mirrors it by inverse-applying the
1400    /// transform once. *Which* rectangle the transform applies to depends
1401    /// on whether it's a **content** transform or a **self** transform
1402    /// (see `WidgetNode::content_transform`):
1403    ///
1404    /// * A **content** transform (`content_transform`, e.g. `SceneView`) is
1405    ///   a fixed viewport: its bounds are a rectangle in PARENT space and
1406    ///   the transform pans / zooms only its CONTENT. Test the bounds
1407    ///   against the parent-space point; inverse-transform only for
1408    ///   descending into children, so the whole visible viewport stays
1409    ///   interactive regardless of pan / zoom. (Without this, panning the
1410    ///   content shifts the hittable region off the viewport — clicks /
1411    ///   wheel over the visible scene fall through to whatever is behind.)
1412    /// * A **self** transform (`Scale` / `Rotate`, whose own bounds move
1413    ///   with the transform) inverse-transforms first, then tests its
1414    ///   bounds in the resulting local space (a click lands where the
1415    ///   scaled / rotated visual actually is).
1416    ///
1417    /// Identity / missing transforms collapse both paths to the scalar
1418    /// case, so the hot path stays cheap. `content_transform` is
1419    /// `SceneView`-only today, so this only changes SceneView hit-testing;
1420    /// `Scale` / `Rotate` (also `clips_children`) keep the self-transform
1421    /// path.
1422    ///
1423    /// `None` when the transform is singular (a collapsed axis) — that hides
1424    /// the entire subtree visually, and hit-testing mirrors it.
1425    fn hit_space(&self, id: WidgetId, point: teksilo_canvas::Point) -> Option<HitSpace> {
1426        let transform = self
1427            .get(id)
1428            .and_then(|n| n.transform_prop.as_ref())
1429            .map(|p| p.get())
1430            .filter(|t| !t.is_identity());
1431        let content_transform = self.get(id).map(|n| n.content_transform).unwrap_or(false);
1432        let child_point = match transform {
1433            Some(t) => t.inverse()?.apply_point(point),
1434            None => point,
1435        };
1436        let bounds_point = if content_transform {
1437            point
1438        } else {
1439            child_point
1440        };
1441        Some(HitSpace {
1442            bounds_point,
1443            child_point,
1444            bounds: self.bounds(id),
1445            scale: transform
1446                .as_ref()
1447                .map(crate::pointer::hit_slop::min_singular_value)
1448                .unwrap_or(1.0),
1449        })
1450    }
1451
1452    /// Every node the *miss-only* slop pass would consider for `point`, nearest
1453    /// first, scoped to `start`'s subtree.
1454    ///
1455    /// Public so a test — and the target-conformance audit — can inspect the
1456    /// pass's reasoning rather than only its verdict. Returning candidates does
1457    /// **not** mean one of them wins: see
1458    /// [`hit_test_at_with_slop`](Self::hit_test_at_with_slop) for the
1459    /// bubble-path rule that decides.
1460    ///
1461    /// # Eligibility
1462    ///
1463    /// A node is a candidate only if all of the following hold. Each is pinned
1464    /// by its own test in `widget_tree::hit_targeting_tests`.
1465    ///
1466    /// * It earns a non-zero outset from its resolved [`HitSlop`] — which, by
1467    ///   the size formula, excludes anything already at least `up_to` on its
1468    ///   smaller axis. A scrim, a page, a list row are excluded by arithmetic.
1469    /// * It would actually *do* something with the press:
1470    ///   [`takes_a_press`](Self::takes_a_press). Re-attributing to a node that
1471    ///   ignores presses would silently swallow one.
1472    /// * It is **enabled** — its own `enabled_state` and every ancestor's.
1473    /// * It is not **read-only**, as reported by the context's probe.
1474    /// * It does not carry `no_hit_slop`, and it is not `event_pass_through`
1475    ///   (which absorbs nothing; its **children** stay eligible).
1476    /// * It is not inside a `hit_transparent` subtree — those are pruned whole.
1477    /// * No `clips_children` ancestor's **uninflated** rectangle excludes the
1478    ///   point: slop never reaches out of a scroller.
1479    /// * Its [`Widget::hit_distance`] answers `Some(d)` with `0 < d ≤ outset`.
1480    ///   `d = 0` means the point is inside the shape, which is the exact pass's
1481    ///   business — the slop pass only ever re-attributes a genuine miss.
1482    ///
1483    /// Distances are measured in each node's own space and converted to screen
1484    /// dp through the accumulated
1485    /// [`min_singular_value`](crate::pointer::hit_slop::min_singular_value) of
1486    /// the transforms above it. For a chain of transforms the product of the
1487    /// per-node minima is a lower bound on the true composed minimum, so the
1488    /// reach under a stack of transforms errs towards being generous rather
1489    /// than short.
1490    ///
1491    /// [`HitSlop`]: crate::pointer::hit_slop::HitSlop
1492    /// [`Widget::hit_distance`]: crate::widget::Widget::hit_distance
1493    pub fn hit_candidates(
1494        &self,
1495        start: WidgetId,
1496        point: teksilo_canvas::Point,
1497        exclude: Option<WidgetId>,
1498        hit: &HitContext<'_>,
1499    ) -> Vec<HitCandidate> {
1500        let mut out = Vec::new();
1501        if hit.slop_enabled() {
1502            self.collect_candidates(start, point, 1.0, true, exclude, hit, &mut out);
1503            out.sort_by(|a, b| {
1504                a.distance
1505                    .partial_cmp(&b.distance)
1506                    .unwrap_or(std::cmp::Ordering::Equal)
1507            });
1508        }
1509        out
1510    }
1511
1512    #[allow(clippy::too_many_arguments)]
1513    fn collect_candidates(
1514        &self,
1515        id: WidgetId,
1516        point: teksilo_canvas::Point,
1517        scale: f32,
1518        enabled: bool,
1519        exclude: Option<WidgetId>,
1520        hit: &HitContext<'_>,
1521        out: &mut Vec<HitCandidate>,
1522    ) {
1523        if !self.is_active(id) || Some(id) == exclude {
1524            return;
1525        }
1526        let Some(node) = self.get(id) else { return };
1527        // Decorative subtree: pruned whole, exactly as in the exact pass.
1528        if node.hit_transparent {
1529            return;
1530        }
1531        let Some(space) = self.hit_space(id, point) else {
1532            return;
1533        };
1534        // Slop never escapes a clipping ancestor's UNINFLATED rectangle: a
1535        // control scrolled out of a `ScrollArea` must not catch a press landing
1536        // on the scroller's border.
1537        if node.clips_children && !space.bounds.contains(space.bounds_point) {
1538            return;
1539        }
1540        let enabled = enabled
1541            && node
1542                .enabled_state
1543                .as_ref()
1544                .map(|state| state.get())
1545                .unwrap_or(true);
1546        let scale_children = scale * space.scale;
1547        // A content transform leaves the node's own bounds in parent space; a
1548        // self transform moves them with it.
1549        let scale_self = if node.content_transform {
1550            scale
1551        } else {
1552            scale_children
1553        };
1554        // A node with no area is a helper, not a control: a frame-tick driver,
1555        // a measuring probe, a collapsed placeholder. Nobody aimed at it, and
1556        // the size formula would hand it the largest top-up there is, so it
1557        // would catch every miss within reach of a point. Its children are
1558        // still walked: an empty node may host real content that overflows it.
1559        let has_area = space.bounds.width > 0.0 && space.bounds.height > 0.0;
1560        if enabled
1561            && has_area
1562            && !node.no_hit_slop
1563            && !node.event_pass_through
1564            && !hit.is_read_only(id)
1565            && self.takes_a_press(id)
1566        {
1567            let slop = node
1568                .hit_slop
1569                .or_else(|| node.widget.hit_slop(hit.kind(), hit.tokens()))
1570                .unwrap_or_else(|| hit.default_slop());
1571            let outset = slop.outset_for(space.bounds.size());
1572            if outset > 0.0
1573                && let Some(local) = node.widget.hit_distance(space.bounds_point, space.bounds)
1574            {
1575                let distance = local * scale_self;
1576                if distance > 0.0 && distance <= outset && distance.is_finite() {
1577                    out.push(HitCandidate {
1578                        id,
1579                        distance,
1580                        outset,
1581                    });
1582                }
1583            }
1584        }
1585        for &child in self.children(id) {
1586            self.collect_candidates(
1587                child,
1588                space.child_point,
1589                scale_children,
1590                enabled,
1591                exclude,
1592                hit,
1593                out,
1594            );
1595        }
1596    }
1597
1598    /// Whether a press landing on this node would do anything at all — the
1599    /// definition of an "eligible handler" for the slop pass's bubble-path
1600    /// rule.
1601    ///
1602    /// A node qualifies if it carries any pointer-facing handler (tap, multi
1603    /// tap, long press, drag, swipe, pinch, the raw pointer stream, scroll) or
1604    /// is focusable, and is enabled. Accessibility actions and key handlers do
1605    /// not count: neither is reachable from a pointer.
1606    pub fn takes_a_press(&self, id: WidgetId) -> bool {
1607        let Some(node) = self.get(id) else {
1608            return false;
1609        };
1610        if !self.is_enabled(id) {
1611            return false;
1612        }
1613        let pointer_facing = |h: &crate::event_handlers::EventHandlers| {
1614            h.on_tap.is_some()
1615                || h.on_double_tap.is_some()
1616                || h.on_triple_tap.is_some()
1617                || h.on_long_press.is_some()
1618                || h.on_drag.is_some()
1619                || h.on_swipe.is_some()
1620                || h.on_pinch.is_some()
1621                || h.on_pointer_event.is_some()
1622                || h.on_scroll.is_some()
1623        };
1624        pointer_facing(&node.handlers)
1625            || pointer_facing(&node.external_handlers)
1626            || node.node_focusable.unwrap_or(false)
1627    }
1628
1629    /// Run the miss-only pass over `roots` and decide between it and `exact`.
1630    ///
1631    /// The rule, in one place: the exact hit's **entire bubble path** is
1632    /// examined, and a slop candidate wins only when that path carries no
1633    /// eligible handler at all, or when the candidate is strictly closer than
1634    /// the bubble owner's *uninflated* shape. That is what keeps a press on a
1635    /// row label 5 dp from an inline checkbox on the row — the row owns the
1636    /// press at distance zero, and nothing beats zero.
1637    fn apply_slop(
1638        &self,
1639        roots: Vec<WidgetId>,
1640        point: teksilo_canvas::Point,
1641        exclude: Option<WidgetId>,
1642        hit: &HitContext<'_>,
1643        exact: Option<WidgetId>,
1644    ) -> Option<WidgetId> {
1645        if !hit.slop_enabled() {
1646            return exact;
1647        }
1648        let owner_distance = match exact.and_then(|target| self.bubble_owner(target, &roots)) {
1649            Some(owner) => self.distance_to(owner, point, &roots).unwrap_or(0.0),
1650            // Either nothing was hit, or what was hit ignores presses all the
1651            // way up: there is nothing to beat.
1652            None => f32::INFINITY,
1653        };
1654        if owner_distance <= 0.0 {
1655            return exact;
1656        }
1657        // A grip that won its point through its own `Widget::hit_outset` made a
1658        // deliberate claim *inside* the exact pass, and the miss-only pass must
1659        // not take it back.
1660        //
1661        // Without this the two mechanisms fight, and the outset loses every
1662        // time: a grip only ever claims a point at a positive distance from its
1663        // own shape, so any slop-eligible node under its ring is strictly
1664        // closer and wins. The rule, rather than the arithmetic: a ring is taken
1665        // back wherever a neighbour is still small enough to earn a top-up of
1666        // its own, so raising the density can LOWER a grip's reach — `up_to`
1667        // grows from 24 to 44 dp and rows that earned nothing become candidates.
1668        // It is not confined to the coarse densities either: at Compact a
1669        // neighbour under 24 dp is already a candidate.
1670        //
1671        // The two measurements this rests on are pinned in
1672        // teksilo-target-conformance by
1673        // `an_outsets_claim_survives_the_slop_pass_in_the_shipped_controls`
1674        // (a SearchField's clear button at Compact, a TableView's scroll bar at
1675        // Touch), and the mechanism itself by
1676        // `a_grip_that_won_through_its_outset_keeps_its_point_against_the_slop_pass`
1677        // in this crate. Reverting this branch reddens all three. The precedence
1678        // chain in `docs/density-and-targets.md` names one chain for both
1679        // mechanisms, and this is what keeps it one.
1680        if exact.is_some_and(|target| self.won_through_outset(target, point, &roots, hit)) {
1681            return exact;
1682        }
1683        let mut best: Option<HitCandidate> = None;
1684        for &root in roots.iter().rev() {
1685            for candidate in self.hit_candidates(root, point, exclude, hit) {
1686                if candidate.distance < owner_distance
1687                    && best.is_none_or(|b| candidate.distance < b.distance)
1688                {
1689                    best = Some(candidate);
1690                }
1691            }
1692        }
1693        best.map(|c| c.id).or(exact)
1694    }
1695
1696    /// The deepest node on `target`'s own path (itself, then ancestors, up to
1697    /// and including whichever of `roots` contains it) that would act on a
1698    /// press.
1699    fn bubble_owner(&self, target: WidgetId, roots: &[WidgetId]) -> Option<WidgetId> {
1700        let mut current = Some(target);
1701        while let Some(id) = current {
1702            if self.takes_a_press(id) {
1703                return Some(id);
1704            }
1705            if roots.contains(&id) {
1706                return None;
1707            }
1708            current = self.get(id).and_then(|n| n.parent);
1709        }
1710        None
1711    }
1712
1713    /// Whether `target`, or a node on its path to a root, claimed `point`
1714    /// through its own [`Widget::hit_outset`] — the point sits outside that
1715    /// node's real bounds and inside its inflated ones.
1716    ///
1717    /// The predicate behind the outset's precedence over the miss-only pass in
1718    /// [`apply_slop`](Self::apply_slop). The whole path is examined because the
1719    /// pre-pass resolves a candidate *through* the ordinary recursion, so the
1720    /// node the exact pass returns may be a descendant of the grip that won.
1721    ///
1722    /// [`Widget::hit_outset`]: crate::widget::Widget::hit_outset
1723    fn won_through_outset(
1724        &self,
1725        target: WidgetId,
1726        point: teksilo_canvas::Point,
1727        roots: &[WidgetId],
1728        hit: &HitContext<'_>,
1729    ) -> bool {
1730        let mut chain = vec![target];
1731        let mut current = target;
1732        while !roots.contains(&current) {
1733            match self.get(current).and_then(|n| n.parent) {
1734                Some(parent) => {
1735                    chain.push(parent);
1736                    current = parent;
1737                }
1738                None => break,
1739            }
1740        }
1741        chain.reverse();
1742        let mut p = point;
1743        for &node_id in &chain {
1744            let Some(space) = self.hit_space(node_id, p) else {
1745                return false;
1746            };
1747            let Some(node) = self.get(node_id) else {
1748                return false;
1749            };
1750            if !node.no_hit_slop {
1751                let outset = node.widget.hit_outset(hit.kind(), hit.tokens());
1752                let (top, bottom) = (finite(outset.top), finite(outset.bottom));
1753                let (leading, trailing) = (finite(outset.leading), finite(outset.trailing));
1754                if top > 0.0 || bottom > 0.0 || leading > 0.0 || trailing > 0.0 {
1755                    let (left, right) = match hit.layout_direction() {
1756                        crate::environment::LayoutDirection::LeftToRight => (leading, trailing),
1757                        crate::environment::LayoutDirection::RightToLeft => (trailing, leading),
1758                    };
1759                    let inflated = teksilo_canvas::Rect::new(
1760                        space.bounds.x - left,
1761                        space.bounds.y - top,
1762                        space.bounds.width + left + right,
1763                        space.bounds.height + top + bottom,
1764                    );
1765                    if !space.bounds.contains(space.bounds_point)
1766                        && inflated.contains(space.bounds_point)
1767                    {
1768                        return true;
1769                    }
1770                }
1771            }
1772            p = space.child_point;
1773        }
1774        false
1775    }
1776
1777    /// Distance from a root-space `point` to `id`'s own shape, in screen dp.
1778    ///
1779    /// Walks down from whichever of `roots` owns `id` so the transforms are
1780    /// applied in the same order the hit test applies them, and converts the
1781    /// local distance through the accumulated minimum singular value.
1782    fn distance_to(
1783        &self,
1784        id: WidgetId,
1785        point: teksilo_canvas::Point,
1786        roots: &[WidgetId],
1787    ) -> Option<f32> {
1788        let mut chain = vec![id];
1789        let mut current = id;
1790        while !roots.contains(&current) {
1791            match self.get(current).and_then(|n| n.parent) {
1792                Some(parent) => {
1793                    chain.push(parent);
1794                    current = parent;
1795                }
1796                None => break,
1797            }
1798        }
1799        chain.reverse();
1800        let mut p = point;
1801        let mut scale = 1.0_f32;
1802        for (index, &node_id) in chain.iter().enumerate() {
1803            let space = self.hit_space(node_id, p)?;
1804            if index + 1 == chain.len() {
1805                let scale_self = if self.get(node_id).map(|n| n.content_transform)? {
1806                    scale
1807                } else {
1808                    scale * space.scale
1809                };
1810                let local = self
1811                    .get(node_id)?
1812                    .widget
1813                    .hit_distance(space.bounds_point, space.bounds)?;
1814                return Some(local * scale_self);
1815            }
1816            scale *= space.scale;
1817            p = space.child_point;
1818        }
1819        None
1820    }
1821
1822    /// Iterate over all active widget IDs.
1823    ///
1824    /// Allocating wrapper around [`Self::active_ids_iter`]. Hot-path
1825    /// callers that hold `&self` for the whole iteration should call
1826    /// the iterator directly to avoid the per-call `Vec` allocation;
1827    /// callers that need an owned snapshot (because they mutate
1828    /// arena state inside the loop) should use
1829    /// [`Self::fill_active_ids`] with a reusable buffer.
1830    pub fn active_ids(&self) -> Vec<WidgetId> {
1831        self.active_ids_iter().collect()
1832    }
1833
1834    /// Stream all active widget IDs without allocating. The iterator
1835    /// borrows the arena, so the caller cannot mutate it while
1836    /// iterating — for that case use [`Self::fill_active_ids`].
1837    pub fn active_ids_iter(&self) -> impl Iterator<Item = WidgetId> + '_ {
1838        self.nodes
1839            .iter()
1840            .filter(|(_, node)| node.activation == ActivationState::Active)
1841            .map(|(id, _)| id)
1842    }
1843
1844    /// Fill `out` with every active widget ID. Clears `out` first so
1845    /// callers can reuse a long-lived buffer across calls. Use this
1846    /// when the iteration site needs an owned snapshot independent
1847    /// of the arena borrow (typically because it mutates per-widget
1848    /// state with `arena.get_mut(id)` inside the loop).
1849    pub fn fill_active_ids(&self, out: &mut Vec<WidgetId>) {
1850        out.clear();
1851        out.extend(self.active_ids_iter());
1852    }
1853
1854    /// Set a widget subtree to dormant state (state preserved, not rendered).
1855    /// Recursively dormants all children.
1856    ///
1857    /// The node named here is marked self-parked (`WidgetNode::self_dormant`);
1858    /// the descendants swept along by the recursion are not, since their
1859    /// dormancy belongs to this ancestor rather than to them. That distinction
1860    /// is what lets [`activate`](Self::activate) put the subtree back exactly as
1861    /// it found it instead of waking content that was already closed.
1862    ///
1863    /// **Returns the whole parked subtree**, `id` first, because a caller that
1864    /// cannot see which nodes went to sleep cannot cancel the pointers holding
1865    /// them. Dormancy is invisible to hit-testing and to dispatch, so a widget
1866    /// parked mid-interaction keeps whatever the press latched and never
1867    /// receives another event: the ids are how the tree finds it and tells it
1868    /// to let go. Every caller is audited in `docs/touch-and-pen.md` §3.3.
1869    pub fn set_dormant(&mut self, id: WidgetId) -> Vec<WidgetId> {
1870        let mut parked = Vec::new();
1871        self.park(id, true, &mut parked);
1872        parked
1873    }
1874
1875    /// [`set_dormant`](Self::set_dormant)'s body, plus whether `id` is being
1876    /// parked on its own account or dragged along by an ancestor, and the
1877    /// accumulator the parked ids land in.
1878    ///
1879    /// A node already self-parked stays that way when an ancestor sweeps over
1880    /// it — the flag is only ever set here, never cleared, so nesting two
1881    /// dormancy cycles cannot lose the inner one.
1882    fn park(&mut self, id: WidgetId, on_its_own_account: bool, parked: &mut Vec<WidgetId>) {
1883        if let Some(node) = self.nodes.get_mut(id) {
1884            let was_active = node.activation == ActivationState::Active;
1885            node.activation = ActivationState::Dormant;
1886            if on_its_own_account {
1887                node.self_dormant = true;
1888            }
1889            // Record the Active→Dormant transition for nodes that opted into an
1890            // activation signal; the signal is fired later by
1891            // `WidgetTree::flush_activation_signals`, not here — see the
1892            // `pending_activation_changes` field docs.
1893            if was_active && node.activation_signal.is_some() {
1894                self.pending_activation_changes.push((id, false));
1895            }
1896            parked.push(id);
1897        }
1898        let children: Vec<WidgetId> = self.children(id).to_vec();
1899        for child in children {
1900            self.park(child, false, parked);
1901        }
1902    }
1903
1904    /// Activate a dormant widget subtree (triggers relayout and repaint).
1905    /// Recursively activates all children, **except** those a descendant
1906    /// widget has independently gated off via `visible_when(false)`.
1907    ///
1908    /// The directly-targeted `id` is always activated (the caller asked for
1909    /// it). When recursing, a child whose own `visible_state` currently
1910    /// evaluates to `false` is left dormant along with its subtree: it is
1911    /// hidden by its own gate, not by the ancestor's dormancy, so a parent
1912    /// reactivation must not wake it. This is what keeps a `ComboBox`'s
1913    /// closed dropdown panel, a collapsed overlay, or any `visible_when`-
1914    /// gated child from leaking back to the screen when an ancestor (e.g. a
1915    /// `Toolbar` item reappearing from overflow) is re-activated. The
1916    /// per-pass visibility reconciliation
1917    /// ([`visibility_checks_iter`](Self::visibility_checks_iter)) still owns
1918    /// the eventual activate/dormant transitions when the gate flips.
1919    pub fn activate(&mut self, id: WidgetId) {
1920        if let Some(node) = self.nodes.get_mut(id) {
1921            // Only Dormant→Active is a real "show" transition. Guard on
1922            // `== Dormant` (not `!= Active`) so a `Destroyed` node — or any
1923            // future non-Active state — is never resurrected or signalled.
1924            let was_dormant = node.activation == ActivationState::Dormant;
1925            node.activation = ActivationState::Active;
1926            node.self_dormant = false;
1927            node.dirty.needs_layout = true;
1928            node.dirty.needs_paint = true;
1929            // A relayout requested off the UI thread while it slept: take it
1930            // (re-arming the request), since the pre-pass skips sleepers.
1931            if let Some(wake) = &node.repaint_wake
1932                && wake.take_relayout()
1933            {
1934                self.relayout_rewake.push(id);
1935            }
1936            if was_dormant && node.activation_signal.is_some() {
1937                self.pending_activation_changes.push((id, true));
1938            }
1939        }
1940        let children: Vec<WidgetId> = self.children(id).to_vec();
1941        for child in children {
1942            let asleep_on_its_own_account = self
1943                .nodes
1944                .get(child)
1945                .map(|n| {
1946                    n.self_dormant
1947                        || n.visible_state
1948                            .as_ref()
1949                            .map(|vs| !vs.get())
1950                            .unwrap_or(false)
1951                })
1952                .unwrap_or(false);
1953            if asleep_on_its_own_account {
1954                continue;
1955            }
1956            self.activate(child);
1957        }
1958    }
1959
1960    /// Destroy a widget and remove it from the arena entirely.
1961    /// Recursively destroys all children. State is gone.
1962    pub fn destroy(&mut self, id: WidgetId) {
1963        self.roots_dirty = true;
1964        let children: Vec<WidgetId> = self.children(id).to_vec();
1965        for child in children {
1966            self.destroy(child);
1967        }
1968        self.remove_node(id);
1969    }
1970
1971    /// Remove a *single* node: unlink it from its parent's child list and drop
1972    /// it from the arena. Does **not** recurse into its children.
1973    ///
1974    /// The caller owns the recursion. This exists for
1975    /// [`WidgetTree::destroy_subtree`](crate::widget_tree::WidgetTree) /
1976    /// the reconciling rebuild path, which walks the subtree itself so it can
1977    /// honour re-parenting — a child re-homed into the surviving tree must NOT
1978    /// be torn down via this node's now-stale `children` list. Using
1979    /// [`destroy`](Self::destroy) there would re-recurse that stale list and
1980    /// destroy the re-homed survivor.
1981    pub fn remove_node(&mut self, id: WidgetId) {
1982        self.roots_dirty = true;
1983        if let Some(parent_id) = self.parent(id)
1984            && let Some(parent) = self.nodes.get_mut(parent_id)
1985        {
1986            parent.children.retain(|&c| c != id);
1987        }
1988        self.nodes.remove(id);
1989    }
1990
1991    /// Drain the buffered Active↔Dormant transitions recorded since the last
1992    /// call. Each `(id, active)` is fed to `WidgetTree::flush_activation_signals`
1993    /// which fires the node's `activation_signal` — at the tree level, outside
1994    /// any arena mutation.
1995    pub(crate) fn take_activation_changes(&mut self) -> Vec<(WidgetId, bool)> {
1996        std::mem::take(&mut self.pending_activation_changes)
1997    }
1998
1999    /// Record that `id` installed an `effective_enabled_signal`. Idempotent —
2000    /// the signal is install-or-reuse, so a rebuild re-registering the same
2001    /// node must not grow the list.
2002    pub(crate) fn watch_effective_enabled(&mut self, id: WidgetId) {
2003        if !self.effective_enabled_watchers.contains(&id) {
2004            self.effective_enabled_watchers.push(id);
2005        }
2006    }
2007
2008    /// The nodes carrying an `effective_enabled_signal`, for the per-pass
2009    /// refresh. Cloned so the caller can recompute `is_enabled` (an immutable
2010    /// ancestor walk) without holding a borrow on the arena.
2011    pub(crate) fn effective_enabled_watchers(&self) -> Vec<WidgetId> {
2012        self.effective_enabled_watchers.clone()
2013    }
2014
2015    /// Drop watchers whose node is gone (destroyed / rebuilt away).
2016    pub(crate) fn prune_effective_enabled_watchers(&mut self) {
2017        self.effective_enabled_watchers
2018            .retain(|id| self.nodes.contains_key(*id));
2019    }
2020
2021    pub fn is_active(&self, id: WidgetId) -> bool {
2022        self.nodes
2023            .get(id)
2024            .map(|n| n.activation == ActivationState::Active)
2025            .unwrap_or(false)
2026    }
2027
2028    pub fn len(&self) -> usize {
2029        self.nodes.len()
2030    }
2031
2032    pub fn is_empty(&self) -> bool {
2033        self.nodes.is_empty()
2034    }
2035
2036    pub fn mark_all_clean(&mut self) {
2037        for (_, node) in self.nodes.iter_mut() {
2038            node.dirty = DirtyFlags::default();
2039        }
2040    }
2041
2042    pub fn any_needs_layout(&self) -> bool {
2043        self.nodes
2044            .values()
2045            .any(|n| n.activation == ActivationState::Active && n.dirty.needs_layout)
2046    }
2047
2048    pub fn any_needs_paint(&self) -> bool {
2049        self.nodes
2050            .values()
2051            .any(|n| n.activation == ActivationState::Active && n.dirty.needs_paint)
2052    }
2053
2054    pub fn mark_needs_paint(&mut self, id: WidgetId) {
2055        if let Some(node) = self.nodes.get_mut(id) {
2056            node.dirty.needs_paint = true;
2057        }
2058    }
2059
2060    /// Recursively mark a widget and all its descendants needs_paint.
2061    /// Used by callers that want a fresh paint of an entire subtree
2062    /// — e.g. a rich tooltip whose dwell indicator child would
2063    /// otherwise reuse its cached_paint while the parent re-runs
2064    /// some per-frame logic.
2065    pub fn mark_subtree_needs_paint(&mut self, id: WidgetId) {
2066        if let Some(node) = self.nodes.get_mut(id) {
2067            node.dirty.needs_paint = true;
2068        }
2069        let children: Vec<WidgetId> = self.children(id).to_vec();
2070        for child in children {
2071            self.mark_subtree_needs_paint(child);
2072        }
2073    }
2074
2075    pub fn mark_needs_layout(&mut self, id: WidgetId) {
2076        if let Some(node) = self.nodes.get_mut(id) {
2077            node.dirty.needs_layout = true;
2078            node.dirty.needs_paint = true;
2079        }
2080    }
2081
2082    /// Mark a widget as needing its `build()` re-run.
2083    /// Also marks for layout and paint since rebuilt children need both.
2084    pub fn mark_needs_rebuild(&mut self, id: WidgetId) {
2085        if let Some(node) = self.nodes.get_mut(id) {
2086            node.dirty.needs_rebuild = true;
2087            node.dirty.needs_layout = true;
2088            node.dirty.needs_paint = true;
2089        }
2090    }
2091
2092    /// Collect widgets that need their `build()` re-run (data-driven rebuild).
2093    /// Only returns active widgets with `needs_rebuild == true`.
2094    ///
2095    /// Allocating wrapper around [`Self::needs_rebuild_iter`]. Prefer
2096    /// the iterator on hot paths.
2097    pub fn collect_needs_rebuild(&self) -> Vec<WidgetId> {
2098        self.needs_rebuild_iter().collect()
2099    }
2100
2101    /// Stream widgets that need `build()` re-run without allocating.
2102    ///
2103    /// `needs_rebuild` is set only by `BindingLevel::Rebuild` bindings —
2104    /// i.e. on composing widgets that explicitly want `build()` re-run
2105    /// when their data model changes. It is intentionally NOT gated on
2106    /// the widget currently having children: a data-driven widget that
2107    /// builds its children directly and starts EMPTY (e.g. the toast
2108    /// host with no toasts yet, an empty list that renders rows without
2109    /// a persistent container) must still rebuild to materialise its
2110    /// FIRST child. `rebuild_single_widget` handles a childless widget
2111    /// correctly (nothing to tear down, then it adopts `build()`'s
2112    /// output).
2113    pub fn needs_rebuild_iter(&self) -> impl Iterator<Item = WidgetId> + '_ {
2114        self.nodes
2115            .iter()
2116            .filter(|(_, n)| n.activation == ActivationState::Active && n.dirty.needs_rebuild)
2117            .map(|(id, _)| id)
2118    }
2119
2120    /// Check all widgets with visible_state bindings and return
2121    /// (id, is_currently_active, should_be_visible) tuples.
2122    ///
2123    /// Allocating wrapper around [`Self::visibility_checks_iter`].
2124    pub fn visibility_checks(&self) -> Vec<(WidgetId, bool, bool)> {
2125        self.visibility_checks_iter().collect()
2126    }
2127
2128    /// Stream widgets with `visible_state` bindings without
2129    /// allocating. Each entry is `(id, is_currently_active,
2130    /// should_be_visible)`.
2131    pub fn visibility_checks_iter(&self) -> impl Iterator<Item = (WidgetId, bool, bool)> + '_ {
2132        self.nodes.iter().filter_map(|(id, node)| {
2133            node.visible_state.as_ref().map(|state| {
2134                let is_active = node.activation == ActivationState::Active;
2135                let should_be_visible = state.get();
2136                (id, is_active, should_be_visible)
2137            })
2138        })
2139    }
2140
2141    /// Check if a widget is effectively enabled, walking up the parent chain.
2142    ///
2143    /// Returns `false` if the widget itself or any ancestor has `enabled_state`
2144    /// bound to `false`. This lets containers like `GroupBox` disable a whole
2145    /// subtree by binding a single signal on their content wrapper.
2146    pub fn is_enabled(&self, id: WidgetId) -> bool {
2147        let mut current = Some(id);
2148        while let Some(node_id) = current {
2149            if let Some(node) = self.nodes.get(node_id) {
2150                if let Some(ref state) = node.enabled_state
2151                    && !state.get()
2152                {
2153                    return false;
2154                }
2155                current = node.parent;
2156            } else {
2157                return true;
2158            }
2159        }
2160        true
2161    }
2162
2163    /// Set a per-child alignment override on a widget.
2164    pub fn set_alignment_override(&mut self, id: WidgetId, alignment: teksilo_tokens::Alignment) {
2165        if let Some(node) = self.get_mut(id) {
2166            node.alignment_override = Some(alignment);
2167        }
2168    }
2169
2170    /// Mark a widget as clipping its children (scroll area, overflow hidden).
2171    pub fn set_clips_children(&mut self, id: WidgetId, clips: bool) {
2172        if let Some(node) = self.get_mut(id) {
2173            node.clips_children = clips;
2174        }
2175    }
2176
2177    /// The OS-IME descriptor for the widget at `id`, or `None` if the node
2178    /// is not a text-input surface (the default) or the id is unknown. The
2179    /// platform IME layer queries this for the focused widget to decide
2180    /// whether to enable the OS input method and with which purpose.
2181    pub fn ime_context(&self, id: WidgetId) -> Option<crate::ime::ImeContext> {
2182        self.get(id).and_then(|n| n.ime)
2183    }
2184
2185    /// Set (or clear, with `None`) the OS-IME descriptor for the widget at
2186    /// `id`.
2187    pub fn set_ime_context(&mut self, id: WidgetId, ime: Option<crate::ime::ImeContext>) {
2188        if let Some(node) = self.get_mut(id) {
2189            node.ime = ime;
2190        }
2191    }
2192
2193    /// Apply a `HandlerSet` to an existing node, merging handlers and
2194    /// transferring node-level metadata (focusable, cursor, clips,
2195    /// context menu). The `scope` argument controls whether the
2196    /// handlers go into the rebuild-cleared `handlers` slot or the
2197    /// persistent `external_handlers` slot.
2198    pub(crate) fn apply_handler_set(
2199        &mut self,
2200        id: WidgetId,
2201        handler_set: crate::widget_builder::HandlerSet,
2202        scope: HandlerScope,
2203    ) {
2204        if let Some(node) = self.get_mut(id) {
2205            let target = match scope {
2206                HandlerScope::Own => &mut node.handlers,
2207                HandlerScope::External => &mut node.external_handlers,
2208            };
2209            let existing = std::mem::take(target);
2210            *target = existing.merge(handler_set.handlers);
2211            if let Some(focusable) = handler_set.focusable {
2212                node.node_focusable = Some(focusable);
2213            }
2214            if let Some(tab_index) = handler_set.tab_index {
2215                node.node_tab_index = Some(tab_index);
2216            }
2217            if let Some(cursor) = handler_set.cursor {
2218                node.node_cursor = Some(cursor);
2219            }
2220            if let Some(clips) = handler_set.clips_children {
2221                node.clips_children = clips;
2222            }
2223            if let Some(ime) = handler_set.ime {
2224                node.ime = Some(ime);
2225            }
2226            if let Some(pass_through) = handler_set.event_pass_through {
2227                node.event_pass_through = pass_through;
2228            }
2229            if let Some(dead_zone) = handler_set.gesture_dead_zone {
2230                node.gesture_dead_zone = dead_zone;
2231            }
2232            if let Some(role) = handler_set.long_press_role {
2233                node.long_press_role = role;
2234            }
2235            if let Some(action) = handler_set.touch_action {
2236                node.touch_action = action;
2237            }
2238            if let Some(claim) = handler_set.pan_claim {
2239                node.pan_claim = Some(claim);
2240            }
2241            if let Some(behavior) = handler_set.overscroll_behavior {
2242                node.overscroll_behavior = behavior;
2243            }
2244            if let Some(activation) = handler_set.drag_activation {
2245                node.drag_activation = activation;
2246            }
2247            if let Some(policy) = handler_set.multi_contact {
2248                node.multi_contact = policy;
2249            }
2250            if let Some(keyboard_capture) = handler_set.keyboard_capture {
2251                node.keyboard_capture = keyboard_capture;
2252            }
2253            if let Some(hit_transparent) = handler_set.hit_transparent {
2254                node.hit_transparent = hit_transparent;
2255            }
2256            if let Some(slop) = handler_set.hit_slop {
2257                node.hit_slop = Some(slop);
2258            }
2259            if let Some(no_slop) = handler_set.no_hit_slop {
2260                node.no_hit_slop = no_slop;
2261            }
2262            if handler_set.context_menu_factory.is_some() {
2263                node.context_menu_factory = handler_set.context_menu_factory;
2264            }
2265            if let Some(sig) = handler_set.focus_within {
2266                node.focus_within_signal = Some(sig);
2267            }
2268            if let Some(sig) = handler_set.hover_within {
2269                node.hover_within_signal = Some(sig);
2270            }
2271            // Mirror builder-level accessibility overrides + subtree mode
2272            // onto the persistent WidgetNode so the accessibility tree
2273            // walker (and the event dispatcher, for action callbacks) can
2274            // read them after handler extraction.
2275            if handler_set.access.is_some() {
2276                // Merged, not assigned: a node can already carry a
2277                // block from its builder chain, and replacing it
2278                // drops everything in it (see
2279                // `AccessibilityOverrides::merge_from`).
2280                match (&mut node.access_overrides, handler_set.access) {
2281                    (Some(existing), Some(incoming)) => existing.merge_from(*incoming),
2282                    (slot, incoming) => *slot = incoming,
2283                }
2284            }
2285            if let Some(mode) = handler_set.access_subtree {
2286                node.access_subtree = mode;
2287            }
2288        }
2289    }
2290
2291    /// Get a widget's alignment override, if any.
2292    pub fn alignment_override(&self, id: WidgetId) -> Option<teksilo_tokens::Alignment> {
2293        self.get(id)?.alignment_override
2294    }
2295
2296    /// Temporarily take the widget box out of a node (for rebuild).
2297    /// The node remains in the arena with a placeholder.
2298    pub fn take_widget(&mut self, id: WidgetId) -> Option<Box<dyn Widget>> {
2299        let node = self.nodes.get_mut(id)?;
2300        // Replace with a minimal placeholder
2301        let taken = std::mem::replace(&mut node.widget, Box::new(PlaceholderWidget));
2302        Some(taken)
2303    }
2304
2305    /// Restore a widget box that was previously taken out.
2306    pub fn restore_widget(&mut self, id: WidgetId, widget: Box<dyn Widget>) {
2307        if let Some(node) = self.nodes.get_mut(id) {
2308            node.widget = widget;
2309        }
2310    }
2311
2312    /// Walk up the parent chain from `id` and mark each ancestor as needing layout.
2313    /// Called when a relayout-level binding changes, since a child's size change
2314    /// may affect its parent's size, and so on up to the root.
2315    pub fn mark_ancestors_need_layout(&mut self, id: WidgetId) {
2316        let mut current = self.parent(id);
2317        while let Some(pid) = current {
2318            if let Some(node) = self.get_mut(pid) {
2319                node.dirty.needs_layout = true;
2320                node.dirty.needs_paint = true;
2321            }
2322            current = self.parent(pid);
2323        }
2324    }
2325
2326    /// Mark all widgets as needing layout and paint (e.g. after a theme change).
2327    /// Also clears per-widget paint caches since the visual output is stale.
2328    pub fn mark_all_dirty(&mut self) {
2329        for (_, node) in self.nodes.iter_mut() {
2330            node.dirty.needs_layout = true;
2331            node.dirty.needs_paint = true;
2332            node.cached_paint = None;
2333            node.cached_post_paint = None;
2334        }
2335    }
2336
2337    /// Mark every active node for repaint **without** touching layout, rebuild,
2338    /// or the per-widget paint caches. Used for a global visual change that
2339    /// leaves geometry untouched — the window's active-state flip (caret
2340    /// hiding, selection desaturation, `DimWhenInactive`). Lighter than
2341    /// [`Self::mark_all_dirty`]: the paint walker re-runs `paint()` for any
2342    /// node whose `needs_paint` is set and overwrites its cache, so there is no
2343    /// need to clear `cached_paint`; and skipping `needs_layout` avoids a
2344    /// pointless relayout pass. Dormant nodes are skipped — they don't paint,
2345    /// and they're re-marked on reactivation.
2346    pub fn mark_all_needs_paint_only(&mut self) {
2347        for (_, node) in self.nodes.iter_mut() {
2348            if node.activation == ActivationState::Active {
2349                node.dirty.needs_paint = true;
2350            }
2351        }
2352    }
2353
2354    /// Resolve the effective theme for a widget by walking ancestors and
2355    /// applying any theme overrides encountered along the way.
2356    /// The base theme is the tree-level default.
2357    pub fn resolve_theme<'a>(
2358        &self,
2359        id: WidgetId,
2360        base: &'a crate::styles::Theme,
2361    ) -> std::borrow::Cow<'a, crate::styles::Theme> {
2362        // Fast path: if no widget has a theme override, borrow the base
2363        // theme — no clone. This is the per-widget hot path during layout
2364        // and paint, so avoiding `Theme::clone()` (which clones the
2365        // typography token strings and bumps ~42 style-slot `Rc`s) here
2366        // saves that work on every node, every pass, in the common case.
2367        if self.theme_override_count == 0 {
2368            return std::borrow::Cow::Borrowed(base);
2369        }
2370
2371        // Collect ancestor chain from root to widget
2372        let mut chain = vec![id];
2373        let mut current = self.parent(id);
2374        while let Some(pid) = current {
2375            chain.push(pid);
2376            current = self.parent(pid);
2377        }
2378        chain.reverse(); // root first
2379
2380        let mut theme = base.clone();
2381        for nid in chain {
2382            if let Some(node) = self.nodes.get(nid)
2383                && let Some(ovr) = &node.theme_override
2384            {
2385                (ovr.func)(&mut theme);
2386            }
2387        }
2388        std::borrow::Cow::Owned(theme)
2389    }
2390}
2391
2392impl Default for WidgetArena {
2393    fn default() -> Self {
2394        Self::new()
2395    }
2396}
2397
2398#[cfg(test)]
2399mod tests {
2400    use super::*;
2401    use crate::test_widgets::FillWidget;
2402    use teksilo_canvas::SizeProposal;
2403
2404    fn key(w: Option<f32>, h: Option<f32>) -> ProposalKey {
2405        ProposalKey::from_proposal(SizeProposal {
2406            width: w,
2407            height: h,
2408        })
2409    }
2410
2411    #[test]
2412    fn activate_skips_a_child_gated_off_by_visible_state() {
2413        // Reactivating a subtree must not wake a child that its own widget
2414        // has gated off via `visible_when(false)` — e.g. a ComboBox's closed
2415        // dropdown panel, or a collapsed overlay. Regression for ghost
2416        // dropdown rows after a `visible_when` collapse→reappear cycle.
2417        let mut arena = WidgetArena::new();
2418        let parent = arena.insert(Box::new(FillWidget::new()));
2419        let visible_child = arena.insert_child(parent, Box::new(FillWidget::new()));
2420        let gated_child = arena.insert_child(parent, Box::new(FillWidget::new()));
2421        // The gated child is hidden by its own visibility gate.
2422        if let Some(node) = arena.get_mut(gated_child) {
2423            node.visible_state = Some(Prop::Static(false));
2424        }
2425
2426        arena.set_dormant(parent);
2427        assert!(!arena.is_active(gated_child));
2428
2429        arena.activate(parent);
2430        assert!(arena.is_active(parent), "the targeted node activates");
2431        assert!(
2432            arena.is_active(visible_child),
2433            "an ungated child activates with its parent"
2434        );
2435        assert!(
2436            !arena.is_active(gated_child),
2437            "a visible_when(false) child stays dormant when its parent reactivates"
2438        );
2439    }
2440
2441    #[test]
2442    fn activate_skips_a_child_parked_directly_by_set_dormant() {
2443        // The ungated twin of the test above, and the one that was missing.
2444        //
2445        // Widgets that pre-build hidden content register it as a child with
2446        // `ctx.add(..)` + `ctx.set_dormant(..)` and show it through an overlay:
2447        // `SplitButton` and `MenuBar` menus, `Popover`, `Snackbar`, the date
2448        // editors' calendars. Such a child carries no `visible_state`, so the
2449        // gate check alone let an ancestor's dormancy cycle wake it — and it
2450        // then rendered inline, with no overlay behind it, because the overlay
2451        // presentation never ran. Seen as export menu-item labels floating
2452        // under the title bar after leaving a mode that parked the shell.
2453        let mut arena = WidgetArena::new();
2454        let parent = arena.insert(Box::new(FillWidget::new()));
2455        let visible_child = arena.insert_child(parent, Box::new(FillWidget::new()));
2456        let menu = arena.insert_child(parent, Box::new(FillWidget::new()));
2457        let menu_row = arena.insert_child(menu, Box::new(FillWidget::new()));
2458
2459        // The widget parks its own closed menu — no gate involved.
2460        arena.set_dormant(menu);
2461        assert!(!arena.is_active(menu));
2462
2463        // An ancestor now goes dormant and comes back.
2464        arena.set_dormant(parent);
2465        arena.activate(parent);
2466
2467        assert!(arena.is_active(parent), "the targeted node activates");
2468        assert!(
2469            arena.is_active(visible_child),
2470            "an ordinary child activates with its parent"
2471        );
2472        assert!(
2473            !arena.is_active(menu),
2474            "the ancestor's dormancy cycle woke a menu that was closed before it \
2475             started — its content is now on screen with no overlay behind it"
2476        );
2477        assert!(
2478            !arena.is_active(menu_row),
2479            "the closed menu's own subtree woke with it"
2480        );
2481
2482        // …and opening it still works: activating by id is how the overlay
2483        // shows this content, so it must clear the self-parked mark.
2484        arena.activate(menu);
2485        assert!(arena.is_active(menu), "the menu can still be opened");
2486        assert!(arena.is_active(menu_row), "…along with its rows");
2487    }
2488
2489    #[test]
2490    fn a_reopened_menu_parks_again_and_survives_the_next_cycle() {
2491        // The flag must be re-armed by every `set_dormant`, not just the first:
2492        // open the menu, close it, then put an ancestor through another
2493        // dormancy cycle. Without re-arming, the second cycle leaks.
2494        let mut arena = WidgetArena::new();
2495        let parent = arena.insert(Box::new(FillWidget::new()));
2496        let menu = arena.insert_child(parent, Box::new(FillWidget::new()));
2497
2498        arena.set_dormant(menu);
2499        arena.activate(menu); // opened
2500        arena.set_dormant(menu); // dismissed
2501
2502        arena.set_dormant(parent);
2503        arena.activate(parent);
2504        assert!(
2505            !arena.is_active(menu),
2506            "a menu that was opened once no longer stays closed across a \
2507             dormancy cycle"
2508        );
2509    }
2510
2511    #[test]
2512    fn an_ancestor_cycle_does_not_strand_an_open_menu() {
2513        // The mirror risk of the fix: `park` marks only the node it is given,
2514        // so a menu that is *open* when an ancestor parks must come back with
2515        // that ancestor rather than being stranded closed.
2516        let mut arena = WidgetArena::new();
2517        let parent = arena.insert(Box::new(FillWidget::new()));
2518        let menu = arena.insert_child(parent, Box::new(FillWidget::new()));
2519
2520        arena.set_dormant(menu);
2521        arena.activate(menu); // open when the ancestor parks
2522
2523        arena.set_dormant(parent);
2524        arena.activate(parent);
2525        assert!(
2526            arena.is_active(menu),
2527            "an open menu was stranded closed by its ancestor's dormancy cycle"
2528        );
2529    }
2530
2531    #[test]
2532    fn proposal_key_distinguishes_none_from_zero() {
2533        // `None` (ask for ideal) must not collide with `Some(0.0)` (give zero).
2534        assert_ne!(key(None, None), key(Some(0.0), None));
2535        assert_ne!(key(Some(0.0), None), key(None, Some(0.0)));
2536    }
2537
2538    #[test]
2539    fn proposal_key_canonicalizes_signed_zero_and_nan() {
2540        assert_eq!(key(Some(-0.0), None), key(Some(0.0), None));
2541        assert_eq!(key(Some(f32::NAN), None), key(Some(f32::NAN), None));
2542    }
2543
2544    #[test]
2545    fn proposal_key_separates_distinct_values_and_axes() {
2546        assert_ne!(key(Some(1.0), None), key(Some(2.0), None));
2547        // Same scalar on different axes must not collide.
2548        assert_ne!(key(Some(10.0), None), key(None, Some(10.0)));
2549    }
2550
2551    #[test]
2552    fn insert_and_retrieve() {
2553        let mut arena = WidgetArena::new();
2554        let id = arena.insert(Box::new(FillWidget::new()));
2555        assert!(arena.get(id).is_some());
2556        assert_eq!(arena.len(), 1);
2557    }
2558
2559    #[test]
2560    fn new_widget_is_dirty() {
2561        let mut arena = WidgetArena::new();
2562        let id = arena.insert(Box::new(FillWidget::new()));
2563        let node = arena.get(id).unwrap();
2564        assert!(node.dirty.needs_layout);
2565        assert!(node.dirty.needs_paint);
2566    }
2567
2568    #[test]
2569    fn roots_returns_parentless_widgets() {
2570        let mut arena = WidgetArena::new();
2571        let root = arena.insert(Box::new(FillWidget::new()));
2572        let _child = arena.insert_child(root, Box::new(FillWidget::new()));
2573        let roots = arena.roots();
2574        assert_eq!(roots.len(), 1);
2575        assert_eq!(roots[0], root);
2576    }
2577
2578    #[test]
2579    fn content_transform_node_claims_viewport_in_parent_space() {
2580        // A content-transform node (the SceneView pattern) is a fixed
2581        // viewport: its bounds are tested in PARENT space and the transform
2582        // only positions its content, so the whole visible viewport stays
2583        // hittable regardless of the content pan/zoom. Before the fix, the
2584        // bounds were tested in content space, so a content pan shifted the
2585        // hittable region off the viewport.
2586        use teksilo_canvas::{Point, Rect, Transform2D};
2587        let mut arena = WidgetArena::new();
2588        let id = arena.insert(Box::new(FillWidget::new()));
2589        {
2590            let node = arena.get_mut(id).unwrap();
2591            node.bounds = Rect::new(0.0, 0.0, 200.0, 100.0);
2592            node.clips_children = true;
2593            node.content_transform = true;
2594            // Content panned by (50, 30).
2595            node.transform_prop = Some(Prop::Static(Transform2D::translate(50.0, 30.0)));
2596        }
2597        // Points across the whole parent-space viewport hit, regardless of the
2598        // pan (these all missed before the fix).
2599        assert_eq!(arena.hit_test_at(Point::new(10.0, 10.0), None), Some(id));
2600        assert_eq!(arena.hit_test_at(Point::new(100.0, 50.0), None), Some(id));
2601        assert_eq!(arena.hit_test_at(Point::new(199.0, 99.0), None), Some(id));
2602        // Outside the viewport: miss.
2603        assert_eq!(arena.hit_test_at(Point::new(250.0, 50.0), None), None);
2604    }
2605
2606    #[test]
2607    fn self_transform_node_tests_bounds_in_local_space() {
2608        // Regression guard: a *self* transform wrapper (Scale / Rotate, NOT a
2609        // content transform) keeps the original semantics — its own bounds
2610        // move with the transform, so the point is inverse-transformed before
2611        // the bounds test. `clips_children` is irrelevant here (Scale clips
2612        // too); only `content_transform` selects the viewport path.
2613        use teksilo_canvas::{Point, Rect, Transform2D};
2614        let mut arena = WidgetArena::new();
2615        let id = arena.insert(Box::new(FillWidget::new()));
2616        {
2617            let node = arena.get_mut(id).unwrap();
2618            node.bounds = Rect::new(0.0, 0.0, 100.0, 100.0);
2619            node.clips_children = true; // Scale clips, but is NOT content_transform.
2620            node.content_transform = false;
2621            // Visually scaled to 50x50 around the origin.
2622            node.transform_prop = Some(Prop::Static(Transform2D::scale(0.5, 0.5)));
2623        }
2624        // Inside the scaled-down 50x50 visual → hit.
2625        assert_eq!(arena.hit_test_at(Point::new(25.0, 25.0), None), Some(id));
2626        // Past the scaled-down visual (but inside the un-scaled 100x100 bounds
2627        // in parent space) → miss, because the bounds test is in local space.
2628        assert_eq!(arena.hit_test_at(Point::new(75.0, 75.0), None), None);
2629    }
2630
2631    #[test]
2632    fn nested_content_transform_nodes_each_claim_their_viewport() {
2633        // A content-transform node embedded inside another (the nested-
2634        // SceneView case): each level tests its own viewport bounds in its
2635        // parent's space, and only the transform is applied when descending.
2636        // The inner viewport stays hittable regardless of either node's pan.
2637        use teksilo_canvas::{Point, Rect, Transform2D};
2638        let mut arena = WidgetArena::new();
2639        let outer = arena.insert(Box::new(FillWidget::new()));
2640        let inner = arena.insert_child(outer, Box::new(FillWidget::new()));
2641        {
2642            let n = arena.get_mut(outer).unwrap();
2643            n.bounds = Rect::new(0.0, 0.0, 200.0, 200.0);
2644            n.clips_children = true;
2645            n.content_transform = true;
2646            n.transform_prop = Some(Prop::Static(Transform2D::translate(20.0, 20.0)));
2647        }
2648        {
2649            let n = arena.get_mut(inner).unwrap();
2650            // Inner viewport expressed in the OUTER's content space.
2651            n.bounds = Rect::new(10.0, 10.0, 50.0, 50.0);
2652            n.clips_children = true;
2653            n.content_transform = true;
2654            n.transform_prop = Some(Prop::Static(Transform2D::translate(5.0, 5.0)));
2655        }
2656        // Screen (40,40) → outer-content (20,20) ∈ inner viewport → reaches inner.
2657        assert_eq!(arena.hit_test_at(Point::new(40.0, 40.0), None), Some(inner));
2658        // Screen (5,5) → outer-content (-15,-15) ∉ inner viewport → reaches outer.
2659        assert_eq!(arena.hit_test_at(Point::new(5.0, 5.0), None), Some(outer));
2660    }
2661
2662    /// Accepts only the right half of its bounds via `hit_shape`; the left
2663    /// half is rejected so a click there falls through to a sibling beneath.
2664    #[derive(Debug)]
2665    struct RightHalfWidget;
2666
2667    impl crate::widget::Widget for RightHalfWidget {
2668        fn layout_response(
2669            &self,
2670            proposal: teksilo_canvas::SizeProposal,
2671            _ctx: &crate::widget::LayoutContext,
2672        ) -> crate::widget::LayoutResponse {
2673            proposal.resolve(0.0, 0.0).into()
2674        }
2675
2676        fn hit_shape(
2677            &self,
2678            local_point: teksilo_canvas::Point,
2679            bounds: teksilo_canvas::Rect,
2680        ) -> bool {
2681            local_point.x >= bounds.x + bounds.width / 2.0
2682        }
2683    }
2684
2685    #[test]
2686    fn hit_shape_rejection_falls_through_to_sibling_underneath() {
2687        // Two overlapping siblings under a common parent. `lower` is a
2688        // full-rect FillWidget; `upper` (inserted later → painted on top,
2689        // hit-tested first) rejects its left half via `hit_shape`. A click in
2690        // the rejected left half must reach `lower` underneath; a click in the
2691        // accepted right half must hit `upper`.
2692        use teksilo_canvas::{Point, Rect};
2693        let mut arena = WidgetArena::new();
2694        let parent = arena.insert(Box::new(FillWidget::new()));
2695        let lower = arena.insert_child(parent, Box::new(FillWidget::new()));
2696        let upper = arena.insert_child(parent, Box::new(RightHalfWidget));
2697        for id in [parent, lower, upper] {
2698            arena.get_mut(id).unwrap().bounds = Rect::new(0.0, 0.0, 100.0, 100.0);
2699        }
2700        // Right half: upper accepts → hit upper.
2701        assert_eq!(arena.hit_test_at(Point::new(75.0, 50.0), None), Some(upper));
2702        // Left half: upper rejects via hit_shape → falls through to lower.
2703        assert_eq!(arena.hit_test_at(Point::new(25.0, 50.0), None), Some(lower));
2704    }
2705}