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