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