Skip to main content

teksilo_core/widget_tree/
layout_impl.rs

1// SPDX-License-Identifier: MPL-2.0
2// SPDX-FileCopyrightText: 2026 FernTech
3
4use super::*;
5
6impl WidgetTree {
7    /// Process dirty state bindings: mark bound widgets for repaint, relayout,
8    /// or rebuild. Called automatically at the start of layout().
9    pub(super) fn process_state_changes(&mut self, ops: &mut dyn crate::window::WindowOps) {
10        // Refresh the node-resident `effective_enabled_signal`s FIRST, so a
11        // widget bound to one is dirty-marked in time for the binding flush
12        // immediately below to drain it in this same pass, rather than a frame
13        // late. This is also where a signal seeded during `build()` — when the
14        // widget's parent was not yet wired, so the seed could only see its own
15        // `enabled` prop — is corrected against the now-complete tree.
16        self.flush_effective_enabled_signals();
17
18        // One unified flush: both visual buckets and the a11y flag
19        // are drained from the same walk, so a signal bound at both
20        // a visual level and `AccessibilityOnly` (e.g. a Button's
21        // `label` re-registers the same Signal at RepaintOnly
22        // *and* AccessibilityOnly) flips both. Two separate flushes
23        // would each advance this registry's last-seen generation for
24        // that source, so the second would find nothing to report.
25        let (dirty_widgets, a11y_binding_dirty) = self.binding_registry.flush_all_dirty();
26        for (id, level) in &dirty_widgets {
27            match level {
28                crate::binding::BindingLevel::RepaintOnly => {
29                    self.arena.mark_needs_paint(*id);
30                }
31                crate::binding::BindingLevel::SubtreeRepaint => {
32                    // Used by `enabled_when` so the leaves in the
33                    // disabled subtree re-resolve their role colors
34                    // via the paint walker's `effective_enabled`.
35                    // No layout work — geometry is unchanged.
36                    self.arena.mark_subtree_needs_paint(*id);
37                }
38                crate::binding::BindingLevel::Relayout => {
39                    self.arena.mark_needs_layout(*id);
40                    self.arena.mark_ancestors_need_layout(*id);
41                }
42                crate::binding::BindingLevel::Rebuild => {
43                    self.arena.mark_needs_rebuild(*id);
44                    self.arena.mark_ancestors_need_layout(*id);
45                }
46                crate::binding::BindingLevel::AccessibilityOnly => {
47                    // Drained into the boolean below — never appears in
48                    // the visual map, but kept in the match so a future
49                    // variant addition is a compile-time reminder.
50                }
51            }
52        }
53
54        // Orthogonal to the visual dirty pass: if any signal bound at
55        // `BindingLevel::AccessibilityOnly` fired, flip the tree-wide
56        // `a11y_dirty` flag so the next `sync_accessibility` rebuilds
57        // the AccessKit tree. Decoupled from layout / paint so a text
58        // edit that changes no visual geometry still reaches screen
59        // readers within one frame.
60        if a11y_binding_dirty {
61            self.a11y_dirty = true;
62        }
63
64        // Rebuild data-driven widgets whose data model changed.
65        self.process_pending_rebuilds(&mut *ops);
66
67        let mut to_dormant = Vec::new();
68        let mut to_activate = Vec::new();
69        for (id, is_active, should_be_visible) in self.arena.visibility_checks_iter() {
70            if is_active && !should_be_visible {
71                to_dormant.push(id);
72            } else if !is_active && should_be_visible {
73                // Only wake a `visible_when(true)` node whose parent is active.
74                // A gated node inside a dormant ancestor (e.g. a row in a
75                // closed popover / overflow menu) must NOT escape that
76                // ancestor's dormancy and render on its own. When the ancestor
77                // is later activated, `arena.activate` wakes this node via the
78                // cascade (its gate is true). The dormancy invariant — an
79                // active node has an active parent — makes the immediate-parent
80                // check sufficient.
81                let parent_active = self
82                    .arena
83                    .parent(id)
84                    .map(|p| self.arena.is_active(p))
85                    .unwrap_or(true);
86                if parent_active {
87                    to_activate.push(id);
88                }
89            }
90        }
91        // The accessibility walk skips dormant nodes, so any
92        // active↔dormant transition changes the AccessKit tree shape
93        // and must dirty the cached snapshot. Other Relayout-causing
94        // signal flips (a Switcher visibility binding that doesn't
95        // straddle activation, an opacity change) do not — the
96        // unconditional `a11y_dirty = true` was removed from `layout()`
97        // and is now set only by events that actually change the AT tree.
98        //
99        // A *resize* is one of them: since a label carries its text one
100        // run per visual line, re-wrapping it at a new width produces a
101        // different set of runs, not the same set somewhere else. A pure
102        // translation is absorbed by `sync_accessibility` instead, which
103        // re-places the cached nodes without walking.
104        if !to_dormant.is_empty() || !to_activate.is_empty() {
105            self.a11y_dirty = true;
106        }
107        for id in to_dormant {
108            // Through the tree-level door, so a pointer working inside a
109            // `visible_when` branch that just flipped false is told its
110            // interaction is over rather than left holding a widget the
111            // dispatcher will no longer reach.
112            self.park_subtree_with_ops(id, &mut *ops);
113        }
114        for id in to_activate {
115            self.arena.activate(id);
116        }
117        // Fire activation_signal observers (e.g. a WebView's set_visible
118        // bridge) after the whole visibility pass has committed — not from
119        // inside the set_dormant/activate recursion above.
120        self.flush_activation_signals();
121
122        // Reclaim binding groups nothing points at any more. Deliberately
123        // last: `unregister_for_widget` leaves emptied groups in place so
124        // that a rebuild — which is unregister-then-re-register — keeps
125        // the group's `last_seen` ledger and cannot swallow a write its
126        // own `build()` made before re-binding. By here every rebuild in
127        // this pass has re-registered, so anything still empty belongs to
128        // a widget that is genuinely gone.
129        self.binding_registry.reclaim_empty_groups();
130    }
131
132    /// Dismiss any active overlay whose content widget is no longer
133    /// alive in the arena. An overlay's owner can be torn down
134    /// out-of-band: a data-driven rebuild destroys the widget that
135    /// showed it (clicking "mark all read" inside a notification popover
136    /// rebuilds the bell that owns the overlay; closing a document tears
137    /// down a still-open inline popover). The content then disappears
138    /// visually, but the overlay ENTRY survives in the manager and keeps
139    /// intercepting clicks (the click-outside scrim) until the user
140    /// clicks elsewhere. This GC removes such orphans immediately (no
141    /// fade — the content is already gone). A normally-open overlay's
142    /// content stays active (gated `true`), so it is never touched.
143    pub(super) fn gc_orphaned_overlays(&mut self) {
144        let orphaned: Vec<crate::overlay::OverlayId> = self
145            .overlay_manager
146            .active_ids()
147            .into_iter()
148            .filter(|&id| {
149                self.overlay_manager
150                    .overlay(id)
151                    .map(|o| !self.arena.is_active(o.content_id))
152                    .unwrap_or(false)
153            })
154            .collect();
155        if orphaned.is_empty() {
156            return;
157        }
158        for id in orphaned {
159            // The content widget is already destroyed, so this is bookkeeping
160            // rather than anything the user did.
161            self.overlay_manager
162                .dismiss_immediate(id, crate::overlay::DismissReason::Programmatic);
163        }
164        // This is one of the two dismissal paths that does NOT park its
165        // content — the content is already gone — so it never reaches
166        // `dormant_dismissed_content`, where the dismissal callbacks are
167        // normally run. Draining here rather than leaving it to a later pass
168        // is what keeps an anchor's "is my overlay up?" state honest: the
169        // touch-selection handles re-raise on the next hold only because this
170        // tells the field its previous layer went away.
171        //
172        // `NoopWindowOps` because a GC runs from the layout pass, outside any
173        // dispatch — the same reason `dismiss_overlay` uses one.
174        let mut noop = crate::window::NoopWindowOps;
175        self.run_pending_dismiss_callbacks(&mut noop);
176    }
177
178    /// Every widget holding live interaction state a park would destroy:
179    /// the focused node, each live pointer's captor, and the source of an
180    /// in-flight drag.
181    ///
182    /// Handed to the layout pass as `LayoutExtras::interaction_anchors` so a
183    /// container deciding what to keep can protect what the user is in the
184    /// middle of. Almost always empty or a single id, so the `Vec` is one
185    /// small allocation per pass on a tree that is being interacted with.
186    fn collect_interaction_anchors(&self) -> Vec<WidgetId> {
187        let mut out: Vec<WidgetId> = Vec::new();
188        let push = |id: WidgetId, out: &mut Vec<WidgetId>| {
189            if !out.contains(&id) {
190                out.push(id);
191            }
192        };
193        if let Some(id) = self.focused {
194            push(id, &mut out);
195        }
196        for entry in self.pointers.iter() {
197            if let Some(id) = entry.captured_by {
198                push(id, &mut out);
199            }
200        }
201        if let Some(id) = self.active_drag.as_ref().and_then(|d| d.source_widget) {
202            push(id, &mut out);
203        }
204        out
205    }
206
207    /// Re-ask every `culls_children` parent whose decision the user's own
208    /// position is an input to, when that position has changed since the last
209    /// walk.
210    ///
211    /// A culling parent decides which of its children exist, and the contract
212    /// says it must keep the one the user is in the middle of — it reads the
213    /// anchors through `LayoutContext::for_each_interaction_ancestor`. But it
214    /// is asked *during layout*, and the idle early-return below skips the
215    /// walk whenever nothing needs laying out. Focus moving from one card to
216    /// another moves nothing and resizes nothing, so without this the parent
217    /// keeps answering with the anchor set from whenever the camera last
218    /// moved: it would go on pinning the card the user has left, and — worse
219    /// for anything that publishes a narrower set than it keeps alive, as
220    /// `SceneView` does — would not pin the card the user has just arrived in.
221    ///
222    /// Scoped so that a tree with no culling container pays nothing but a
223    /// parent-chain walk per changed anchor, and forces no pass at all. Anchors
224    /// are almost always empty or a single id.
225    fn invalidate_culls_for_moved_interaction(&mut self) {
226        let anchors = self.collect_interaction_anchors();
227        if anchors == self.last_interaction_anchors {
228            return;
229        }
230        // Both directions: an anchor that arrived needs its ancestors to start
231        // pinning it, one that left needs them to stop.
232        let mut moved: Vec<WidgetId> = anchors
233            .iter()
234            .filter(|id| !self.last_interaction_anchors.contains(id))
235            .copied()
236            .collect();
237        moved.extend(
238            self.last_interaction_anchors
239                .iter()
240                .filter(|id| !anchors.contains(id))
241                .copied(),
242        );
243        self.last_interaction_anchors = anchors;
244        for id in moved {
245            // From the parent up: the anchor itself culling its own children
246            // is not affected by being an anchor.
247            let mut current = self.arena.parent(id);
248            while let Some(curr) = current {
249                if self
250                    .arena
251                    .get(curr)
252                    .is_some_and(|node| node.widget.culls_children())
253                {
254                    self.arena.mark_needs_layout(curr);
255                    // A culling parent may publish a narrower accessibility
256                    // set than it keeps alive, and pinning an anchor into that
257                    // set widens it without parking or waking anything — so
258                    // the park/wake invalidation below cannot see it. Without
259                    // this, `sync_accessibility` serves a cached tree that
260                    // omits the newly-pinned node and names an ancestor as the
261                    // focus. `WidgetTree::focus` happens to set the same flag
262                    // for its own reasons, but whichever sync runs first
263                    // consumes it, and that sync precedes this pass.
264                    self.a11y_dirty = true;
265                }
266                current = self.arena.parent(curr);
267            }
268        }
269    }
270
271    /// Drain any widgets flagged `needs_rebuild` that are currently
272    /// active + have built children. Called from
273    /// `process_state_changes` after dirty bindings have been
274    /// flushed, and again after overlay / tooltip activation so that
275    /// widgets transitioning from dormant → active in the same
276    /// layout pass get rebuilt *this* frame rather than the next.
277    pub(super) fn process_pending_rebuilds(&mut self, ops: &mut dyn crate::window::WindowOps) {
278        // Defer *selected* rebuilds while a pointer capture is held:
279        // from `PointerDown` (which stores the press position in the
280        // captured widget's arena) until `PointerUp`. Rebuilding the
281        // captured widget, or any of its ancestors, would destroy that
282        // arena and lose the press state — the recognizer would never
283        // fire.
284        //
285        // The window really does last the whole gesture, NOT just up to
286        // `DragStarted`: a gesture drag auto-captures on `DragStarted`
287        // (`gesture_dispatch_impl`) and holds until `DragEnded`, and the
288        // only thing that lifts this filter is `active_drag`, which is
289        // the drag-and-DROP session set by `start_drag` — never a
290        // scrollbar thumb. So a widget holding a live gesture must not
291        // be a descendant of anything that rebuilds on data or scroll
292        // changes, or that rebuild is silently dropped until release.
293        //
294        // Rebuilds targeting widgets *outside* the captured widget's
295        // ancestor chain are safe: destroying sibling subtrees leaves
296        // the captured widget intact, so ongoing drags keep routing
297        // correctly. That is exactly why all five virtualized views
298        // (`ListView`, `TreeView`, `TableView`, `TreeTableView`,
299        // `GridView`) hoist their rows into a body pane that is a
300        // *sibling* of their scrollbar rather than realizing rows on
301        // the view root — see `common::thumb_drag_test` in
302        // `teksilo-widgets`, which asserts it for each of them.
303        //
304        // Once `active_drag` is set, the framework routes PointerMove /
305        // PointerUp via `handle_drag_move` / `handle_drag_drop` keyed
306        // on the `DragSession`, not on the captured widget's arena —
307        // so a mid-drag rebuild is safe regardless of topology. Post-
308        // rebuild, `revalidate_interaction_state` clears a now-stale
309        // `pointer_captured_by`; subsequent events hit-test normally.
310        let to_rebuild_all = self.arena.collect_needs_rebuild();
311        if to_rebuild_all.is_empty() {
312            self.revalidate_interaction_state(&mut *ops);
313            return;
314        }
315        let captured_ancestors: Option<Vec<WidgetId>> = if self.active_drag.is_none() {
316            // Every captured widget, not just the primary pointer's: two
317            // contacts can hold two captures, and rebuilding either one's
318            // ancestors mid-gesture is what this guard exists to prevent.
319            let captors: Vec<WidgetId> = self
320                .pointers
321                .iter()
322                .filter_map(|entry| entry.captured_by)
323                .collect();
324            (!captors.is_empty()).then(|| {
325                let mut ids = Vec::new();
326                for cap in captors {
327                    let mut cur = Some(cap);
328                    while let Some(id) = cur {
329                        if !ids.contains(&id) {
330                            ids.push(id);
331                        }
332                        cur = self.arena.parent(id);
333                    }
334                }
335                ids
336            })
337        } else {
338            None
339        };
340        let to_rebuild: Vec<WidgetId> = match &captured_ancestors {
341            Some(chain) => to_rebuild_all
342                .into_iter()
343                .filter(|id| !chain.contains(id))
344                .collect(),
345            None => to_rebuild_all,
346        };
347        if to_rebuild.is_empty() {
348            self.revalidate_interaction_state(&mut *ops);
349            return;
350        }
351        // Does focus live inside a subtree we are about to rebuild? Its children
352        // are about to be destroyed and re-allocated with fresh ids, taking the
353        // focused node with them — and once that has happened there is no way
354        // back from the dead id to the subtree it belonged to. Work it out now.
355        let focus_owner: Option<WidgetId> = self.focused.and_then(|focused| {
356            let depth = |id: WidgetId| -> usize {
357                let mut d = 0;
358                let mut cur = id;
359                while let Some(parent) = self.arena.parent(cur) {
360                    d += 1;
361                    cur = parent;
362                }
363                d
364            };
365            // Every root containing `focused` sits on its ancestor chain, so the
366            // candidates are totally ordered by depth. Take the OUTERMOST: it is
367            // the only one sure to survive, since a rebuild destroys its children
368            // — an inner rebuild root nested inside an outer one is torn down by
369            // the outer's rebuild, and its id would be dead by restore time.
370            to_rebuild
371                .iter()
372                .copied()
373                .filter(|&root| self.is_descendant_of(focused, root))
374                .min_by_key(|&root| depth(root))
375        });
376
377        // The focused node's ancestors up to that root, innermost first. The
378        // restore below goes into the innermost one the rebuild left alive.
379        let focus_ancestors: Vec<WidgetId> = match (self.focused, focus_owner) {
380            (Some(focused), Some(owner)) => {
381                let mut chain = Vec::new();
382                let mut cur = self.arena.parent(focused);
383                while let Some(id) = cur {
384                    chain.push(id);
385                    if id == owner {
386                        break;
387                    }
388                    cur = self.arena.parent(id);
389                }
390                chain
391            }
392            _ => Vec::new(),
393        };
394
395        for widget_id in to_rebuild {
396            self.rebuild_single_widget(widget_id);
397        }
398        // A rebuild destroys old child subtrees and allocates fresh
399        // WidgetIds, so the AccessKit tree shape changed — dirty the cached
400        // snapshot so the next `sync_accessibility` re-walks. This is the one
401        // place every `BindingLevel::Rebuild` consumer converges (data-view
402        // model updates via the binding registry AND `with_widget_mut(Rebuild)`
403        // via `apply_tree_mutations`, both draining the same `needs_rebuild`
404        // arena flag) — without this, an ordinary `ListModel::push()` leaves
405        // screen readers on a stale tree indefinitely.
406        self.a11y_dirty = true;
407        // Rebuild destroys old child subtrees and allocates fresh WidgetIds;
408        // drop any focus/hover state whose target is no longer valid so we
409        // don't dispatch to dead widgets on the next event.
410        self.revalidate_interaction_state(&mut *ops);
411        // ...but "no longer valid" must not mean "gone". If focus lived in the
412        // subtree we just rebuilt, the drop above kicked the user clean out of
413        // the widget they were in: a popover that re-scans its content when it
414        // opens throws away the row the popover itself had just focused, and the
415        // menu comes up with nothing focused — no arrow keys, no Enter. Put focus
416        // back inside that subtree, at the end of the layout pass (the fresh
417        // children have no bounds yet, and the focus-driven scroll-into-view
418        // needs them). A rebuild that never held focus, or one whose focused node
419        // survived it (the rebuild root itself is not destroyed), records nothing.
420        //
421        // Into the innermost ancestor that survived, not the root: a reconciling
422        // rebuild re-attaches the children it keeps, so the toast, tab or group
423        // the user was in is usually still there, and the root's first focusable
424        // descendant is the first of them, not theirs.
425        if self.focused.is_none()
426            && let Some(owner) = focus_owner
427        {
428            self.pending_focus_restore = focus_ancestors
429                .into_iter()
430                .filter(|&id| {
431                    self.arena.get(id).is_some()
432                        && (id == owner || self.is_descendant_of(id, owner))
433                })
434                .collect();
435        }
436        // A rebuild's `build()` may arm new animations (looping or
437        // one-shot) by calling `signal.animate_to(...)` /
438        // `animate_looping(...)` — these set `pending` on the signal
439        // but don't enter the scheduler until `process_pending_animations`
440        // runs again. The early-frame `process_pending_animations`
441        // (`layout_impl::layout_with_ops`) already ran *before* this
442        // rebuild, so without this second drain the animation would
443        // wait for the next frame; if the rebuild also cancelled
444        // existing scheduler entries (`cancel_by_widget` is called by
445        // `rebuild_single_widget`), the scheduler ends up empty, no
446        // frame deadline is set, and the freshly-armed animation
447        // *never* gets picked up — the user sees animations freeze
448        // after any state-driven rebuild that re-arms them
449        // (e.g. SceneView's drag-end rebuild re-arming PulsingDot
450        // loopers via `register_bindings`).
451        self.process_pending_animations();
452    }
453
454    /// Run the layout pass with the given size proposal, using
455    /// [`NoopWindowOps`](crate::window::NoopWindowOps). Handlers
456    /// triggered from drag_tick / tooltip activation / etc cannot
457    /// call `ctx.open_window(...)` from this path.
458    ///
459    /// `teksilo-app` calls [`layout_with_ops`](Self::layout_with_ops)
460    /// with a real sink so those handlers can open windows.
461    pub fn layout(&mut self, proposal: SizeProposal) {
462        let mut noop = crate::window::NoopWindowOps;
463        self.layout_with_ops(proposal, &mut noop);
464    }
465
466    /// Measure the intrinsic size of the primary (non-overlay) content root(s)
467    /// at `proposal` — e.g. `{ width: Some(w), height: None }` for the natural
468    /// height at a fixed width. Mirrors the overlay intrinsic pass below: it
469    /// calls the root's `layout_response` *directly* — NOT the
470    /// activation-ignoring `WidgetArena::measure_intrinsic` — so a
471    /// `visible_when(false)` / parked-`Switcher` descendant is excluded exactly
472    /// as the real layout excludes it. A size-to-content window is therefore
473    /// sized to what is actually shown. Computes sizes only (never writes
474    /// bounds), so it is safe to call right after a layout pass.
475    ///
476    /// Drives size-to-content windows (see
477    /// [`WindowConfig::size_to_content`](crate::window::WindowConfig::size_to_content)):
478    /// the native-window path has no in-tree overlay to size to content, so
479    /// `teksilo-app` measures the root here and resizes the OS window to fit.
480    /// Returns `None` if there is no active primary root; with more than one
481    /// active primary root the per-axis maximum is returned (size-to-content is
482    /// intended for single-primary-root windows).
483    pub fn measure_root_intrinsic(&self, proposal: SizeProposal) -> Option<teksilo_canvas::Size> {
484        let overlay_content_ids = self.overlay_manager.active_content_ids();
485        let base_theme = self.effective_theme.clone();
486        let mut result: Option<teksilo_canvas::Size> = None;
487        for root_id in self.arena.roots() {
488            if overlay_content_ids.contains(&root_id) || !self.arena.is_active(root_id) {
489                continue;
490            }
491            let resolved_theme = self.arena.resolve_theme(root_id, &base_theme);
492            let extras = crate::widget::LayoutExtras {
493                focused: self.focused,
494                // A measurement, not a pass: nothing is parked off the back of
495                // it, so there is nothing for an anchor to protect.
496                interaction_anchors: &[],
497                shortcut_registry: Some(&self.shortcut_registry),
498                overlay_manager: Some(&self.overlay_manager),
499            };
500            let ctx = LayoutContext {
501                theme: &resolved_theme,
502                layout_direction: self.layout_direction,
503                scale_factor: self.device_scale_factor,
504                text_scale: self.effective_text_scale,
505                text_backend: self.text_backend.as_ref(),
506                arena: Some(&self.arena),
507                extras: Some(extras),
508                stack_main_axis: None,
509            };
510            let Some(node) = self.arena.get(root_id) else {
511                continue;
512            };
513            // Direct `layout_response` (activation-respecting), like the overlay
514            // pass — dormant descendants fall out via `child_size` returning
515            // `None`, so we measure only what is actually shown.
516            let size = node.widget.layout_response(proposal, &ctx).size;
517            result = Some(match result {
518                Some(acc) => teksilo_canvas::Size::new(
519                    acc.width.max(size.width),
520                    acc.height.max(size.height),
521                ),
522                None => size,
523            });
524        }
525        result
526    }
527
528    /// Run the layout pass with the given size proposal, threading
529    /// the app's [`WindowOps`](crate::window::WindowOps) sink
530    /// through to drag_tick / tooltip / delayed-overlay handlers.
531    pub fn layout_with_ops(
532        &mut self,
533        proposal: SizeProposal,
534        ops: &mut dyn crate::window::WindowOps,
535    ) {
536        self.process_pending_animations();
537
538        let now = std::time::Instant::now();
539        // Deadline-driven wake-up: if a widget requested a future
540        // frame via `wake_at_handle()` and that deadline is now past,
541        // arm the frame tick so its effect runs on this layout pass.
542        // Used by the rich text editor's caret blink to avoid
543        // keeping winit in Poll mode.
544        if let Some(deadline) = self.pending_wake_at.get()
545            && deadline <= now
546        {
547            self.pending_wake_at.set(None);
548            self.frame_tick_requested.set(true);
549        }
550        self.advance_frame_tick(now);
551        // Ticked on the same clock the animations were *promoted* against
552        // (`process_pending_animations` immediately above reads it too). While
553        // the tree runs on real time that is `now`; while an automation
554        // operation has time taken over it is `sim_clock`, and ticking at
555        // `Instant::now()` there would hand every animation an elapsed time of
556        // the tree's whole wall-clock age and complete it on its first layout
557        // pass. The operation gives the clock back when it ends, rebasing the
558        // scheduler as it goes, so this reads the wall clock again from the
559        // next frame on — see `WidgetTree::resume_real_time`.
560        let animation_now = self.animation_clock();
561        self.animation_scheduler
562            .tick(animation_now, &self.arena, self.paint_epoch);
563
564        // Fire on_drag_tick on the current drop target, if any. Runs once
565        // per layout pass so widgets can implement per-frame behaviours
566        // (viewport-edge auto-scroll, spring-loaded folders) without
567        // depending on pointer events — crucial when the user holds the
568        // cursor still at the edge or over a collapsed branch.
569        self.process_drag_tick(&mut *ops);
570
571        // What content updated off the UI thread asked for since the last
572        // frame: before the state changes it may cause are processed, and
573        // before the idle early return below, which its marks defeat.
574        self.poll_off_thread();
575
576        self.process_state_changes(&mut *ops);
577        // A drag owns the pointer. `handle_pointer_move` is short-circuited for
578        // the duration, so a dwell armed just before the drag started would sit
579        // frozen at its hover origin and then mature here — popping a tooltip
580        // over the drag. Keep the timers cleared instead of letting them ripen.
581        if self.active_drag.is_some() {
582            self.tooltip_cancel_pending_dwell();
583        }
584        self.process_tooltips_real();
585        self.process_delayed_overlays_real(&mut *ops);
586        self.process_pointer_leave_overlays_real(&mut *ops);
587        self.process_auto_dismiss_overlays_real(&mut *ops);
588        self.process_overlay_fade_dismissals_real(&mut *ops);
589        // The show paths above may arm a fade animation via
590        // `attach_overlay_fade` (plain tooltips, delayed overlays).
591        // That sets `pending` on the opacity signal but does NOT
592        // register the animation with the scheduler — registration
593        // happens via `process_pending_animations`, which already ran
594        // earlier in this layout pass. Without a second drain here,
595        // the fade only enters the scheduler on the *next* layout
596        // pass, and for surfaces with no further wake source (plain
597        // tooltips, no dwell timer) `next_deadline` returns `None`
598        // and the event loop sleeps with the fade stuck at opacity 0
599        // — the tooltip is "shown" but invisible until an unrelated
600        // input event forces another layout pass.
601        self.process_pending_animations();
602        // Overlay / tooltip activation may have flipped widgets from
603        // dormant → active; if any of those had `needs_rebuild`
604        // pending (e.g. a shortcut rebind happened while the tooltip
605        // was hidden), drain them now so the freshly-visible surface
606        // shows fresh content in the *same* layout pass rather than
607        // waiting for another paint-triggering event.
608        self.process_pending_rebuilds(&mut *ops);
609
610        // Now that any data-driven rebuilds have torn down their old
611        // subtrees, drop any overlay whose content was destroyed out-of-
612        // band (e.g. clicking "mark all read" inside a notification
613        // popover rebuilds the bell that owns it). Without this the
614        // overlay lingers as an invisible click-blocker. Runs before the
615        // early-return so it takes effect even on otherwise-idle passes.
616        self.gc_orphaned_overlays();
617
618        self.arena.refresh_roots();
619
620        // Before the idle early-return, because this is precisely the case it
621        // would swallow: the user moved and nothing else did.
622        self.invalidate_culls_for_moved_interaction();
623
624        let proposal_changed = self.last_proposal != proposal;
625        self.last_proposal = proposal;
626
627        if !proposal_changed && !self.arena.any_needs_layout() {
628            return;
629        }
630
631        // Per-pass layout memoization: a widget's `layout_response` is a pure
632        // function of (state, proposal) within a pass, so memoizing across the
633        // main-then-cross queries that height-for-width negotiation issues keeps
634        // the pass O(n). Cleared here — once, dominating both the main-tree and
635        // overlay root recursions below — because geometry may change between
636        // passes. See `WidgetArena::cached_layout_response`.
637        self.arena.clear_layout_cache();
638
639        // `effective_theme` carries the user/OS text-scale multiplier baked into
640        // its typography, so every text widget measures at the scaled size.
641        let base_theme = self.effective_theme.clone();
642
643        let overlay_content_ids = self.overlay_manager.active_content_ids();
644        let roots: Vec<WidgetId> = self.arena.roots();
645        let focused = self.focused;
646        // Everything a park would take away from the user, gathered once so a
647        // culling container can ask
648        // `LayoutContext::for_each_interaction_ancestor` without the tree.
649        // Empty on an idle tree.
650        let interaction_anchors = self.collect_interaction_anchors();
651        // What the `culls_children` parents decided about their children
652        // during this walk — parked and woken alike. Settled after it, because
653        // parking goes through the tree-level door and both halves change the
654        // AccessKit tree.
655        let mut culled = CullTransitions::default();
656        // A widget a culling parent wakes during this walk takes its pending
657        // off-thread relayout in `activate`; see the re-mark after the walk.
658        self.arena.relayout_rewake.clear();
659        for root_id in roots {
660            if overlay_content_ids.contains(&root_id) {
661                continue;
662            }
663            let extras = crate::widget::LayoutExtras {
664                focused,
665                interaction_anchors: &interaction_anchors,
666                shortcut_registry: Some(&self.shortcut_registry),
667                overlay_manager: Some(&self.overlay_manager),
668            };
669            layout_widget_recursive(
670                &mut self.arena,
671                root_id,
672                Rect::from_origin_size(Point::ZERO, proposal.resolve(0.0, 0.0)),
673                proposal,
674                &base_theme,
675                self.layout_direction,
676                self.device_scale_factor,
677                self.effective_text_scale,
678                self.text_backend.as_ref(),
679                Some(extras),
680                &mut culled,
681            );
682        }
683
684        let anchor_bounds = |id: WidgetId| -> Option<Rect> {
685            self.arena.is_active(id).then(|| self.arena.bounds(id))
686        };
687        // The window, less the platform safe area, less whatever is covering
688        // it. Both are `ZERO`/`None` unless something supplied them, so a
689        // desktop frame produces exactly the bare `(width, height)` this used
690        // to pass.
691        let viewport = self.overlay_viewport_for(teksilo_canvas::Size::new(
692            proposal.width.unwrap_or(800.0),
693            proposal.height.unwrap_or(600.0),
694        ));
695        self.overlay_manager
696            .position_overlays(anchor_bounds, viewport, self.layout_direction);
697        for content_id in &overlay_content_ids {
698            if !self.arena.is_active(*content_id) {
699                continue;
700            }
701            let overlay_id = self.overlay_manager.find_by_content(*content_id);
702            let intrinsic = {
703                let resolved_theme = self.arena.resolve_theme(*content_id, &base_theme);
704                let extras = crate::widget::LayoutExtras {
705                    focused: self.focused,
706                    interaction_anchors: &interaction_anchors,
707                    shortcut_registry: Some(&self.shortcut_registry),
708                    overlay_manager: Some(&self.overlay_manager),
709                };
710                let ctx = LayoutContext {
711                    theme: &resolved_theme,
712                    layout_direction: self.layout_direction,
713                    scale_factor: self.device_scale_factor,
714                    text_scale: self.effective_text_scale,
715                    text_backend: self.text_backend.as_ref(),
716                    arena: Some(&self.arena),
717                    extras: Some(extras),
718                    stack_main_axis: None,
719                };
720                let node = self
721                    .arena
722                    .get(*content_id)
723                    .expect("content_id from active arena children");
724                node.widget
725                    .layout_response(
726                        SizeProposal {
727                            width: None,
728                            height: None,
729                        },
730                        &ctx,
731                    )
732                    .size
733            };
734            if let Some(overlay_id) = overlay_id {
735                self.overlay_manager
736                    .set_content_bounds(overlay_id, intrinsic);
737                let anchor_bounds = |id: WidgetId| -> Option<Rect> {
738                    self.arena.is_active(id).then(|| self.arena.bounds(id))
739                };
740                self.overlay_manager.position_overlays(
741                    anchor_bounds,
742                    viewport,
743                    self.layout_direction,
744                );
745            }
746            let overlay_bounds = overlay_id
747                .and_then(|overlay_id| {
748                    self.overlay_manager
749                        .stack
750                        .iter()
751                        .find(|overlay| overlay.id == overlay_id)
752                        .map(|overlay| overlay.bounds)
753                })
754                .unwrap_or(Rect::ZERO);
755            // Use the positioned overlay_bounds for layout, not the intrinsic
756            // size. For `Below` / `BelowPreferred` (and any other placement
757            // that inflates the overlay rect beyond the content's intrinsic
758            // size to match an anchor, e.g. a combo-box dropdown that must be
759            // at least as wide as its trigger), this lets the content widget
760            // actually fill the overlay rather than sitting as a narrow
761            // strip inside it. It carries the placements that *shrink* the
762            // rect just as well — `Above`/`BelowPreferred` to the room they
763            // found, `Centered`/`BottomCenter`/`ViewportCorner` to the usable
764            // area, `FullViewport` to the whole window — so the content is
765            // laid out at the rectangle it was actually given, whichever
766            // placement decided it.
767            let content_proposal = SizeProposal::exact(overlay_bounds.width, overlay_bounds.height);
768            let extras = crate::widget::LayoutExtras {
769                focused: self.focused,
770                interaction_anchors: &interaction_anchors,
771                shortcut_registry: Some(&self.shortcut_registry),
772                overlay_manager: Some(&self.overlay_manager),
773            };
774            layout_widget_recursive(
775                &mut self.arena,
776                *content_id,
777                overlay_bounds,
778                content_proposal,
779                &base_theme,
780                self.layout_direction,
781                self.device_scale_factor,
782                self.effective_text_scale,
783                self.text_backend.as_ref(),
784                Some(extras),
785                &mut culled,
786            );
787        }
788
789        // ── Settle what a culling parent decided ──────────────────────
790        // A widget that culls its children decides during layout which of them
791        // exist, and it can only decide once it knows its own bounds and — for
792        // a scene — the camera it is looking through. Waking has already
793        // happened inline, so a child brought back was laid out this pass;
794        // parking is here because it has to go through the tree-level door,
795        // which tells any pointer working inside the subtree that its
796        // interaction is over rather than leaving it holding a widget the
797        // dispatcher will no longer reach.
798        //
799        // Both halves land here, and neither is the special case. The
800        // accessibility walk skips dormant nodes, so an active↔dormant
801        // transition in EITHER direction changes the AT tree's shape; and
802        // `activation_signal` is the hook a native subview (a `WebView`'s
803        // `set_visible` bridge) hangs its own visibility on, so a queued
804        // `true` that nothing drains is a subview that never comes back. This
805        // is the same rule the `visible_when` sweep at the top of
806        // `process_state_changes` applies to `to_dormant` / `to_activate`;
807        // writing it for parking alone made waking a silent no-op that the
808        // usual probe cannot see, because a card waking *into* the viewport
809        // resizes from `Size::ZERO` and a resize dirties the tree on its own.
810        // A card that wakes and stays zero-sized — which is every card in the
811        // band `A11yOffScreenMode::ViewportPlusN` promises to enumerate — does
812        // not.
813        if !culled.is_empty() {
814            self.a11y_dirty = true;
815            // The composed frame holds what the walk drew, parked children
816            // included, and a render replays it when no active node is marked
817            // for paint. A pass can end that way: a handled scroll marks only
818            // its target, and the parent may park that very target. Dropping
819            // it is what `set_dormant` and `activate` do; the next render
820            // reassembles the frame from the nodes' own caches.
821            self.cached_frame = None;
822            // `revalidate_interaction_state` follows the parks immediately:
823            // focus must never survive a pass pointing at a node this just
824            // parked, because dispatch rejects inactive targets and a
825            // keystroke into the void is worse than a focus loss the user can
826            // see. A culling parent is expected to pin what the user is using
827            // (see `LayoutContext::for_each_interaction_ancestor`), so this is
828            // the backstop, not the plan.
829            let parked = !culled.park.is_empty();
830            for id in std::mem::take(&mut culled.park) {
831                self.park_subtree_with_ops(id, &mut *ops);
832            }
833            self.flush_activation_signals();
834            if parked {
835                self.revalidate_interaction_state(&mut *ops);
836            }
837        }
838
839        // Clear `needs_layout` for every active widget — layout just
840        // ran. `needs_rebuild` is NOT cleared here: `rebuild_single_widget`
841        // clears it for widgets it processes, and widgets whose rebuild
842        // was deferred (captured-pointer window) must keep the flag set
843        // so the next layout pass picks them up. Wiping it here caused
844        // a regression where a scroll-driven ListView rebuild, deferred
845        // during a scrollbar thumb drag, was silently dropped — the
846        // user saw the thumb move but the list view stayed frozen.
847        // Clear `needs_layout` on every active node. Mutation during
848        // iter — pull the snapshot via the reusable scratch.
849        self.arena.fill_active_ids(&mut self.active_ids_scratch);
850        let ids = std::mem::take(&mut self.active_ids_scratch);
851        for &id in &ids {
852            if let Some(node) = self.arena.get_mut(id) {
853                node.dirty.needs_layout = false;
854            }
855        }
856        self.active_ids_scratch = ids;
857        // A widget woken inside the walk with an off-thread relayout pending
858        // was measured before it was woken, so possibly at the size before
859        // the request: lay it out again next pass. One extra pass, only then.
860        for id in std::mem::take(&mut self.arena.relayout_rewake) {
861            if self.arena.is_active(id) {
862                self.arena.mark_needs_layout(id);
863                self.arena.mark_ancestors_need_layout(id);
864            }
865        }
866
867        // Post-layout hover refresh. When a rebuild destroyed the
868        // hovered widget, `revalidate_interaction_state` cleared
869        // `hovered` to `None`. Now that widgets have fresh bounds
870        // from this layout pass, re-hit-test at the cached pointer
871        // position so the next wheel/pointer event routes to the
872        // widget the cursor is actually over. Without this, a
873        // virtualized list that materializes new rows under a
874        // stationary cursor would see the next `Scroll` fall through
875        // to `focused` and bubble to an ancestor scrollable.
876        // Hover recovery is the **hover owner**'s business: re-deriving hover
877        // from the primary would invent one on a touch-only device, where the
878        // primary is a finger and nothing hovers at all.
879        if self.hovered_id().is_none()
880            && let Some(pos) = self.hover_owner_position()
881        {
882            let new_target = self.hit_test(pos);
883            if new_target.is_some() {
884                if let Some(new) = new_target {
885                    // Credited to the hover owner, whose cached position is
886                    // what re-derived the target — no sample raised this.
887                    let enter = WidgetEvent::PointerEnter {
888                        pointer: self.hover_transition_pointer(),
889                    };
890                    self.dispatch_to_widget(new, &enter, &mut *ops);
891                    // Seed the tooltip dwell too, exactly as `handle_pointer_move`
892                    // pairs these two. The rebuild replaced the anchor's tooltip
893                    // entry with a fresh one whose `hover_start` is `None`, and
894                    // the pointer is not going to move again — so without this the
895                    // widget's tooltip is unreachable for the rest of the hover.
896                    self.tooltip_pointer_enter(new);
897                }
898                self.set_hovered(new_target);
899            }
900        }
901
902        // Post-layout focus refresh — the symmetric case to the hover refresh
903        // above. A rebuild destroyed the focused widget, so
904        // `revalidate_interaction_state` cleared `focused` to `None`; the
905        // subtree that owned it was recorded as `pending_focus_restore`. Now
906        // that its fresh children have bounds from this layout pass, land focus
907        // back inside it, so a rebuild keeps focus in the subtree that had it
908        // rather than dumping it out of the widget entirely.
909        //
910        // Deliberately conservative: only when nothing else has taken focus in
911        // the meantime, only into a subtree that is still active (a rebuild that
912        // also went dormant, e.g. a popover closing, must NOT drag focus back
913        // into hidden content — its own dismiss path restores focus to the
914        // trigger), and only if it still has somewhere to put it. Otherwise focus
915        // stays `None`, exactly as before.
916        let restore = std::mem::take(&mut self.pending_focus_restore);
917        if self.focused.is_none()
918            && let Some(target) = restore.into_iter().find_map(|root| {
919                self.arena
920                    .is_active(root)
921                    .then(|| self.first_focusable_descendant(root))
922                    .flatten()
923            })
924        {
925            self.focus_ops(target, &mut *ops);
926        }
927
928        // A widget that changed size may have re-wrapped its text, and a
929        // wrapped label carries one accessibility text run per visual line
930        // — a different set of runs, not the same set somewhere else. Pure
931        // translations stay recorded on the arena for `sync_accessibility`
932        // to absorb without walking.
933        if self.arena.take_a11y_resized() {
934            self.a11y_dirty = true;
935        }
936
937        // Backstop. Every dismissal path is supposed to drain its callbacks
938        // itself — `dormant_dismissed_content` for the ones that park content,
939        // `gc_orphaned_overlays` for the one whose content is already gone —
940        // because draining *there* is what keeps the documented ordering
941        // (during dismissal, before focus returns to the trigger). This exists
942        // for the path nobody thought of: a parked callback that reaches the
943        // end of a frame has been stranded, and running it a frame late beats
944        // never. Costs a bool test when the queue is empty, which is always.
945        self.run_pending_dismiss_callbacks(&mut *ops);
946    }
947}
948
949/// What the `culls_children` parents in one layout walk decided about their
950/// children, collected here because settling either half needs `WidgetTree`,
951/// which the free function below does not have.
952///
953/// Both halves are recorded, not just the parks. A wake is applied inline —
954/// the child has to be laid out in the same pass or a camera that jumps shows
955/// a hole — but it still owes the tree the two things a park owes it: an
956/// invalidated AccessKit cache and a drained `activation_signal` queue.
957#[derive(Default)]
958pub(super) struct CullTransitions {
959    /// Children to park, applied once the walk is over so parking can go
960    /// through `WidgetTree::park_subtree_with_ops`.
961    park: Vec<WidgetId>,
962    /// Children already woken during the walk, kept so the settle step can
963    /// tell "nothing happened" from "something came back".
964    woke: Vec<WidgetId>,
965}
966
967impl CullTransitions {
968    /// Whether this walk changed any child's activation, either way.
969    fn is_empty(&self) -> bool {
970        self.park.is_empty() && self.woke.is_empty()
971    }
972}
973
974/// Recursive layout pass operating on the arena directly (avoids borrow conflicts).
975#[allow(clippy::too_many_arguments)]
976fn layout_widget_recursive(
977    arena: &mut WidgetArena,
978    id: WidgetId,
979    parent_bounds: Rect,
980    proposal: SizeProposal,
981    base_theme: &crate::styles::Theme,
982    layout_direction: crate::environment::LayoutDirection,
983    scale_factor: f32,
984    text_scale: f32,
985    text_backend: Option<&std::rc::Rc<std::cell::RefCell<dyn teksilo_canvas::TextBackend>>>,
986    extras: Option<crate::widget::LayoutExtras<'_>>,
987    // Every activation change a culling parent asked for during this walk.
988    // Settled by the caller once the walk is over.
989    culled: &mut CullTransitions,
990) {
991    if !arena.is_active(id) {
992        return;
993    }
994
995    let resolved_theme = arena.resolve_theme(id, base_theme);
996
997    let desired_size = {
998        let ctx = LayoutContext {
999            theme: &resolved_theme,
1000            layout_direction,
1001            scale_factor,
1002            text_scale,
1003            text_backend,
1004            arena: Some(arena),
1005            extras,
1006            stack_main_axis: None,
1007        };
1008        arena
1009            .cached_layout_response(id, proposal, &ctx)
1010            .map(|r| r.size)
1011            .unwrap_or(teksilo_canvas::Size::ZERO)
1012    };
1013
1014    let bounds = Rect::new(
1015        parent_bounds.x,
1016        parent_bounds.y,
1017        proposal.width.unwrap_or(desired_size.width),
1018        proposal.height.unwrap_or(desired_size.height),
1019    );
1020    let previous = arena.get_mut(id).and_then(|node| {
1021        let previous = node.bounds;
1022        (previous != bounds).then(|| {
1023            node.cached_paint = None;
1024            node.dirty.needs_paint = true;
1025            node.bounds = bounds;
1026            previous
1027        })
1028    });
1029    if let Some(previous) = previous {
1030        arena.note_bounds_change(id, previous, bounds);
1031    }
1032
1033    let child_ids: Vec<WidgetId> = arena.children(id).to_vec();
1034    // A widget that culls its children is handed the dormant ones too — it is
1035    // the only way it can ask for one back, having parked it. Every other
1036    // widget sees its active children and nothing else, exactly as before.
1037    let culls_children = arena
1038        .get(id)
1039        .is_some_and(|node| node.widget.culls_children());
1040    let mut placements: Vec<WidgetPlacement> = child_ids
1041        .iter()
1042        .copied()
1043        .filter_map(|child_id| {
1044            let active = arena.is_active(child_id);
1045            (active || culls_children).then_some(WidgetPlacement {
1046                id: child_id,
1047                origin: bounds.origin(),
1048                size: bounds.size(),
1049                dormant: !active,
1050            })
1051        })
1052        .collect();
1053
1054    // `place_children` is a widget's ONLY hook that receives its final,
1055    // parent-assigned `bounds`, so it runs for EVERY active widget on every
1056    // pass — including leaves, which get an empty `placements` slice. A widget
1057    // whose paint depends on where the parent put it (a scene folding its
1058    // origin into a view transform, a text engine sizing its viewport) can then
1059    // read its bounds during *layout*, which is the only point early enough:
1060    // the render walker pushes node-level transform scopes before `paint` runs.
1061    {
1062        let ctx = LayoutContext {
1063            theme: &resolved_theme,
1064            layout_direction,
1065            scale_factor,
1066            text_scale,
1067            text_backend,
1068            arena: Some(arena),
1069            extras,
1070            stack_main_axis: None,
1071        };
1072        let node = arena.get(id).expect("widget id is active in arena");
1073        node.widget
1074            .place_children(bounds, proposal, &mut placements, &ctx);
1075    }
1076
1077    for placement in &placements {
1078        if culls_children {
1079            // Apply the parent's decision before anything reads the child's
1080            // state. Waking is immediate — the child is laid out below, this
1081            // pass, so a camera that jumps shows no hole. Parking is recorded
1082            // and applied once the walk is over, because it has to go through
1083            // the tree-level door (`WidgetTree::park_subtree_with_ops`) to
1084            // tell any pointer working inside that its interaction is over.
1085            // Either way the child's bounds are written first, so a parked
1086            // card keeps the coordinate that `scroll_into_view` and
1087            // focus-follow read.
1088            let active = arena.is_active(placement.id);
1089            if !placement.dormant && !active {
1090                arena.activate(placement.id);
1091                // `activate` only *queues* the `(id, true)` transition; the
1092                // caller's settle step drains it. Recorded so that step can
1093                // run at all — a pass that woke a child and parked none used
1094                // to leave the queue and the AT cache untouched.
1095                culled.woke.push(placement.id);
1096            } else if placement.dormant && active {
1097                culled.park.push(placement.id);
1098            }
1099        }
1100
1101        let child_bounds = Rect::from_origin_size(placement.origin, placement.size);
1102        let previous = arena.get_mut(placement.id).and_then(|child_node| {
1103            let previous = child_node.bounds;
1104            (previous != child_bounds).then(|| {
1105                child_node.cached_paint = None;
1106                child_node.dirty.needs_paint = true;
1107                child_node.bounds = child_bounds;
1108                previous
1109            })
1110        });
1111        if let Some(previous) = previous {
1112            arena.note_bounds_change(placement.id, previous, child_bounds);
1113        }
1114
1115        // Gated on `culls_children`, because that is the contract: for every
1116        // other widget `dormant` arrives `false` and is not read back, and a
1117        // widget that set it anyway must not be able to take a child out of
1118        // the pass by writing a field it was told does nothing.
1119        if culls_children && placement.dormant {
1120            // Nothing below a parked child is laid out, painted, walked for
1121            // accessibility or reachable by Tab. That is the whole point.
1122            continue;
1123        }
1124
1125        let child_proposal = SizeProposal::exact(placement.size.width, placement.size.height);
1126        let grandchild_ids: Vec<WidgetId> = arena.children(placement.id).to_vec();
1127        if !grandchild_ids.is_empty() {
1128            layout_widget_recursive(
1129                arena,
1130                placement.id,
1131                child_bounds,
1132                child_proposal,
1133                base_theme,
1134                layout_direction,
1135                scale_factor,
1136                text_scale,
1137                text_backend,
1138                extras,
1139                culled,
1140            );
1141        } else {
1142            // A childless child is never visited by the recursion above, so
1143            // hand it its final bounds here — with an empty `placements` slice.
1144            //
1145            // Deliberately NOT a `layout_widget_recursive` call: that would
1146            // re-measure the leaf against a fresh `exact` proposal (a memo miss,
1147            // since the parent measured it under a different proposal), adding a
1148            // redundant `layout_response` per leaf on every pass.
1149            let ctx = LayoutContext {
1150                theme: &resolved_theme,
1151                layout_direction,
1152                scale_factor,
1153                text_scale,
1154                text_backend,
1155                arena: Some(arena),
1156                extras,
1157                stack_main_axis: None,
1158            };
1159            let node = arena.get(placement.id).expect("child id is active");
1160            node.widget
1161                .place_children(child_bounds, child_proposal, &mut [], &ctx);
1162        }
1163    }
1164}
1165
1166#[cfg(test)]
1167mod tests {
1168    use super::*;
1169    use crate::test_widgets::{FillWidget, InsetWidget, StackWidget};
1170    use teksilo_canvas::Size;
1171    use teksilo_tokens::Color;
1172
1173    /// A leaf of a fixed intrinsic size, so a `Centered` overlay has something
1174    /// to centre.
1175    #[derive(Debug)]
1176    struct Sized(f32, f32);
1177
1178    impl Widget for Sized {
1179        fn layout_response(
1180            &self,
1181            _proposal: SizeProposal,
1182            _ctx: &LayoutContext,
1183        ) -> crate::widget::LayoutResponse {
1184            Size::new(self.0, self.1).into()
1185        }
1186    }
1187
1188    fn tree_with_centred_modal(content_height: f32) -> (WidgetTree, crate::overlay::OverlayId) {
1189        let mut tree = WidgetTree::new();
1190        let anchor = tree.add(FillWidget::new());
1191        let content = tree.add(Sized(200.0, content_height));
1192        let id = tree.show_overlay(crate::overlay::OverlayRequest::new(
1193            content,
1194            anchor,
1195            crate::overlay::OverlayPlacement::Centered,
1196            crate::overlay::DismissBehavior::Manual,
1197        ));
1198        (tree, id)
1199    }
1200
1201    /// The supply this package exists to add: with nothing covering the window
1202    /// and no safe area, the viewport is the whole window — byte for byte the
1203    /// bare `(width, height)` tuple that used to be passed.
1204    #[test]
1205    fn a_bare_window_is_usable_to_its_last_pixel() {
1206        let (mut tree, id) = tree_with_centred_modal(100.0);
1207        tree.layout(SizeProposal::exact(400.0, 300.0));
1208        assert_eq!(tree.usable_viewport(), Rect::new(0.0, 0.0, 400.0, 300.0));
1209        let bounds = tree.overlay_content_bounds(id).expect("placed");
1210        assert_eq!(bounds.y, 100.0, "centred in 300: (300 - 100) / 2");
1211    }
1212
1213    /// A soft keyboard covering the bottom band shrinks the viewport, and the
1214    /// modal recomputes against what is left instead of centring behind it.
1215    #[test]
1216    fn an_occluding_band_shrinks_the_viewport_and_moves_the_modal() {
1217        let (mut tree, id) = tree_with_centred_modal(100.0);
1218        // The bottom 140 of a 300-tall window: a keyboard.
1219        tree.set_occluded_inset(Some(Rect::new(0.0, 160.0, 400.0, 140.0)));
1220        tree.layout(SizeProposal::exact(400.0, 300.0));
1221
1222        assert_eq!(
1223            tree.usable_viewport(),
1224            Rect::new(0.0, 0.0, 400.0, 160.0),
1225            "the largest free slab is the band above the keyboard"
1226        );
1227        let bounds = tree.overlay_content_bounds(id).expect("placed");
1228        assert_eq!(bounds.y, 30.0, "centred in 160: (160 - 100) / 2");
1229        assert!(
1230            bounds.y + bounds.height <= 160.0,
1231            "and the whole modal clears the keyboard"
1232        );
1233    }
1234
1235    /// When the content is taller than what is left, centring would push it off
1236    /// the top. It pins to the top of the usable area instead, so the first
1237    /// line stays reachable and the rest is scrolled to.
1238    #[test]
1239    fn a_modal_taller_than_the_usable_area_pins_to_its_top() {
1240        let (mut tree, id) = tree_with_centred_modal(240.0);
1241        tree.set_occluded_inset(Some(Rect::new(0.0, 160.0, 400.0, 140.0)));
1242        tree.layout(SizeProposal::exact(400.0, 300.0));
1243        let bounds = tree.overlay_content_bounds(id).expect("placed");
1244        assert_eq!(bounds.y, 0.0, "pinned to the top of the usable band");
1245    }
1246
1247    /// A safe area does the same for the reason a notch exists.
1248    #[test]
1249    fn a_safe_area_insets_the_viewport() {
1250        let (mut tree, id) = tree_with_centred_modal(100.0);
1251        tree.set_safe_area(teksilo_canvas::EdgeInsets {
1252            top: 40.0,
1253            bottom: 20.0,
1254            leading: 10.0,
1255            trailing: 10.0,
1256        });
1257        tree.layout(SizeProposal::exact(400.0, 300.0));
1258        assert_eq!(tree.usable_viewport(), Rect::new(10.0, 40.0, 380.0, 240.0));
1259        let bounds = tree.overlay_content_bounds(id).expect("placed");
1260        assert_eq!(bounds.y, 40.0 + (240.0 - 100.0) / 2.0);
1261    }
1262
1263    /// The scrim is deliberately not inset: one that respected the safe area
1264    /// would leave the notch undimmed and the content behind it legible.
1265    #[test]
1266    fn the_supply_does_not_move_the_root_layout() {
1267        // Occlusion reaches overlay placement and nothing else. A keyboard
1268        // rising must not reflow the document behind it — that is a scroll, not
1269        // a resize, and this is where the difference is decided.
1270        let mut tree = WidgetTree::new();
1271        let root = tree.add(FillWidget::new());
1272        tree.set_occluded_inset(Some(Rect::new(0.0, 160.0, 400.0, 140.0)));
1273        tree.set_safe_area(teksilo_canvas::EdgeInsets {
1274            top: 40.0,
1275            bottom: 0.0,
1276            leading: 0.0,
1277            trailing: 0.0,
1278        });
1279        tree.layout(SizeProposal::exact(400.0, 300.0));
1280        assert_eq!(
1281            tree.bounds(root),
1282            Rect::new(0.0, 0.0, 400.0, 300.0),
1283            "the root still owns the whole window"
1284        );
1285    }
1286
1287    /// A pending soft-keyboard request is recorded on the tree and taken
1288    /// exactly once, by the app layer, after its IME reconcile.
1289    #[test]
1290    fn a_soft_keyboard_request_is_taken_once() {
1291        let mut tree = WidgetTree::new();
1292        assert_eq!(tree.take_soft_keyboard_request(), None);
1293        tree.request_soft_keyboard(true);
1294        assert_eq!(tree.take_soft_keyboard_request(), Some(true));
1295        assert_eq!(
1296            tree.take_soft_keyboard_request(),
1297            None,
1298            "a request is a one-shot; a second take must not re-ask"
1299        );
1300    }
1301
1302    /// A leaf that records the bounds `place_children` hands it, and how often.
1303    #[derive(Debug, Clone, Default)]
1304    struct BoundsRecorder {
1305        seen: std::rc::Rc<std::cell::RefCell<Vec<Rect>>>,
1306    }
1307
1308    impl Widget for BoundsRecorder {
1309        fn layout_response(
1310            &self,
1311            proposal: SizeProposal,
1312            _ctx: &LayoutContext,
1313        ) -> crate::widget::LayoutResponse {
1314            Size::new(
1315                proposal.width.unwrap_or(10.0),
1316                proposal.height.unwrap_or(10.0),
1317            )
1318            .into()
1319        }
1320
1321        fn place_children(
1322            &self,
1323            bounds: Rect,
1324            _proposal: SizeProposal,
1325            children: &mut [WidgetPlacement],
1326            _ctx: &LayoutContext,
1327        ) {
1328            assert!(
1329                children.is_empty(),
1330                "a leaf must be handed an empty placements slice"
1331            );
1332            self.seen.borrow_mut().push(bounds);
1333        }
1334    }
1335
1336    /// The invariant `SceneView` (and both text engines) depend on: a widget with
1337    /// NO children still gets `place_children`, carrying its final bounds.
1338    ///
1339    /// Before this was guaranteed, the walker skipped `place_children` whenever
1340    /// there was nothing to place, so a leaf could only discover its bounds in
1341    /// `paint`. That is too late for anything the renderer consumes *before*
1342    /// paint — a `SceneView` folds `bounds.origin` into the transform scope the
1343    /// walker pushes around its subtree, so a scene holding only lightweight
1344    /// items (hence no arena children) painted its content offset by
1345    /// `-bounds.origin`, an error that scaled with zoom.
1346    #[test]
1347    fn a_childless_widget_still_receives_its_bounds() {
1348        let mut tree = WidgetTree::new();
1349        let leaf = BoundsRecorder::default();
1350        let seen = leaf.seen.clone();
1351
1352        // Nested inside an inset container, so a correct origin is non-zero and a
1353        // stale/zero origin cannot pass by accident.
1354        let leaf_id = tree.add(leaf);
1355        let _root = tree.add(InsetWidget::new(12.0).set_child(leaf_id));
1356        tree.layout(SizeProposal::exact(200.0, 100.0));
1357
1358        let bounds = seen.borrow();
1359        assert_eq!(
1360            bounds.len(),
1361            1,
1362            "the leaf must be placed exactly once per layout pass, got {bounds:?}"
1363        );
1364        assert_eq!(
1365            (bounds[0].x, bounds[0].y),
1366            (12.0, 12.0),
1367            "the leaf must receive its real, parent-assigned origin"
1368        );
1369        assert_eq!(
1370            (bounds[0].width, bounds[0].height),
1371            (176.0, 76.0),
1372            "the leaf must receive its real, parent-assigned size"
1373        );
1374    }
1375
1376    /// The same guarantee at the root: a tree whose root IS a leaf.
1377    #[test]
1378    fn a_childless_root_still_receives_its_bounds() {
1379        let mut tree = WidgetTree::new();
1380        let leaf = BoundsRecorder::default();
1381        let seen = leaf.seen.clone();
1382        let _id = tree.add(leaf);
1383        tree.layout(SizeProposal::exact(320.0, 240.0));
1384
1385        let bounds = seen.borrow();
1386        assert_eq!(bounds.len(), 1, "root leaf must be placed once");
1387        assert_eq!((bounds[0].width, bounds[0].height), (320.0, 240.0));
1388    }
1389
1390    #[derive(Debug)]
1391    struct ShrinkWrapContainer {
1392        child: WidgetId,
1393        inset: f32,
1394    }
1395
1396    impl Widget for ShrinkWrapContainer {
1397        fn layout_response(
1398            &self,
1399            _proposal: SizeProposal,
1400            ctx: &LayoutContext,
1401        ) -> crate::widget::LayoutResponse {
1402            let child_size = ctx
1403                .child_size(self.child, SizeProposal::unspecified())
1404                .unwrap_or(Size::ZERO);
1405            Size::new(
1406                child_size.width + self.inset * 2.0,
1407                child_size.height + self.inset * 2.0,
1408            )
1409            .into()
1410        }
1411
1412        fn place_children(
1413            &self,
1414            bounds: Rect,
1415            _proposal: SizeProposal,
1416            children: &mut [WidgetPlacement],
1417            _ctx: &LayoutContext,
1418        ) {
1419            for child in children.iter_mut() {
1420                child.origin = Point::new(bounds.x + self.inset, bounds.y + self.inset);
1421                child.size = Size::new(
1422                    (bounds.width - self.inset * 2.0).max(0.0),
1423                    (bounds.height - self.inset * 2.0).max(0.0),
1424                );
1425            }
1426        }
1427
1428        fn children(&self) -> Vec<WidgetId> {
1429            vec![self.child]
1430        }
1431    }
1432
1433    // ── Per-pass layout memoization cache (Part C) ──────────────────────────
1434
1435    /// A childless leaf that counts how many times `layout_response` runs and
1436    /// can opt out of caching. The driver does not recurse into a childless
1437    /// leaf's placement, so the only calls come from a parent's `child_size`
1438    /// queries — making the count a precise probe of the cache.
1439    #[derive(Debug)]
1440    struct CountingLeaf {
1441        calls: std::rc::Rc<std::cell::Cell<u32>>,
1442        cacheable: bool,
1443    }
1444
1445    impl Widget for CountingLeaf {
1446        fn layout_response(
1447            &self,
1448            _proposal: SizeProposal,
1449            _ctx: &LayoutContext,
1450        ) -> crate::widget::LayoutResponse {
1451            self.calls.set(self.calls.get() + 1);
1452            Size::new(50.0, 20.0).into()
1453        }
1454        fn cacheable_layout(&self) -> bool {
1455            self.cacheable
1456        }
1457    }
1458
1459    /// Queries its single child with the *same* proposal in both
1460    /// `layout_response` and `place_children` — the pattern real stacks use
1461    /// for height-for-width. With caching the child computes once; without it,
1462    /// twice.
1463    #[derive(Debug)]
1464    struct DoubleQueryContainer {
1465        child: WidgetId,
1466    }
1467
1468    impl Widget for DoubleQueryContainer {
1469        fn layout_response(
1470            &self,
1471            _proposal: SizeProposal,
1472            ctx: &LayoutContext,
1473        ) -> crate::widget::LayoutResponse {
1474            ctx.child_size(self.child, SizeProposal::exact(50.0, 20.0))
1475                .unwrap_or(Size::ZERO)
1476                .into()
1477        }
1478        fn place_children(
1479            &self,
1480            bounds: Rect,
1481            _proposal: SizeProposal,
1482            children: &mut [WidgetPlacement],
1483            ctx: &LayoutContext,
1484        ) {
1485            // Second query with the identical proposal.
1486            let _ = ctx.child_size(self.child, SizeProposal::exact(50.0, 20.0));
1487            for child in children.iter_mut() {
1488                child.origin = bounds.origin();
1489                child.size = bounds.size();
1490            }
1491        }
1492        fn children(&self) -> Vec<WidgetId> {
1493            vec![self.child]
1494        }
1495    }
1496
1497    #[test]
1498    fn cache_dedupes_identical_child_queries_within_a_pass() {
1499        let calls = std::rc::Rc::new(std::cell::Cell::new(0));
1500        let mut tree = WidgetTree::new();
1501        let leaf = tree.add(CountingLeaf {
1502            calls: calls.clone(),
1503            cacheable: true,
1504        });
1505        let _root = tree.add(DoubleQueryContainer { child: leaf });
1506        tree.layout(SizeProposal::exact(100.0, 50.0));
1507        // Two identical `exact(50,20)` queries (layout_response + place_children)
1508        // collapse to one real call; the driver does not recurse into the
1509        // childless leaf.
1510        assert_eq!(calls.get(), 1, "cacheable leaf should be computed once");
1511    }
1512
1513    #[test]
1514    fn cache_opt_out_recomputes_every_query() {
1515        let calls = std::rc::Rc::new(std::cell::Cell::new(0));
1516        let mut tree = WidgetTree::new();
1517        let leaf = tree.add(CountingLeaf {
1518            calls: calls.clone(),
1519            cacheable: false,
1520        });
1521        let _root = tree.add(DoubleQueryContainer { child: leaf });
1522        tree.layout(SizeProposal::exact(100.0, 50.0));
1523        assert_eq!(
1524            calls.get(),
1525            2,
1526            "opt-out leaf must run on every query (side effects preserved)"
1527        );
1528    }
1529
1530    #[test]
1531    fn cache_is_cleared_between_passes() {
1532        let calls = std::rc::Rc::new(std::cell::Cell::new(0));
1533        let mut tree = WidgetTree::new();
1534        let leaf = tree.add(CountingLeaf {
1535            calls: calls.clone(),
1536            cacheable: true,
1537        });
1538        let _root = tree.add(DoubleQueryContainer { child: leaf });
1539        tree.layout(SizeProposal::exact(100.0, 50.0));
1540        // A second pass with a different proposal must re-run layout — proving
1541        // the cache is per-pass, not stale across passes (the `exact(50,20)`
1542        // child key is identical between passes).
1543        tree.layout(SizeProposal::exact(120.0, 60.0));
1544        assert_eq!(
1545            calls.get(),
1546            2,
1547            "each pass recomputes; cache cleared per pass"
1548        );
1549    }
1550
1551    // ── measure_intrinsic (Primitive 2) ─────────────────────────────────────
1552
1553    /// Probe: from its own `layout_response`, measures `target` two ways and
1554    /// stashes the results — the normal (activation-gated) query and the
1555    /// intrinsic (activation-ignoring) query.
1556    #[derive(Debug)]
1557    struct MeasureProbe {
1558        target: WidgetId,
1559        active_w: std::rc::Rc<std::cell::Cell<f32>>, // -1.0 == None
1560        intrinsic_w: std::rc::Rc<std::cell::Cell<f32>>,
1561    }
1562    impl Widget for MeasureProbe {
1563        fn layout_response(
1564            &self,
1565            p: SizeProposal,
1566            ctx: &LayoutContext,
1567        ) -> crate::widget::LayoutResponse {
1568            // Measure intrinsic FIRST, then the normal gated query: if the
1569            // measure had polluted the cache, the gated query could wrongly
1570            // return a size for the dormant target. `exact` because FillWidget
1571            // fills its proposal (it has no intrinsic size of its own).
1572            let probe = SizeProposal::exact(120.0, 30.0);
1573            let intrinsic = ctx
1574                .measure_intrinsic(self.target, probe)
1575                .map(|s| s.width)
1576                .unwrap_or(-1.0);
1577            let active = ctx
1578                .child_size(self.target, probe)
1579                .map(|s| s.width)
1580                .unwrap_or(-1.0);
1581            self.intrinsic_w.set(intrinsic);
1582            self.active_w.set(active);
1583            p.resolve(0.0, 0.0).into()
1584        }
1585        fn cacheable_layout(&self) -> bool {
1586            false
1587        }
1588    }
1589
1590    #[test]
1591    fn measure_intrinsic_sees_a_dormant_widget_normal_query_does_not() {
1592        let active = std::rc::Rc::new(std::cell::Cell::new(0.0));
1593        let intrinsic = std::rc::Rc::new(std::cell::Cell::new(0.0));
1594        let mut tree = WidgetTree::new();
1595        let leaf = tree.add(FillWidget::new());
1596        tree.set_dormant(leaf);
1597        let _probe = tree.add(MeasureProbe {
1598            target: leaf,
1599            active_w: active.clone(),
1600            intrinsic_w: intrinsic.clone(),
1601        });
1602        tree.layout(SizeProposal::exact(200.0, 50.0));
1603
1604        // measure_intrinsic measures the dormant widget (FillWidget fills the
1605        // 120px probe)…
1606        assert!(
1607            (intrinsic.get() - 120.0).abs() < 0.01,
1608            "measure_intrinsic should size the dormant widget, got {}",
1609            intrinsic.get()
1610        );
1611        // …and the normal gated query (run AFTER) still returns None — proving
1612        // the measure bypassed, and did not seed, the per-pass cache.
1613        assert_eq!(
1614            active.get(),
1615            -1.0,
1616            "child_size must stay None for a dormant widget (no cache pollution)"
1617        );
1618    }
1619
1620    /// A box whose height is driven by a signal and whose width echoes the
1621    /// proposed width (height-for-width) — models a widget (e.g. a `MessageBox`
1622    /// "Show details" expander) whose intrinsic height changes with content.
1623    /// Echoing the width lets a fixed-width intrinsic measurement be exercised.
1624    #[derive(Debug)]
1625    struct SignalBox {
1626        h: crate::signal::Signal<f32>,
1627    }
1628    impl Widget for SignalBox {
1629        fn layout_response(
1630            &self,
1631            p: SizeProposal,
1632            _ctx: &LayoutContext,
1633        ) -> crate::widget::LayoutResponse {
1634            teksilo_canvas::Size::new(p.width.unwrap_or(0.0), self.h.get()).into()
1635        }
1636        fn cacheable_layout(&self) -> bool {
1637            false
1638        }
1639    }
1640
1641    /// Sums the ACTIVE children's heights via `child_size` (which returns
1642    /// `None` for a dormant child, so a hidden child contributes nothing) —
1643    /// lets a test assert size-to-content excludes dormant subtrees.
1644    #[derive(Debug)]
1645    struct VSumBox {
1646        children: Vec<WidgetId>,
1647    }
1648    impl Widget for VSumBox {
1649        fn layout_response(
1650            &self,
1651            p: SizeProposal,
1652            ctx: &LayoutContext,
1653        ) -> crate::widget::LayoutResponse {
1654            let h: f32 = self
1655                .children
1656                .iter()
1657                .filter_map(|&c| ctx.child_size(c, p))
1658                .map(|s| s.height)
1659                .sum();
1660            teksilo_canvas::Size::new(p.width.unwrap_or(0.0), h).into()
1661        }
1662        fn children(&self) -> Vec<WidgetId> {
1663            self.children.clone()
1664        }
1665    }
1666
1667    #[test]
1668    fn measure_root_intrinsic_honors_fixed_width_and_tracks_content() {
1669        let h = crate::signal::Signal::new(140.0);
1670        let mut tree = WidgetTree::new();
1671        let _root = tree.add(SignalBox { h: h.clone() });
1672        // Lay the root out constrained to a fixed native-modal size.
1673        tree.layout(SizeProposal::exact(460.0, 140.0));
1674
1675        // Intrinsic measurement at a fixed width / unbounded height reports the
1676        // proposed width and the content's natural height — the size a
1677        // size-to-content window grows to, independent of the constrained pass.
1678        let m = tree
1679            .measure_root_intrinsic(SizeProposal {
1680                width: Some(460.0),
1681                height: None,
1682            })
1683            .expect("one active primary root");
1684        assert!(
1685            (m.width - 460.0).abs() < 0.01,
1686            "fixed width honored, got {}",
1687            m.width
1688        );
1689        assert!(
1690            (m.height - 140.0).abs() < 0.01,
1691            "natural height, got {}",
1692            m.height
1693        );
1694
1695        // A different fixed width flows through (the proposal really is used).
1696        let narrow = tree
1697            .measure_root_intrinsic(SizeProposal {
1698                width: Some(300.0),
1699                height: None,
1700            })
1701            .expect("root active");
1702        assert!(
1703            (narrow.width - 300.0).abs() < 0.01,
1704            "proposal width, got {}",
1705            narrow.width
1706        );
1707
1708        // Content growth (a "Show details" expander) is reflected.
1709        h.set(300.0);
1710        let grown = tree
1711            .measure_root_intrinsic(SizeProposal {
1712                width: Some(460.0),
1713                height: None,
1714            })
1715            .expect("root active");
1716        assert!(
1717            (grown.height - 300.0).abs() < 0.01,
1718            "grows with content, got {}",
1719            grown.height
1720        );
1721    }
1722
1723    #[test]
1724    fn measure_root_intrinsic_excludes_dormant_content() {
1725        let mut tree = WidgetTree::new();
1726        let shown = tree.add(SignalBox {
1727            h: crate::signal::Signal::new(200.0),
1728        });
1729        let hidden = tree.add(SignalBox {
1730            h: crate::signal::Signal::new(1000.0),
1731        });
1732        tree.set_dormant(hidden);
1733        let _root = tree.add(VSumBox {
1734            children: vec![shown, hidden],
1735        });
1736        tree.layout(SizeProposal::exact(460.0, 200.0));
1737
1738        // The dormant child must NOT contribute — a size-to-content window is
1739        // sized to what is actually shown. Regression guard for measuring via
1740        // `layout_response` (activation-respecting) rather than the
1741        // activation-ignoring `measure_intrinsic` (which would return 1200).
1742        let m = tree
1743            .measure_root_intrinsic(SizeProposal {
1744                width: Some(460.0),
1745                height: None,
1746            })
1747            .expect("one active primary root");
1748        assert!(
1749            (m.height - 200.0).abs() < 0.01,
1750            "dormant child must be excluded, got {}",
1751            m.height
1752        );
1753    }
1754
1755    #[test]
1756    fn single_widget_fills_proposal() {
1757        let mut tree = WidgetTree::new();
1758        let widget = tree.add(FillWidget::new().background(Color::RED));
1759        tree.layout(SizeProposal::exact(200.0, 40.0));
1760        let bounds = tree.bounds(widget);
1761        assert_eq!(bounds.width, 200.0);
1762        assert_eq!(bounds.height, 40.0);
1763    }
1764
1765    #[test]
1766    fn stack_children_overlap() {
1767        let mut tree = WidgetTree::new();
1768        let a = tree.add(FillWidget::new());
1769        let b = tree.add(FillWidget::new());
1770        let stack = tree.add(StackWidget::new().child(a).child(b));
1771        tree.layout(SizeProposal::exact(100.0, 50.0));
1772        let children = tree.children(stack);
1773        assert_eq!(children.len(), 2);
1774        let a_bounds = tree.bounds(children[0]);
1775        let b_bounds = tree.bounds(children[1]);
1776        assert_eq!(a_bounds.origin(), b_bounds.origin());
1777        assert_eq!(a_bounds.size(), b_bounds.size());
1778    }
1779
1780    #[test]
1781    fn inset_widget_insets_child() {
1782        let mut tree = WidgetTree::new();
1783        let child = tree.add(FillWidget::new());
1784        let parent = tree.add(InsetWidget::new(10.0).set_child(child));
1785        tree.layout(SizeProposal::exact(100.0, 50.0));
1786        let children = tree.children(parent);
1787        let child_bounds = tree.bounds(children[0]);
1788        assert_eq!(child_bounds.x, 10.0);
1789        assert_eq!(child_bounds.y, 10.0);
1790        assert_eq!(child_bounds.width, 80.0);
1791        assert_eq!(child_bounds.height, 30.0);
1792    }
1793
1794    #[test]
1795    fn recursive_layout_preserves_exact_parent_placement_for_containers() {
1796        let mut tree = WidgetTree::new();
1797        let leaf = tree.add(FillWidget::new());
1798        let shrink = tree.add(ShrinkWrapContainer {
1799            child: leaf,
1800            inset: 8.0,
1801        });
1802        let root = tree.add(StackWidget::new().child(shrink));
1803
1804        tree.layout(SizeProposal::exact(120.0, 80.0));
1805
1806        assert_eq!(tree.bounds(root), Rect::new(0.0, 0.0, 120.0, 80.0));
1807        assert_eq!(
1808            tree.bounds(shrink),
1809            Rect::new(0.0, 0.0, 120.0, 80.0),
1810            "child container should keep the exact size assigned by its parent"
1811        );
1812        assert_eq!(tree.bounds(leaf), Rect::new(8.0, 8.0, 104.0, 64.0));
1813    }
1814
1815    #[test]
1816    fn needs_paint_after_layout() {
1817        let mut tree = WidgetTree::new();
1818        tree.add(FillWidget::new());
1819        assert!(tree.needs_layout());
1820        tree.layout(SizeProposal::exact(100.0, 50.0));
1821        assert!(!tree.needs_layout());
1822    }
1823
1824    #[test]
1825    fn signal_binding_marks_widget_dirty_on_layout() {
1826        use crate::signal::Signal;
1827
1828        let mut tree = WidgetTree::new();
1829        let widget = tree.add(FillWidget::new().background(Color::RED));
1830        tree.layout(SizeProposal::exact(100.0, 50.0));
1831        tree.render();
1832
1833        assert!(!tree.needs_paint());
1834
1835        let visible = Signal::new(true);
1836        visible.bind_to(
1837            widget,
1838            tree.binding_registry(),
1839            crate::binding::BindingLevel::RepaintOnly,
1840        );
1841
1842        visible.set(false);
1843        tree.layout(SizeProposal::exact(100.0, 50.0));
1844        assert!(tree.needs_paint());
1845    }
1846
1847    /// `culls_children` as a framework primitive, without a scene.
1848    ///
1849    /// The mechanism is one field and two rules: a widget that opts in is
1850    /// handed every child, parked ones included, and whatever it leaves in
1851    /// `WidgetPlacement::dormant` is applied — cleared wakes in the same pass,
1852    /// set parks after it.
1853    mod culling_containers {
1854        use super::*;
1855        use crate::signal::Signal;
1856        use crate::widget::{LayoutResponse, WidgetPlacement};
1857        use crate::widget_builder::WidgetBuilder;
1858        use std::cell::Cell;
1859        use std::rc::Rc;
1860
1861        /// Parks every child whose index is set in the `park` bitmask, and
1862        /// reports how many children its `place_children` was handed.
1863        ///
1864        /// `park` is a `Signal` bound at `BindingLevel::Relayout` — the same
1865        /// level a `SceneView` binds its camera at — because that is what makes
1866        /// changing it run a pass at all: `layout_with_ops` returns early when
1867        /// the proposal is unchanged and nothing needs layout.
1868        #[derive(Debug)]
1869        struct Culler {
1870            kids: Vec<WidgetId>,
1871            park: Signal<u64>,
1872            seen: Rc<Cell<usize>>,
1873            opts_in: bool,
1874            /// Stop writing `dormant` at all, so what the framework pre-set
1875            /// there is what gets applied.
1876            ignore_dormant: Rc<Cell<bool>>,
1877            /// One per child, so "was this subtree recursed into" is
1878            /// observable and not merely inferred from the child's activation.
1879            grandkids: Rc<std::cell::RefCell<Vec<WidgetId>>>,
1880            /// How many times the culler has been asked to decide. The
1881            /// question "was the decision re-taken?" has no other witness — a
1882            /// re-run that reaches the same answer changes nothing else.
1883            passes: Rc<Cell<usize>>,
1884        }
1885
1886        impl Culler {
1887            fn new(park: Signal<u64>, seen: Rc<Cell<usize>>, opts_in: bool) -> Self {
1888                Self {
1889                    kids: Vec::new(),
1890                    park,
1891                    seen,
1892                    opts_in,
1893                    ignore_dormant: Rc::new(Cell::new(false)),
1894                    grandkids: Rc::new(std::cell::RefCell::new(Vec::new())),
1895                    passes: Rc::new(Cell::new(0)),
1896                }
1897            }
1898        }
1899
1900        impl Widget for Culler {
1901            fn build(&mut self, ctx: &mut crate::build_context::BuildContext) -> Vec<WidgetId> {
1902                self.park.bind_to(
1903                    ctx.self_id(),
1904                    ctx.binding_registry(),
1905                    crate::binding::BindingLevel::Relayout,
1906                );
1907                // Each child has a child of its own, so "was this subtree
1908                // recursed into" is observable from the grandchild's bounds
1909                // and not only from the child's activation.
1910                self.kids = (0..3)
1911                    .map(|i| {
1912                        let grandkid = ctx.add(FillWidget::new().label(format!("grandkid{i}")));
1913                        self.grandkids.borrow_mut().push(grandkid);
1914                        ctx.add(StackWidget::new().child(grandkid).focusable(true))
1915                    })
1916                    .collect();
1917                self.kids.clone()
1918            }
1919            fn layout_response(
1920                &self,
1921                _p: SizeProposal,
1922                _c: &crate::widget::LayoutContext,
1923            ) -> LayoutResponse {
1924                teksilo_canvas::Size::new(100.0, 100.0).into()
1925            }
1926            fn children(&self) -> Vec<WidgetId> {
1927                self.kids.clone()
1928            }
1929            fn culls_children(&self) -> bool {
1930                self.opts_in
1931            }
1932            fn place_children(
1933                &self,
1934                bounds: Rect,
1935                _proposal: SizeProposal,
1936                children: &mut [WidgetPlacement],
1937                _ctx: &crate::widget::LayoutContext,
1938            ) {
1939                self.seen.set(children.len());
1940                self.passes.set(self.passes.get() + 1);
1941                let mask = self.park.get();
1942                for placement in children.iter_mut() {
1943                    let Some(i) = self.kids.iter().position(|&k| k == placement.id) else {
1944                        continue;
1945                    };
1946                    placement.origin = teksilo_canvas::Point::new(0.0, i as f32 * 20.0);
1947                    // Width follows the proposal so a *grandchild*'s size says
1948                    // whether the recursion reached it — a child's own size is
1949                    // written here, before any cull decision, and so proves
1950                    // nothing.
1951                    placement.size = teksilo_canvas::Size::new(bounds.width, 20.0);
1952                    if !self.ignore_dormant.get() {
1953                        placement.dormant = mask & (1 << i) != 0;
1954                    }
1955                }
1956            }
1957        }
1958
1959        struct Rig {
1960            tree: WidgetTree,
1961            id: WidgetId,
1962            park: Signal<u64>,
1963            seen: Rc<Cell<usize>>,
1964            ignore_dormant: Rc<Cell<bool>>,
1965            grandkids: Rc<std::cell::RefCell<Vec<WidgetId>>>,
1966            passes: Rc<Cell<usize>>,
1967        }
1968
1969        fn tree_with(opts_in: bool) -> Rig {
1970            let park = Signal::new(0u64);
1971            let seen = Rc::new(Cell::new(0usize));
1972            let culler = Culler::new(park.clone(), seen.clone(), opts_in);
1973            let ignore_dormant = culler.ignore_dormant.clone();
1974            let grandkids = culler.grandkids.clone();
1975            let passes = culler.passes.clone();
1976            let mut tree = WidgetTree::new();
1977            let id = tree.add(culler);
1978            tree.layout(SizeProposal::exact(100.0, 100.0));
1979            Rig {
1980                tree,
1981                id,
1982                park,
1983                seen,
1984                ignore_dormant,
1985                grandkids,
1986                passes,
1987            }
1988        }
1989
1990        #[test]
1991        fn focus_moving_re_asks_the_culling_parent_that_owns_it() {
1992            // A culling parent is told to keep what the user is in the middle
1993            // of, and it is only asked during layout — but focus moving from
1994            // one child to another moves nothing and resizes nothing, so the
1995            // idle early-return would skip the pass and leave the parent
1996            // answering with a stale anchor set. It would go on pinning the
1997            // child the user has left, and never pin the one they arrived in.
1998            //
1999            // Harmless while pinning only keeps a child *alive* — a newly
2000            // focused child is active by definition. Not harmless for a parent
2001            // that publishes a narrower set than it keeps alive, as
2002            // `SceneView` does: the published tree names its focused node, and
2003            // a focus the walk did not emit is a broken update.
2004            let Rig {
2005                mut tree,
2006                id,
2007                passes,
2008                ..
2009            } = tree_with(true);
2010            let kids = tree.children(id).to_vec();
2011
2012            let before = passes.get();
2013            tree.layout(SizeProposal::exact(100.0, 100.0));
2014            assert_eq!(
2015                passes.get(),
2016                before,
2017                "precondition: a settled tree skips the pass entirely"
2018            );
2019
2020            tree.focus(kids[0]);
2021            tree.layout(SizeProposal::exact(100.0, 100.0));
2022            assert_eq!(
2023                passes.get(),
2024                before + 1,
2025                "focus arriving is a change to the culler's inputs"
2026            );
2027
2028            tree.focus(kids[2]);
2029            tree.layout(SizeProposal::exact(100.0, 100.0));
2030            assert_eq!(
2031                passes.get(),
2032                before + 2,
2033                "…and so is focus moving between two of its children"
2034            );
2035
2036            tree.layout(SizeProposal::exact(100.0, 100.0));
2037            assert_eq!(
2038                passes.get(),
2039                before + 2,
2040                "…while a pass with the same anchors is still skipped"
2041            );
2042        }
2043
2044        #[test]
2045        fn focus_moving_forces_no_pass_where_nothing_culls() {
2046            // The scoping half. The invalidation walks up from the moved
2047            // anchor and marks only `culls_children` ancestors, so a tree
2048            // without one pays a parent-chain walk and forces no layout — the
2049            // cost lands on the trees that asked for the mechanism.
2050            let Rig {
2051                mut tree,
2052                id,
2053                passes,
2054                ..
2055            } = tree_with(false);
2056            let kids = tree.children(id).to_vec();
2057            let before = passes.get();
2058
2059            tree.focus(kids[0]);
2060            tree.layout(SizeProposal::exact(100.0, 100.0));
2061            tree.focus(kids[2]);
2062            tree.layout(SizeProposal::exact(100.0, 100.0));
2063
2064            assert_eq!(
2065                passes.get(),
2066                before,
2067                "no culling ancestor, no reason to re-run layout"
2068            );
2069        }
2070
2071        #[test]
2072        fn a_parked_child_leaves_the_tab_ring_and_the_at_tree_in_the_same_pass() {
2073            let Rig {
2074                mut tree, id, park, ..
2075            } = tree_with(true);
2076            let kids = tree.children(id).to_vec();
2077            assert_eq!(tree.tab_stops_within(id).len(), 3);
2078            let before = tree.accessibility_tree_snapshot().nodes.len();
2079
2080            park.set(0b010);
2081            tree.layout(SizeProposal::exact(100.0, 100.0));
2082
2083            assert!(!tree.is_active(kids[1]), "parked in the pass that asked");
2084            assert!(tree.is_active(kids[0]) && tree.is_active(kids[2]));
2085            let stops = tree.tab_stops_within(id);
2086            assert_eq!(stops.len(), 2, "stops = {stops:?}");
2087            assert!(!stops.contains(&kids[1]));
2088            assert_eq!(
2089                tree.accessibility_tree_snapshot().nodes.len(),
2090                before - 2,
2091                "the parked child AND its own child leave the AccessKit tree — \
2092                 parking is a subtree operation"
2093            );
2094        }
2095
2096        #[test]
2097        fn a_parked_child_takes_its_subtree_out_of_the_layout_recursion() {
2098            // The activation flag alone does not prove this: a child could be
2099            // dormant and still have been recursed into. Watch the grandchild's
2100            // bounds, which only the recursion writes.
2101            let Rig {
2102                mut tree,
2103                park,
2104                grandkids,
2105                ..
2106            } = tree_with(true);
2107            let grandkid = grandkids.borrow()[1];
2108            assert_eq!(tree.bounds(grandkid).size(), Size::new(100.0, 20.0));
2109
2110            park.set(0b010);
2111            tree.layout(SizeProposal::exact(100.0, 300.0));
2112            let parked_bounds = tree.bounds(grandkid);
2113
2114            // Change the geometry the recursion would have written, and check
2115            // it does not reach the parked subtree.
2116            park.set(0b010);
2117            tree.layout(SizeProposal::exact(100.0, 300.0));
2118            assert_eq!(
2119                tree.bounds(grandkid),
2120                parked_bounds,
2121                "nothing below a parked child is laid out"
2122            );
2123
2124            park.set(0);
2125            tree.layout(SizeProposal::exact(100.0, 300.0));
2126            assert_eq!(
2127                tree.bounds(grandkid).size(),
2128                Size::new(100.0, 20.0),
2129                "…and the recursion resumes when it wakes"
2130            );
2131        }
2132
2133        #[test]
2134        fn a_parent_that_leaves_dormant_alone_changes_nothing() {
2135            // `dormant` arrives pre-set to the child's current state, so a
2136            // culling parent that does not write it keeps whatever it decided
2137            // last time. Without that, every pass in which the parent declines
2138            // to answer would silently wake everything it had parked.
2139            let Rig {
2140                mut tree,
2141                park,
2142                ignore_dormant,
2143                id,
2144                ..
2145            } = tree_with(true);
2146            let kids = tree.children(id).to_vec();
2147
2148            park.set(0b101);
2149            tree.layout(SizeProposal::exact(100.0, 100.0));
2150            assert!(!tree.is_active(kids[0]) && !tree.is_active(kids[2]));
2151
2152            ignore_dormant.set(true);
2153            park.set(0);
2154            tree.layout(SizeProposal::exact(100.0, 100.0));
2155            assert!(
2156                !tree.is_active(kids[0]) && !tree.is_active(kids[2]),
2157                "a parent that ignores the field must not resurrect anything"
2158            );
2159            assert!(tree.is_active(kids[1]), "…nor park anything");
2160        }
2161
2162        #[test]
2163        fn a_woken_child_is_laid_out_in_the_same_pass() {
2164            // The half a signal-based gate cannot do: a gate written during
2165            // layout is not read until the next pass, so the woken child would
2166            // paint at a stale rectangle for a frame.
2167            let Rig {
2168                mut tree, id, park, ..
2169            } = tree_with(true);
2170            let kids = tree.children(id).to_vec();
2171
2172            park.set(0b100);
2173            tree.layout(SizeProposal::exact(100.0, 100.0));
2174            assert!(!tree.is_active(kids[2]));
2175
2176            park.set(0);
2177            tree.layout(SizeProposal::exact(100.0, 100.0));
2178            assert!(tree.is_active(kids[2]), "woken");
2179            assert_eq!(
2180                tree.bounds(kids[2]),
2181                Rect::new(0.0, 40.0, 100.0, 20.0),
2182                "…and laid out this pass, not the next"
2183            );
2184        }
2185
2186        #[test]
2187        fn a_culling_parent_is_handed_its_parked_children() {
2188            // Otherwise it could never ask one back, having parked it.
2189            let Rig {
2190                mut tree,
2191                park,
2192                seen,
2193                ..
2194            } = tree_with(true);
2195            assert_eq!(seen.get(), 3);
2196            park.set(0b111);
2197            tree.layout(SizeProposal::exact(100.0, 100.0));
2198            park.set(0b111);
2199            tree.layout(SizeProposal::exact(100.0, 100.0));
2200            assert_eq!(
2201                seen.get(),
2202                3,
2203                "all three are parked, and all three are still offered"
2204            );
2205        }
2206
2207        #[test]
2208        fn a_widget_that_did_not_opt_in_cannot_park_anything() {
2209            // `dormant` is documented as read only for a `culls_children`
2210            // parent. A widget that writes it anyway must change nothing —
2211            // otherwise the field is a trapdoor on every container in the
2212            // framework.
2213            let Rig {
2214                mut tree,
2215                id,
2216                park,
2217                seen,
2218                grandkids,
2219                ..
2220            } = tree_with(false);
2221            let kids = tree.children(id).to_vec();
2222            park.set(0b111);
2223            tree.layout(SizeProposal::exact(100.0, 100.0));
2224            assert_eq!(seen.get(), 3, "active children only, which is all of them");
2225            for kid in &kids {
2226                assert!(tree.is_active(*kid), "{kid:?} must stay active");
2227            }
2228            assert_eq!(tree.tab_stops_within(id).len(), 3);
2229            // Widen the view so a subtree that was recursed into changes size.
2230            tree.layout(SizeProposal::exact(200.0, 100.0));
2231            for grandkid in grandkids.borrow().iter() {
2232                assert_eq!(
2233                    tree.bounds(*grandkid).size(),
2234                    Size::new(200.0, 20.0),
2235                    "…and its subtree must still be laid out: reading `dormant` \
2236                     from a widget that did not opt in would take the subtree \
2237                     out of the recursion",
2238                );
2239            }
2240        }
2241
2242        #[test]
2243        fn parking_the_focused_child_does_not_leave_focus_on_a_dormant_node() {
2244            // The backstop behind the pin. A culling parent is expected to keep
2245            // what the user is using, but if it parks it anyway, focus must not
2246            // survive the pass pointing at a node dispatch will refuse — a
2247            // keystroke into the void is worse than a focus loss the user can
2248            // see.
2249            let Rig {
2250                mut tree, id, park, ..
2251            } = tree_with(true);
2252            let kids = tree.children(id).to_vec();
2253            tree.focus(kids[0]);
2254            assert_eq!(tree.focused(), Some(kids[0]));
2255
2256            park.set(0b001);
2257            tree.layout(SizeProposal::exact(100.0, 100.0));
2258
2259            assert!(!tree.is_active(kids[0]));
2260            assert_eq!(
2261                tree.focused(),
2262                None,
2263                "focus must not point into a subtree this pass parked"
2264            );
2265            let _ = id;
2266        }
2267
2268        /// Parks the children whose bit is set in a mask no binding watches,
2269        /// so what runs its pass is whatever else needed one: here a child's
2270        /// own scroll handler, which writes the mask.
2271        #[derive(Debug)]
2272        struct ScrollCuller {
2273            kids: Vec<WidgetId>,
2274            park: Rc<Cell<u64>>,
2275        }
2276
2277        impl Widget for ScrollCuller {
2278            fn build(&mut self, ctx: &mut crate::build_context::BuildContext) -> Vec<WidgetId> {
2279                self.kids = (0..3)
2280                    .map(|i| {
2281                        let park = self.park.clone();
2282                        ctx.add(
2283                            FillWidget::new()
2284                                .background(teksilo_tokens::Color::RED)
2285                                .corner_radius(teksilo_tokens::CornerRadius::uniform(2.0))
2286                                .on_scroll(move |_event, _ctx| {
2287                                    park.set(1 << i);
2288                                    crate::event::EventResponse::Handled
2289                                }),
2290                        )
2291                    })
2292                    .collect();
2293                self.kids.clone()
2294            }
2295            fn layout_response(
2296                &self,
2297                _p: SizeProposal,
2298                _c: &crate::widget::LayoutContext,
2299            ) -> LayoutResponse {
2300                teksilo_canvas::Size::new(100.0, 60.0).into()
2301            }
2302            fn children(&self) -> Vec<WidgetId> {
2303                self.kids.clone()
2304            }
2305            fn culls_children(&self) -> bool {
2306                true
2307            }
2308            fn place_children(
2309                &self,
2310                bounds: Rect,
2311                _proposal: SizeProposal,
2312                children: &mut [WidgetPlacement],
2313                _ctx: &crate::widget::LayoutContext,
2314            ) {
2315                let mask = self.park.get();
2316                for placement in children.iter_mut() {
2317                    let Some(i) = self.kids.iter().position(|&k| k == placement.id) else {
2318                        continue;
2319                    };
2320                    placement.origin = teksilo_canvas::Point::new(0.0, i as f32 * 20.0);
2321                    placement.size = teksilo_canvas::Size::new(bounds.width, 20.0);
2322                    placement.dormant = mask & (1 << i) != 0;
2323                }
2324            }
2325        }
2326
2327        /// The rows the frame draws, by their top edge.
2328        fn drawn_rows(frame: &teksilo_canvas::RenderFrame) -> Vec<f32> {
2329            frame.shapes.iter().map(|shape| shape.screen[1]).collect()
2330        }
2331
2332        #[test]
2333        fn a_child_parked_in_a_pass_that_marked_nothing_for_paint_leaves_the_frame() {
2334            // A handled scroll marks its target for layout and nothing else.
2335            // When the culling parent then parks that target, the pass ends
2336            // with no active node marked for paint, which is the condition
2337            // under which a render replays the frame it cached: the parked
2338            // child's drawing with it, and a live picture's texture kept for
2339            // a widget nothing shows.
2340            let park = Rc::new(Cell::new(0));
2341            let mut tree = WidgetTree::new();
2342            let id = tree.add(ScrollCuller {
2343                kids: Vec::new(),
2344                park: park.clone(),
2345            });
2346            tree.layout(SizeProposal::exact(100.0, 60.0));
2347            assert_eq!(drawn_rows(&tree.render()), vec![0.0, 20.0, 40.0]);
2348            let kids = tree.children(id).to_vec();
2349
2350            let scroll_over = |tree: &mut WidgetTree, y: f32| {
2351                tree.dispatch_event(WidgetEvent::scroll_at(
2352                    crate::event::ScrollDelta::Lines { x: 0.0, y: -1.0 },
2353                    crate::event::Modifiers::NONE,
2354                    teksilo_canvas::Point::new(50.0, y),
2355                ));
2356                tree.layout(SizeProposal::exact(100.0, 60.0));
2357            };
2358            scroll_over(&mut tree, 30.0);
2359            assert!(!tree.is_active(kids[1]), "the culler parked the middle row");
2360            assert_eq!(
2361                drawn_rows(&tree.render()),
2362                vec![0.0, 40.0],
2363                "a parked child is not drawn, whatever marked the pass"
2364            );
2365
2366            // And back: the first row's handler clears the middle row's bit
2367            // and parks its own.
2368            scroll_over(&mut tree, 10.0);
2369            assert!(tree.is_active(kids[1]) && !tree.is_active(kids[0]));
2370            assert_eq!(drawn_rows(&tree.render()), vec![20.0, 40.0]);
2371        }
2372    }
2373}