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 for widget_id in to_rebuild {
378 self.rebuild_single_widget(widget_id);
379 }
380 // A rebuild destroys old child subtrees and allocates fresh
381 // WidgetIds, so the AccessKit tree shape changed — dirty the cached
382 // snapshot so the next `sync_accessibility` re-walks. This is the one
383 // place every `BindingLevel::Rebuild` consumer converges (data-view
384 // model updates via the binding registry AND `with_widget_mut(Rebuild)`
385 // via `apply_tree_mutations`, both draining the same `needs_rebuild`
386 // arena flag) — without this, an ordinary `ListModel::push()` leaves
387 // screen readers on a stale tree indefinitely.
388 self.a11y_dirty = true;
389 // Rebuild destroys old child subtrees and allocates fresh WidgetIds;
390 // drop any focus/hover state whose target is no longer valid so we
391 // don't dispatch to dead widgets on the next event.
392 self.revalidate_interaction_state(&mut *ops);
393 // ...but "no longer valid" must not mean "gone". If focus lived in the
394 // subtree we just rebuilt, the drop above kicked the user clean out of
395 // the widget they were in: a popover that re-scans its content when it
396 // opens throws away the row the popover itself had just focused, and the
397 // menu comes up with nothing focused — no arrow keys, no Enter. Put focus
398 // back inside that subtree, at the end of the layout pass (the fresh
399 // children have no bounds yet, and the focus-driven scroll-into-view
400 // needs them). A rebuild that never held focus, or one whose focused node
401 // survived it (the rebuild root itself is not destroyed), records nothing.
402 if self.focused.is_none()
403 && let Some(root) = focus_owner
404 {
405 self.pending_focus_restore = Some(root);
406 }
407 // A rebuild's `build()` may arm new animations (looping or
408 // one-shot) by calling `signal.animate_to(...)` /
409 // `animate_looping(...)` — these set `pending` on the signal
410 // but don't enter the scheduler until `process_pending_animations`
411 // runs again. The early-frame `process_pending_animations`
412 // (`layout_impl::layout_with_ops`) already ran *before* this
413 // rebuild, so without this second drain the animation would
414 // wait for the next frame; if the rebuild also cancelled
415 // existing scheduler entries (`cancel_by_widget` is called by
416 // `rebuild_single_widget`), the scheduler ends up empty, no
417 // frame deadline is set, and the freshly-armed animation
418 // *never* gets picked up — the user sees animations freeze
419 // after any state-driven rebuild that re-arms them
420 // (e.g. SceneView's drag-end rebuild re-arming PulsingDot
421 // loopers via `register_bindings`).
422 self.process_pending_animations();
423 }
424
425 /// Run the layout pass with the given size proposal, using
426 /// [`NoopWindowOps`](crate::window::NoopWindowOps). Handlers
427 /// triggered from drag_tick / tooltip activation / etc cannot
428 /// call `ctx.open_window(...)` from this path.
429 ///
430 /// `teksilo-app` calls [`layout_with_ops`](Self::layout_with_ops)
431 /// with a real sink so those handlers can open windows.
432 pub fn layout(&mut self, proposal: SizeProposal) {
433 let mut noop = crate::window::NoopWindowOps;
434 self.layout_with_ops(proposal, &mut noop);
435 }
436
437 /// Measure the intrinsic size of the primary (non-overlay) content root(s)
438 /// at `proposal` — e.g. `{ width: Some(w), height: None }` for the natural
439 /// height at a fixed width. Mirrors the overlay intrinsic pass below: it
440 /// calls the root's `layout_response` *directly* — NOT the
441 /// activation-ignoring `WidgetArena::measure_intrinsic` — so a
442 /// `visible_when(false)` / parked-`Switcher` descendant is excluded exactly
443 /// as the real layout excludes it. A size-to-content window is therefore
444 /// sized to what is actually shown. Computes sizes only (never writes
445 /// bounds), so it is safe to call right after a layout pass.
446 ///
447 /// Drives size-to-content windows (see
448 /// [`WindowConfig::size_to_content`](crate::window::WindowConfig::size_to_content)):
449 /// the native-window path has no in-tree overlay to size to content, so
450 /// `teksilo-app` measures the root here and resizes the OS window to fit.
451 /// Returns `None` if there is no active primary root; with more than one
452 /// active primary root the per-axis maximum is returned (size-to-content is
453 /// intended for single-primary-root windows).
454 pub fn measure_root_intrinsic(&self, proposal: SizeProposal) -> Option<teksilo_canvas::Size> {
455 let overlay_content_ids = self.overlay_manager.active_content_ids();
456 let base_theme = self.effective_theme.clone();
457 let mut result: Option<teksilo_canvas::Size> = None;
458 for root_id in self.arena.roots() {
459 if overlay_content_ids.contains(&root_id) || !self.arena.is_active(root_id) {
460 continue;
461 }
462 let resolved_theme = self.arena.resolve_theme(root_id, &base_theme);
463 let extras = crate::widget::LayoutExtras {
464 focused: self.focused,
465 // A measurement, not a pass: nothing is parked off the back of
466 // it, so there is nothing for an anchor to protect.
467 interaction_anchors: &[],
468 shortcut_registry: Some(&self.shortcut_registry),
469 overlay_manager: Some(&self.overlay_manager),
470 };
471 let ctx = LayoutContext {
472 theme: &resolved_theme,
473 layout_direction: self.layout_direction,
474 scale_factor: self.device_scale_factor,
475 text_scale: self.effective_text_scale,
476 text_backend: self.text_backend.as_ref(),
477 arena: Some(&self.arena),
478 extras: Some(extras),
479 stack_main_axis: None,
480 };
481 let Some(node) = self.arena.get(root_id) else {
482 continue;
483 };
484 // Direct `layout_response` (activation-respecting), like the overlay
485 // pass — dormant descendants fall out via `child_size` returning
486 // `None`, so we measure only what is actually shown.
487 let size = node.widget.layout_response(proposal, &ctx).size;
488 result = Some(match result {
489 Some(acc) => teksilo_canvas::Size::new(
490 acc.width.max(size.width),
491 acc.height.max(size.height),
492 ),
493 None => size,
494 });
495 }
496 result
497 }
498
499 /// Run the layout pass with the given size proposal, threading
500 /// the app's [`WindowOps`](crate::window::WindowOps) sink
501 /// through to drag_tick / tooltip / delayed-overlay handlers.
502 pub fn layout_with_ops(
503 &mut self,
504 proposal: SizeProposal,
505 ops: &mut dyn crate::window::WindowOps,
506 ) {
507 self.process_pending_animations();
508
509 let now = std::time::Instant::now();
510 // Deadline-driven wake-up: if a widget requested a future
511 // frame via `wake_at_handle()` and that deadline is now past,
512 // arm the frame tick so its effect runs on this layout pass.
513 // Used by the rich text editor's caret blink to avoid
514 // keeping winit in Poll mode.
515 if let Some(deadline) = self.pending_wake_at.get()
516 && deadline <= now
517 {
518 self.pending_wake_at.set(None);
519 self.frame_tick_requested.set(true);
520 }
521 self.advance_frame_tick(now);
522 // Ticked on the same clock the animations were *promoted* against
523 // (`process_pending_animations` immediately above reads it too). While
524 // the tree runs on real time that is `now`; while an automation
525 // operation has time taken over it is `sim_clock`, and ticking at
526 // `Instant::now()` there would hand every animation an elapsed time of
527 // the tree's whole wall-clock age and complete it on its first layout
528 // pass. The operation gives the clock back when it ends, rebasing the
529 // scheduler as it goes, so this reads the wall clock again from the
530 // next frame on — see `WidgetTree::resume_real_time`.
531 let animation_now = self.animation_clock();
532 self.animation_scheduler
533 .tick(animation_now, &self.arena, self.paint_epoch);
534
535 // Fire on_drag_tick on the current drop target, if any. Runs once
536 // per layout pass so widgets can implement per-frame behaviours
537 // (viewport-edge auto-scroll, spring-loaded folders) without
538 // depending on pointer events — crucial when the user holds the
539 // cursor still at the edge or over a collapsed branch.
540 self.process_drag_tick(&mut *ops);
541
542 self.process_state_changes(&mut *ops);
543 // A drag owns the pointer. `handle_pointer_move` is short-circuited for
544 // the duration, so a dwell armed just before the drag started would sit
545 // frozen at its hover origin and then mature here — popping a tooltip
546 // over the drag. Keep the timers cleared instead of letting them ripen.
547 if self.active_drag.is_some() {
548 self.tooltip_cancel_pending_dwell();
549 }
550 self.process_tooltips_real();
551 self.process_delayed_overlays_real(&mut *ops);
552 self.process_pointer_leave_overlays_real(&mut *ops);
553 self.process_auto_dismiss_overlays_real(&mut *ops);
554 self.process_overlay_fade_dismissals_real(&mut *ops);
555 // The show paths above may arm a fade animation via
556 // `attach_overlay_fade` (plain tooltips, delayed overlays).
557 // That sets `pending` on the opacity signal but does NOT
558 // register the animation with the scheduler — registration
559 // happens via `process_pending_animations`, which already ran
560 // earlier in this layout pass. Without a second drain here,
561 // the fade only enters the scheduler on the *next* layout
562 // pass, and for surfaces with no further wake source (plain
563 // tooltips, no dwell timer) `next_deadline` returns `None`
564 // and the event loop sleeps with the fade stuck at opacity 0
565 // — the tooltip is "shown" but invisible until an unrelated
566 // input event forces another layout pass.
567 self.process_pending_animations();
568 // Overlay / tooltip activation may have flipped widgets from
569 // dormant → active; if any of those had `needs_rebuild`
570 // pending (e.g. a shortcut rebind happened while the tooltip
571 // was hidden), drain them now so the freshly-visible surface
572 // shows fresh content in the *same* layout pass rather than
573 // waiting for another paint-triggering event.
574 self.process_pending_rebuilds(&mut *ops);
575
576 // Now that any data-driven rebuilds have torn down their old
577 // subtrees, drop any overlay whose content was destroyed out-of-
578 // band (e.g. clicking "mark all read" inside a notification
579 // popover rebuilds the bell that owns it). Without this the
580 // overlay lingers as an invisible click-blocker. Runs before the
581 // early-return so it takes effect even on otherwise-idle passes.
582 self.gc_orphaned_overlays();
583
584 self.arena.refresh_roots();
585
586 // Before the idle early-return, because this is precisely the case it
587 // would swallow: the user moved and nothing else did.
588 self.invalidate_culls_for_moved_interaction();
589
590 let proposal_changed = self.last_proposal != proposal;
591 self.last_proposal = proposal;
592
593 if !proposal_changed && !self.arena.any_needs_layout() {
594 return;
595 }
596
597 // Per-pass layout memoization: a widget's `layout_response` is a pure
598 // function of (state, proposal) within a pass, so memoizing across the
599 // main-then-cross queries that height-for-width negotiation issues keeps
600 // the pass O(n). Cleared here — once, dominating both the main-tree and
601 // overlay root recursions below — because geometry may change between
602 // passes. See `WidgetArena::cached_layout_response`.
603 self.arena.clear_layout_cache();
604
605 // `effective_theme` carries the user/OS text-scale multiplier baked into
606 // its typography, so every text widget measures at the scaled size.
607 let base_theme = self.effective_theme.clone();
608
609 let overlay_content_ids = self.overlay_manager.active_content_ids();
610 let roots: Vec<WidgetId> = self.arena.roots();
611 let focused = self.focused;
612 // Everything a park would take away from the user, gathered once so a
613 // culling container can ask
614 // `LayoutContext::for_each_interaction_ancestor` without the tree.
615 // Empty on an idle tree.
616 let interaction_anchors = self.collect_interaction_anchors();
617 // What the `culls_children` parents decided about their children
618 // during this walk — parked and woken alike. Settled after it, because
619 // parking goes through the tree-level door and both halves change the
620 // AccessKit tree.
621 let mut culled = CullTransitions::default();
622 for root_id in roots {
623 if overlay_content_ids.contains(&root_id) {
624 continue;
625 }
626 let extras = crate::widget::LayoutExtras {
627 focused,
628 interaction_anchors: &interaction_anchors,
629 shortcut_registry: Some(&self.shortcut_registry),
630 overlay_manager: Some(&self.overlay_manager),
631 };
632 layout_widget_recursive(
633 &mut self.arena,
634 root_id,
635 Rect::from_origin_size(Point::ZERO, proposal.resolve(0.0, 0.0)),
636 proposal,
637 &base_theme,
638 self.layout_direction,
639 self.device_scale_factor,
640 self.effective_text_scale,
641 self.text_backend.as_ref(),
642 Some(extras),
643 &mut culled,
644 );
645 }
646
647 let anchor_bounds = |id: WidgetId| -> Option<Rect> {
648 self.arena.is_active(id).then(|| self.arena.bounds(id))
649 };
650 // The window, less the platform safe area, less whatever is covering
651 // it. Both are `ZERO`/`None` unless something supplied them, so a
652 // desktop frame produces exactly the bare `(width, height)` this used
653 // to pass.
654 let viewport = self.overlay_viewport_for(teksilo_canvas::Size::new(
655 proposal.width.unwrap_or(800.0),
656 proposal.height.unwrap_or(600.0),
657 ));
658 self.overlay_manager
659 .position_overlays(anchor_bounds, viewport, self.layout_direction);
660 for content_id in &overlay_content_ids {
661 if !self.arena.is_active(*content_id) {
662 continue;
663 }
664 let overlay_id = self.overlay_manager.find_by_content(*content_id);
665 let intrinsic = {
666 let resolved_theme = self.arena.resolve_theme(*content_id, &base_theme);
667 let extras = crate::widget::LayoutExtras {
668 focused: self.focused,
669 interaction_anchors: &interaction_anchors,
670 shortcut_registry: Some(&self.shortcut_registry),
671 overlay_manager: Some(&self.overlay_manager),
672 };
673 let ctx = LayoutContext {
674 theme: &resolved_theme,
675 layout_direction: self.layout_direction,
676 scale_factor: self.device_scale_factor,
677 text_scale: self.effective_text_scale,
678 text_backend: self.text_backend.as_ref(),
679 arena: Some(&self.arena),
680 extras: Some(extras),
681 stack_main_axis: None,
682 };
683 let node = self
684 .arena
685 .get(*content_id)
686 .expect("content_id from active arena children");
687 node.widget
688 .layout_response(
689 SizeProposal {
690 width: None,
691 height: None,
692 },
693 &ctx,
694 )
695 .size
696 };
697 if let Some(overlay_id) = overlay_id {
698 self.overlay_manager
699 .set_content_bounds(overlay_id, intrinsic);
700 let anchor_bounds = |id: WidgetId| -> Option<Rect> {
701 self.arena.is_active(id).then(|| self.arena.bounds(id))
702 };
703 self.overlay_manager.position_overlays(
704 anchor_bounds,
705 viewport,
706 self.layout_direction,
707 );
708 }
709 let overlay_bounds = overlay_id
710 .and_then(|overlay_id| {
711 self.overlay_manager
712 .stack
713 .iter()
714 .find(|overlay| overlay.id == overlay_id)
715 .map(|overlay| overlay.bounds)
716 })
717 .unwrap_or(Rect::ZERO);
718 // Use the positioned overlay_bounds for layout, not the intrinsic
719 // size. For `Below` / `BelowPreferred` (and any other placement
720 // that inflates the overlay rect beyond the content's intrinsic
721 // size to match an anchor, e.g. a combo-box dropdown that must be
722 // at least as wide as its trigger), this lets the content widget
723 // actually fill the overlay rather than sitting as a narrow
724 // strip inside it. It carries the placements that *shrink* the
725 // rect just as well — `Above`/`BelowPreferred` to the room they
726 // found, `Centered`/`BottomCenter`/`ViewportCorner` to the usable
727 // area, `FullViewport` to the whole window — so the content is
728 // laid out at the rectangle it was actually given, whichever
729 // placement decided it.
730 let content_proposal = SizeProposal::exact(overlay_bounds.width, overlay_bounds.height);
731 let extras = crate::widget::LayoutExtras {
732 focused: self.focused,
733 interaction_anchors: &interaction_anchors,
734 shortcut_registry: Some(&self.shortcut_registry),
735 overlay_manager: Some(&self.overlay_manager),
736 };
737 layout_widget_recursive(
738 &mut self.arena,
739 *content_id,
740 overlay_bounds,
741 content_proposal,
742 &base_theme,
743 self.layout_direction,
744 self.device_scale_factor,
745 self.effective_text_scale,
746 self.text_backend.as_ref(),
747 Some(extras),
748 &mut culled,
749 );
750 }
751
752 // ── Settle what a culling parent decided ──────────────────────
753 // A widget that culls its children decides during layout which of them
754 // exist, and it can only decide once it knows its own bounds and — for
755 // a scene — the camera it is looking through. Waking has already
756 // happened inline, so a child brought back was laid out this pass;
757 // parking is here because it has to go through the tree-level door,
758 // which tells any pointer working inside the subtree that its
759 // interaction is over rather than leaving it holding a widget the
760 // dispatcher will no longer reach.
761 //
762 // Both halves land here, and neither is the special case. The
763 // accessibility walk skips dormant nodes, so an active↔dormant
764 // transition in EITHER direction changes the AT tree's shape; and
765 // `activation_signal` is the hook a native subview (a `WebView`'s
766 // `set_visible` bridge) hangs its own visibility on, so a queued
767 // `true` that nothing drains is a subview that never comes back. This
768 // is the same rule the `visible_when` sweep at the top of
769 // `process_state_changes` applies to `to_dormant` / `to_activate`;
770 // writing it for parking alone made waking a silent no-op that the
771 // usual probe cannot see, because a card waking *into* the viewport
772 // resizes from `Size::ZERO` and a resize dirties the tree on its own.
773 // A card that wakes and stays zero-sized — which is every card in the
774 // band `A11yOffScreenMode::ViewportPlusN` promises to enumerate — does
775 // not.
776 if !culled.is_empty() {
777 self.a11y_dirty = true;
778 // `revalidate_interaction_state` follows the parks immediately:
779 // focus must never survive a pass pointing at a node this just
780 // parked, because dispatch rejects inactive targets and a
781 // keystroke into the void is worse than a focus loss the user can
782 // see. A culling parent is expected to pin what the user is using
783 // (see `LayoutContext::for_each_interaction_ancestor`), so this is
784 // the backstop, not the plan.
785 let parked = !culled.park.is_empty();
786 for id in std::mem::take(&mut culled.park) {
787 self.park_subtree_with_ops(id, &mut *ops);
788 }
789 self.flush_activation_signals();
790 if parked {
791 self.revalidate_interaction_state(&mut *ops);
792 }
793 }
794
795 // Clear `needs_layout` for every active widget — layout just
796 // ran. `needs_rebuild` is NOT cleared here: `rebuild_single_widget`
797 // clears it for widgets it processes, and widgets whose rebuild
798 // was deferred (captured-pointer window) must keep the flag set
799 // so the next layout pass picks them up. Wiping it here caused
800 // a regression where a scroll-driven ListView rebuild, deferred
801 // during a scrollbar thumb drag, was silently dropped — the
802 // user saw the thumb move but the list view stayed frozen.
803 // Clear `needs_layout` on every active node. Mutation during
804 // iter — pull the snapshot via the reusable scratch.
805 self.arena.fill_active_ids(&mut self.active_ids_scratch);
806 let ids = std::mem::take(&mut self.active_ids_scratch);
807 for &id in &ids {
808 if let Some(node) = self.arena.get_mut(id) {
809 node.dirty.needs_layout = false;
810 }
811 }
812 self.active_ids_scratch = ids;
813
814 // Post-layout hover refresh. When a rebuild destroyed the
815 // hovered widget, `revalidate_interaction_state` cleared
816 // `hovered` to `None`. Now that widgets have fresh bounds
817 // from this layout pass, re-hit-test at the cached pointer
818 // position so the next wheel/pointer event routes to the
819 // widget the cursor is actually over. Without this, a
820 // virtualized list that materializes new rows under a
821 // stationary cursor would see the next `Scroll` fall through
822 // to `focused` and bubble to an ancestor scrollable.
823 // Hover recovery is the **hover owner**'s business: re-deriving hover
824 // from the primary would invent one on a touch-only device, where the
825 // primary is a finger and nothing hovers at all.
826 if self.hovered_id().is_none()
827 && let Some(pos) = self.hover_owner_position()
828 {
829 let new_target = self.hit_test(pos);
830 if new_target.is_some() {
831 if let Some(new) = new_target {
832 // Credited to the hover owner, whose cached position is
833 // what re-derived the target — no sample raised this.
834 let enter = WidgetEvent::PointerEnter {
835 pointer: self.hover_transition_pointer(),
836 };
837 self.dispatch_to_widget(new, &enter, &mut *ops);
838 // Seed the tooltip dwell too, exactly as `handle_pointer_move`
839 // pairs these two. The rebuild replaced the anchor's tooltip
840 // entry with a fresh one whose `hover_start` is `None`, and
841 // the pointer is not going to move again — so without this the
842 // widget's tooltip is unreachable for the rest of the hover.
843 self.tooltip_pointer_enter(new);
844 }
845 self.set_hovered(new_target);
846 }
847 }
848
849 // Post-layout focus refresh — the symmetric case to the hover refresh
850 // above. A rebuild destroyed the focused widget, so
851 // `revalidate_interaction_state` cleared `focused` to `None`; the
852 // subtree that owned it was recorded as `pending_focus_restore`. Now
853 // that its fresh children have bounds from this layout pass, land focus
854 // back inside it, so a rebuild keeps focus in the subtree that had it
855 // rather than dumping it out of the widget entirely.
856 //
857 // Deliberately conservative: only when nothing else has taken focus in
858 // the meantime, only into a subtree that is still active (a rebuild that
859 // also went dormant, e.g. a popover closing, must NOT drag focus back
860 // into hidden content — its own dismiss path restores focus to the
861 // trigger), and only if it still has somewhere to put it. Otherwise focus
862 // stays `None`, exactly as before.
863 if let Some(root) = self.pending_focus_restore.take()
864 && self.focused.is_none()
865 && self.arena.is_active(root)
866 && let Some(target) = self.first_focusable_descendant(root)
867 {
868 self.focus_ops(target, &mut *ops);
869 }
870
871 // A widget that changed size may have re-wrapped its text, and a
872 // wrapped label carries one accessibility text run per visual line
873 // — a different set of runs, not the same set somewhere else. Pure
874 // translations stay recorded on the arena for `sync_accessibility`
875 // to absorb without walking.
876 if self.arena.take_a11y_resized() {
877 self.a11y_dirty = true;
878 }
879
880 // Backstop. Every dismissal path is supposed to drain its callbacks
881 // itself — `dormant_dismissed_content` for the ones that park content,
882 // `gc_orphaned_overlays` for the one whose content is already gone —
883 // because draining *there* is what keeps the documented ordering
884 // (during dismissal, before focus returns to the trigger). This exists
885 // for the path nobody thought of: a parked callback that reaches the
886 // end of a frame has been stranded, and running it a frame late beats
887 // never. Costs a bool test when the queue is empty, which is always.
888 self.run_pending_dismiss_callbacks(&mut *ops);
889 }
890}
891
892/// What the `culls_children` parents in one layout walk decided about their
893/// children, collected here because settling either half needs `WidgetTree`,
894/// which the free function below does not have.
895///
896/// Both halves are recorded, not just the parks. A wake is applied inline —
897/// the child has to be laid out in the same pass or a camera that jumps shows
898/// a hole — but it still owes the tree the two things a park owes it: an
899/// invalidated AccessKit cache and a drained `activation_signal` queue.
900#[derive(Default)]
901pub(super) struct CullTransitions {
902 /// Children to park, applied once the walk is over so parking can go
903 /// through `WidgetTree::park_subtree_with_ops`.
904 park: Vec<WidgetId>,
905 /// Children already woken during the walk, kept so the settle step can
906 /// tell "nothing happened" from "something came back".
907 woke: Vec<WidgetId>,
908}
909
910impl CullTransitions {
911 /// Whether this walk changed any child's activation, either way.
912 fn is_empty(&self) -> bool {
913 self.park.is_empty() && self.woke.is_empty()
914 }
915}
916
917/// Recursive layout pass operating on the arena directly (avoids borrow conflicts).
918#[allow(clippy::too_many_arguments)]
919fn layout_widget_recursive(
920 arena: &mut WidgetArena,
921 id: WidgetId,
922 parent_bounds: Rect,
923 proposal: SizeProposal,
924 base_theme: &crate::styles::Theme,
925 layout_direction: crate::environment::LayoutDirection,
926 scale_factor: f32,
927 text_scale: f32,
928 text_backend: Option<&std::rc::Rc<std::cell::RefCell<dyn teksilo_canvas::TextBackend>>>,
929 extras: Option<crate::widget::LayoutExtras<'_>>,
930 // Every activation change a culling parent asked for during this walk.
931 // Settled by the caller once the walk is over.
932 culled: &mut CullTransitions,
933) {
934 if !arena.is_active(id) {
935 return;
936 }
937
938 let resolved_theme = arena.resolve_theme(id, base_theme);
939
940 let desired_size = {
941 let ctx = LayoutContext {
942 theme: &resolved_theme,
943 layout_direction,
944 scale_factor,
945 text_scale,
946 text_backend,
947 arena: Some(arena),
948 extras,
949 stack_main_axis: None,
950 };
951 arena
952 .cached_layout_response(id, proposal, &ctx)
953 .map(|r| r.size)
954 .unwrap_or(teksilo_canvas::Size::ZERO)
955 };
956
957 let bounds = Rect::new(
958 parent_bounds.x,
959 parent_bounds.y,
960 proposal.width.unwrap_or(desired_size.width),
961 proposal.height.unwrap_or(desired_size.height),
962 );
963 let previous = arena.get_mut(id).and_then(|node| {
964 let previous = node.bounds;
965 (previous != bounds).then(|| {
966 node.cached_paint = None;
967 node.dirty.needs_paint = true;
968 node.bounds = bounds;
969 previous
970 })
971 });
972 if let Some(previous) = previous {
973 arena.note_bounds_change(id, previous, bounds);
974 }
975
976 let child_ids: Vec<WidgetId> = arena.children(id).to_vec();
977 // A widget that culls its children is handed the dormant ones too — it is
978 // the only way it can ask for one back, having parked it. Every other
979 // widget sees its active children and nothing else, exactly as before.
980 let culls_children = arena
981 .get(id)
982 .is_some_and(|node| node.widget.culls_children());
983 let mut placements: Vec<WidgetPlacement> = child_ids
984 .iter()
985 .copied()
986 .filter_map(|child_id| {
987 let active = arena.is_active(child_id);
988 (active || culls_children).then_some(WidgetPlacement {
989 id: child_id,
990 origin: bounds.origin(),
991 size: bounds.size(),
992 dormant: !active,
993 })
994 })
995 .collect();
996
997 // `place_children` is a widget's ONLY hook that receives its final,
998 // parent-assigned `bounds`, so it runs for EVERY active widget on every
999 // pass — including leaves, which get an empty `placements` slice. A widget
1000 // whose paint depends on where the parent put it (a scene folding its
1001 // origin into a view transform, a text engine sizing its viewport) can then
1002 // read its bounds during *layout*, which is the only point early enough:
1003 // the render walker pushes node-level transform scopes before `paint` runs.
1004 {
1005 let ctx = LayoutContext {
1006 theme: &resolved_theme,
1007 layout_direction,
1008 scale_factor,
1009 text_scale,
1010 text_backend,
1011 arena: Some(arena),
1012 extras,
1013 stack_main_axis: None,
1014 };
1015 let node = arena.get(id).expect("widget id is active in arena");
1016 node.widget
1017 .place_children(bounds, proposal, &mut placements, &ctx);
1018 }
1019
1020 for placement in &placements {
1021 if culls_children {
1022 // Apply the parent's decision before anything reads the child's
1023 // state. Waking is immediate — the child is laid out below, this
1024 // pass, so a camera that jumps shows no hole. Parking is recorded
1025 // and applied once the walk is over, because it has to go through
1026 // the tree-level door (`WidgetTree::park_subtree_with_ops`) to
1027 // tell any pointer working inside that its interaction is over.
1028 // Either way the child's bounds are written first, so a parked
1029 // card keeps the coordinate that `scroll_into_view` and
1030 // focus-follow read.
1031 let active = arena.is_active(placement.id);
1032 if !placement.dormant && !active {
1033 arena.activate(placement.id);
1034 // `activate` only *queues* the `(id, true)` transition; the
1035 // caller's settle step drains it. Recorded so that step can
1036 // run at all — a pass that woke a child and parked none used
1037 // to leave the queue and the AT cache untouched.
1038 culled.woke.push(placement.id);
1039 } else if placement.dormant && active {
1040 culled.park.push(placement.id);
1041 }
1042 }
1043
1044 let child_bounds = Rect::from_origin_size(placement.origin, placement.size);
1045 let previous = arena.get_mut(placement.id).and_then(|child_node| {
1046 let previous = child_node.bounds;
1047 (previous != child_bounds).then(|| {
1048 child_node.cached_paint = None;
1049 child_node.dirty.needs_paint = true;
1050 child_node.bounds = child_bounds;
1051 previous
1052 })
1053 });
1054 if let Some(previous) = previous {
1055 arena.note_bounds_change(placement.id, previous, child_bounds);
1056 }
1057
1058 // Gated on `culls_children`, because that is the contract: for every
1059 // other widget `dormant` arrives `false` and is not read back, and a
1060 // widget that set it anyway must not be able to take a child out of
1061 // the pass by writing a field it was told does nothing.
1062 if culls_children && placement.dormant {
1063 // Nothing below a parked child is laid out, painted, walked for
1064 // accessibility or reachable by Tab. That is the whole point.
1065 continue;
1066 }
1067
1068 let child_proposal = SizeProposal::exact(placement.size.width, placement.size.height);
1069 let grandchild_ids: Vec<WidgetId> = arena.children(placement.id).to_vec();
1070 if !grandchild_ids.is_empty() {
1071 layout_widget_recursive(
1072 arena,
1073 placement.id,
1074 child_bounds,
1075 child_proposal,
1076 base_theme,
1077 layout_direction,
1078 scale_factor,
1079 text_scale,
1080 text_backend,
1081 extras,
1082 culled,
1083 );
1084 } else {
1085 // A childless child is never visited by the recursion above, so
1086 // hand it its final bounds here — with an empty `placements` slice.
1087 //
1088 // Deliberately NOT a `layout_widget_recursive` call: that would
1089 // re-measure the leaf against a fresh `exact` proposal (a memo miss,
1090 // since the parent measured it under a different proposal), adding a
1091 // redundant `layout_response` per leaf on every pass.
1092 let ctx = LayoutContext {
1093 theme: &resolved_theme,
1094 layout_direction,
1095 scale_factor,
1096 text_scale,
1097 text_backend,
1098 arena: Some(arena),
1099 extras,
1100 stack_main_axis: None,
1101 };
1102 let node = arena.get(placement.id).expect("child id is active");
1103 node.widget
1104 .place_children(child_bounds, child_proposal, &mut [], &ctx);
1105 }
1106 }
1107}
1108
1109#[cfg(test)]
1110mod tests {
1111 use super::*;
1112 use crate::test_widgets::{FillWidget, InsetWidget, StackWidget};
1113 use teksilo_canvas::Size;
1114 use teksilo_tokens::Color;
1115
1116 /// A leaf of a fixed intrinsic size, so a `Centered` overlay has something
1117 /// to centre.
1118 #[derive(Debug)]
1119 struct Sized(f32, f32);
1120
1121 impl Widget for Sized {
1122 fn layout_response(
1123 &self,
1124 _proposal: SizeProposal,
1125 _ctx: &LayoutContext,
1126 ) -> crate::widget::LayoutResponse {
1127 Size::new(self.0, self.1).into()
1128 }
1129 }
1130
1131 fn tree_with_centred_modal(content_height: f32) -> (WidgetTree, crate::overlay::OverlayId) {
1132 let mut tree = WidgetTree::new();
1133 let anchor = tree.add(FillWidget::new());
1134 let content = tree.add(Sized(200.0, content_height));
1135 let id = tree.show_overlay(crate::overlay::OverlayRequest {
1136 content_id: content,
1137 anchor,
1138 placement: crate::overlay::OverlayPlacement::Centered,
1139 dismiss: crate::overlay::DismissBehavior::Manual,
1140 layer: crate::overlay::OverlayLayer::InTree,
1141 parent_overlay: None,
1142 on_dismiss: None,
1143 fade_duration: None,
1144 });
1145 (tree, id)
1146 }
1147
1148 /// The supply this package exists to add: with nothing covering the window
1149 /// and no safe area, the viewport is the whole window — byte for byte the
1150 /// bare `(width, height)` tuple that used to be passed.
1151 #[test]
1152 fn a_bare_window_is_usable_to_its_last_pixel() {
1153 let (mut tree, id) = tree_with_centred_modal(100.0);
1154 tree.layout(SizeProposal::exact(400.0, 300.0));
1155 assert_eq!(tree.usable_viewport(), Rect::new(0.0, 0.0, 400.0, 300.0));
1156 let bounds = tree.overlay_content_bounds(id).expect("placed");
1157 assert_eq!(bounds.y, 100.0, "centred in 300: (300 - 100) / 2");
1158 }
1159
1160 /// A soft keyboard covering the bottom band shrinks the viewport, and the
1161 /// modal recomputes against what is left instead of centring behind it.
1162 #[test]
1163 fn an_occluding_band_shrinks_the_viewport_and_moves_the_modal() {
1164 let (mut tree, id) = tree_with_centred_modal(100.0);
1165 // The bottom 140 of a 300-tall window: a keyboard.
1166 tree.set_occluded_inset(Some(Rect::new(0.0, 160.0, 400.0, 140.0)));
1167 tree.layout(SizeProposal::exact(400.0, 300.0));
1168
1169 assert_eq!(
1170 tree.usable_viewport(),
1171 Rect::new(0.0, 0.0, 400.0, 160.0),
1172 "the largest free slab is the band above the keyboard"
1173 );
1174 let bounds = tree.overlay_content_bounds(id).expect("placed");
1175 assert_eq!(bounds.y, 30.0, "centred in 160: (160 - 100) / 2");
1176 assert!(
1177 bounds.y + bounds.height <= 160.0,
1178 "and the whole modal clears the keyboard"
1179 );
1180 }
1181
1182 /// When the content is taller than what is left, centring would push it off
1183 /// the top. It pins to the top of the usable area instead, so the first
1184 /// line stays reachable and the rest is scrolled to.
1185 #[test]
1186 fn a_modal_taller_than_the_usable_area_pins_to_its_top() {
1187 let (mut tree, id) = tree_with_centred_modal(240.0);
1188 tree.set_occluded_inset(Some(Rect::new(0.0, 160.0, 400.0, 140.0)));
1189 tree.layout(SizeProposal::exact(400.0, 300.0));
1190 let bounds = tree.overlay_content_bounds(id).expect("placed");
1191 assert_eq!(bounds.y, 0.0, "pinned to the top of the usable band");
1192 }
1193
1194 /// A safe area does the same for the reason a notch exists.
1195 #[test]
1196 fn a_safe_area_insets_the_viewport() {
1197 let (mut tree, id) = tree_with_centred_modal(100.0);
1198 tree.set_safe_area(teksilo_canvas::EdgeInsets {
1199 top: 40.0,
1200 bottom: 20.0,
1201 leading: 10.0,
1202 trailing: 10.0,
1203 });
1204 tree.layout(SizeProposal::exact(400.0, 300.0));
1205 assert_eq!(tree.usable_viewport(), Rect::new(10.0, 40.0, 380.0, 240.0));
1206 let bounds = tree.overlay_content_bounds(id).expect("placed");
1207 assert_eq!(bounds.y, 40.0 + (240.0 - 100.0) / 2.0);
1208 }
1209
1210 /// The scrim is deliberately not inset: one that respected the safe area
1211 /// would leave the notch undimmed and the content behind it legible.
1212 #[test]
1213 fn the_supply_does_not_move_the_root_layout() {
1214 // Occlusion reaches overlay placement and nothing else. A keyboard
1215 // rising must not reflow the document behind it — that is a scroll, not
1216 // a resize, and this is where the difference is decided.
1217 let mut tree = WidgetTree::new();
1218 let root = tree.add(FillWidget::new());
1219 tree.set_occluded_inset(Some(Rect::new(0.0, 160.0, 400.0, 140.0)));
1220 tree.set_safe_area(teksilo_canvas::EdgeInsets {
1221 top: 40.0,
1222 bottom: 0.0,
1223 leading: 0.0,
1224 trailing: 0.0,
1225 });
1226 tree.layout(SizeProposal::exact(400.0, 300.0));
1227 assert_eq!(
1228 tree.bounds(root),
1229 Rect::new(0.0, 0.0, 400.0, 300.0),
1230 "the root still owns the whole window"
1231 );
1232 }
1233
1234 /// A pending soft-keyboard request is recorded on the tree and taken
1235 /// exactly once, by the app layer, after its IME reconcile.
1236 #[test]
1237 fn a_soft_keyboard_request_is_taken_once() {
1238 let mut tree = WidgetTree::new();
1239 assert_eq!(tree.take_soft_keyboard_request(), None);
1240 tree.request_soft_keyboard(true);
1241 assert_eq!(tree.take_soft_keyboard_request(), Some(true));
1242 assert_eq!(
1243 tree.take_soft_keyboard_request(),
1244 None,
1245 "a request is a one-shot; a second take must not re-ask"
1246 );
1247 }
1248
1249 /// A leaf that records the bounds `place_children` hands it, and how often.
1250 #[derive(Debug, Clone, Default)]
1251 struct BoundsRecorder {
1252 seen: std::rc::Rc<std::cell::RefCell<Vec<Rect>>>,
1253 }
1254
1255 impl Widget for BoundsRecorder {
1256 fn layout_response(
1257 &self,
1258 proposal: SizeProposal,
1259 _ctx: &LayoutContext,
1260 ) -> crate::widget::LayoutResponse {
1261 Size::new(
1262 proposal.width.unwrap_or(10.0),
1263 proposal.height.unwrap_or(10.0),
1264 )
1265 .into()
1266 }
1267
1268 fn place_children(
1269 &self,
1270 bounds: Rect,
1271 _proposal: SizeProposal,
1272 children: &mut [WidgetPlacement],
1273 _ctx: &LayoutContext,
1274 ) {
1275 assert!(
1276 children.is_empty(),
1277 "a leaf must be handed an empty placements slice"
1278 );
1279 self.seen.borrow_mut().push(bounds);
1280 }
1281 }
1282
1283 /// The invariant `SceneView` (and both text engines) depend on: a widget with
1284 /// NO children still gets `place_children`, carrying its final bounds.
1285 ///
1286 /// Before this was guaranteed, the walker skipped `place_children` whenever
1287 /// there was nothing to place, so a leaf could only discover its bounds in
1288 /// `paint`. That is too late for anything the renderer consumes *before*
1289 /// paint — a `SceneView` folds `bounds.origin` into the transform scope the
1290 /// walker pushes around its subtree, so a scene holding only lightweight
1291 /// items (hence no arena children) painted its content offset by
1292 /// `-bounds.origin`, an error that scaled with zoom.
1293 #[test]
1294 fn a_childless_widget_still_receives_its_bounds() {
1295 let mut tree = WidgetTree::new();
1296 let leaf = BoundsRecorder::default();
1297 let seen = leaf.seen.clone();
1298
1299 // Nested inside an inset container, so a correct origin is non-zero and a
1300 // stale/zero origin cannot pass by accident.
1301 let leaf_id = tree.add(leaf);
1302 let _root = tree.add(InsetWidget::new(12.0).set_child(leaf_id));
1303 tree.layout(SizeProposal::exact(200.0, 100.0));
1304
1305 let bounds = seen.borrow();
1306 assert_eq!(
1307 bounds.len(),
1308 1,
1309 "the leaf must be placed exactly once per layout pass, got {bounds:?}"
1310 );
1311 assert_eq!(
1312 (bounds[0].x, bounds[0].y),
1313 (12.0, 12.0),
1314 "the leaf must receive its real, parent-assigned origin"
1315 );
1316 assert_eq!(
1317 (bounds[0].width, bounds[0].height),
1318 (176.0, 76.0),
1319 "the leaf must receive its real, parent-assigned size"
1320 );
1321 }
1322
1323 /// The same guarantee at the root: a tree whose root IS a leaf.
1324 #[test]
1325 fn a_childless_root_still_receives_its_bounds() {
1326 let mut tree = WidgetTree::new();
1327 let leaf = BoundsRecorder::default();
1328 let seen = leaf.seen.clone();
1329 let _id = tree.add(leaf);
1330 tree.layout(SizeProposal::exact(320.0, 240.0));
1331
1332 let bounds = seen.borrow();
1333 assert_eq!(bounds.len(), 1, "root leaf must be placed once");
1334 assert_eq!((bounds[0].width, bounds[0].height), (320.0, 240.0));
1335 }
1336
1337 #[derive(Debug)]
1338 struct ShrinkWrapContainer {
1339 child: WidgetId,
1340 inset: f32,
1341 }
1342
1343 impl Widget for ShrinkWrapContainer {
1344 fn layout_response(
1345 &self,
1346 _proposal: SizeProposal,
1347 ctx: &LayoutContext,
1348 ) -> crate::widget::LayoutResponse {
1349 let child_size = ctx
1350 .child_size(self.child, SizeProposal::unspecified())
1351 .unwrap_or(Size::ZERO);
1352 Size::new(
1353 child_size.width + self.inset * 2.0,
1354 child_size.height + self.inset * 2.0,
1355 )
1356 .into()
1357 }
1358
1359 fn place_children(
1360 &self,
1361 bounds: Rect,
1362 _proposal: SizeProposal,
1363 children: &mut [WidgetPlacement],
1364 _ctx: &LayoutContext,
1365 ) {
1366 for child in children.iter_mut() {
1367 child.origin = Point::new(bounds.x + self.inset, bounds.y + self.inset);
1368 child.size = Size::new(
1369 (bounds.width - self.inset * 2.0).max(0.0),
1370 (bounds.height - self.inset * 2.0).max(0.0),
1371 );
1372 }
1373 }
1374
1375 fn children(&self) -> Vec<WidgetId> {
1376 vec![self.child]
1377 }
1378 }
1379
1380 // ── Per-pass layout memoization cache (Part C) ──────────────────────────
1381
1382 /// A childless leaf that counts how many times `layout_response` runs and
1383 /// can opt out of caching. The driver does not recurse into a childless
1384 /// leaf's placement, so the only calls come from a parent's `child_size`
1385 /// queries — making the count a precise probe of the cache.
1386 #[derive(Debug)]
1387 struct CountingLeaf {
1388 calls: std::rc::Rc<std::cell::Cell<u32>>,
1389 cacheable: bool,
1390 }
1391
1392 impl Widget for CountingLeaf {
1393 fn layout_response(
1394 &self,
1395 _proposal: SizeProposal,
1396 _ctx: &LayoutContext,
1397 ) -> crate::widget::LayoutResponse {
1398 self.calls.set(self.calls.get() + 1);
1399 Size::new(50.0, 20.0).into()
1400 }
1401 fn cacheable_layout(&self) -> bool {
1402 self.cacheable
1403 }
1404 }
1405
1406 /// Queries its single child with the *same* proposal in both
1407 /// `layout_response` and `place_children` — the pattern real stacks use
1408 /// for height-for-width. With caching the child computes once; without it,
1409 /// twice.
1410 #[derive(Debug)]
1411 struct DoubleQueryContainer {
1412 child: WidgetId,
1413 }
1414
1415 impl Widget for DoubleQueryContainer {
1416 fn layout_response(
1417 &self,
1418 _proposal: SizeProposal,
1419 ctx: &LayoutContext,
1420 ) -> crate::widget::LayoutResponse {
1421 ctx.child_size(self.child, SizeProposal::exact(50.0, 20.0))
1422 .unwrap_or(Size::ZERO)
1423 .into()
1424 }
1425 fn place_children(
1426 &self,
1427 bounds: Rect,
1428 _proposal: SizeProposal,
1429 children: &mut [WidgetPlacement],
1430 ctx: &LayoutContext,
1431 ) {
1432 // Second query with the identical proposal.
1433 let _ = ctx.child_size(self.child, SizeProposal::exact(50.0, 20.0));
1434 for child in children.iter_mut() {
1435 child.origin = bounds.origin();
1436 child.size = bounds.size();
1437 }
1438 }
1439 fn children(&self) -> Vec<WidgetId> {
1440 vec![self.child]
1441 }
1442 }
1443
1444 #[test]
1445 fn cache_dedupes_identical_child_queries_within_a_pass() {
1446 let calls = std::rc::Rc::new(std::cell::Cell::new(0));
1447 let mut tree = WidgetTree::new();
1448 let leaf = tree.add(CountingLeaf {
1449 calls: calls.clone(),
1450 cacheable: true,
1451 });
1452 let _root = tree.add(DoubleQueryContainer { child: leaf });
1453 tree.layout(SizeProposal::exact(100.0, 50.0));
1454 // Two identical `exact(50,20)` queries (layout_response + place_children)
1455 // collapse to one real call; the driver does not recurse into the
1456 // childless leaf.
1457 assert_eq!(calls.get(), 1, "cacheable leaf should be computed once");
1458 }
1459
1460 #[test]
1461 fn cache_opt_out_recomputes_every_query() {
1462 let calls = std::rc::Rc::new(std::cell::Cell::new(0));
1463 let mut tree = WidgetTree::new();
1464 let leaf = tree.add(CountingLeaf {
1465 calls: calls.clone(),
1466 cacheable: false,
1467 });
1468 let _root = tree.add(DoubleQueryContainer { child: leaf });
1469 tree.layout(SizeProposal::exact(100.0, 50.0));
1470 assert_eq!(
1471 calls.get(),
1472 2,
1473 "opt-out leaf must run on every query (side effects preserved)"
1474 );
1475 }
1476
1477 #[test]
1478 fn cache_is_cleared_between_passes() {
1479 let calls = std::rc::Rc::new(std::cell::Cell::new(0));
1480 let mut tree = WidgetTree::new();
1481 let leaf = tree.add(CountingLeaf {
1482 calls: calls.clone(),
1483 cacheable: true,
1484 });
1485 let _root = tree.add(DoubleQueryContainer { child: leaf });
1486 tree.layout(SizeProposal::exact(100.0, 50.0));
1487 // A second pass with a different proposal must re-run layout — proving
1488 // the cache is per-pass, not stale across passes (the `exact(50,20)`
1489 // child key is identical between passes).
1490 tree.layout(SizeProposal::exact(120.0, 60.0));
1491 assert_eq!(
1492 calls.get(),
1493 2,
1494 "each pass recomputes; cache cleared per pass"
1495 );
1496 }
1497
1498 // ── measure_intrinsic (Primitive 2) ─────────────────────────────────────
1499
1500 /// Probe: from its own `layout_response`, measures `target` two ways and
1501 /// stashes the results — the normal (activation-gated) query and the
1502 /// intrinsic (activation-ignoring) query.
1503 #[derive(Debug)]
1504 struct MeasureProbe {
1505 target: WidgetId,
1506 active_w: std::rc::Rc<std::cell::Cell<f32>>, // -1.0 == None
1507 intrinsic_w: std::rc::Rc<std::cell::Cell<f32>>,
1508 }
1509 impl Widget for MeasureProbe {
1510 fn layout_response(
1511 &self,
1512 p: SizeProposal,
1513 ctx: &LayoutContext,
1514 ) -> crate::widget::LayoutResponse {
1515 // Measure intrinsic FIRST, then the normal gated query: if the
1516 // measure had polluted the cache, the gated query could wrongly
1517 // return a size for the dormant target. `exact` because FillWidget
1518 // fills its proposal (it has no intrinsic size of its own).
1519 let probe = SizeProposal::exact(120.0, 30.0);
1520 let intrinsic = ctx
1521 .measure_intrinsic(self.target, probe)
1522 .map(|s| s.width)
1523 .unwrap_or(-1.0);
1524 let active = ctx
1525 .child_size(self.target, probe)
1526 .map(|s| s.width)
1527 .unwrap_or(-1.0);
1528 self.intrinsic_w.set(intrinsic);
1529 self.active_w.set(active);
1530 p.resolve(0.0, 0.0).into()
1531 }
1532 fn cacheable_layout(&self) -> bool {
1533 false
1534 }
1535 }
1536
1537 #[test]
1538 fn measure_intrinsic_sees_a_dormant_widget_normal_query_does_not() {
1539 let active = std::rc::Rc::new(std::cell::Cell::new(0.0));
1540 let intrinsic = std::rc::Rc::new(std::cell::Cell::new(0.0));
1541 let mut tree = WidgetTree::new();
1542 let leaf = tree.add(FillWidget::new());
1543 tree.set_dormant(leaf);
1544 let _probe = tree.add(MeasureProbe {
1545 target: leaf,
1546 active_w: active.clone(),
1547 intrinsic_w: intrinsic.clone(),
1548 });
1549 tree.layout(SizeProposal::exact(200.0, 50.0));
1550
1551 // measure_intrinsic measures the dormant widget (FillWidget fills the
1552 // 120px probe)…
1553 assert!(
1554 (intrinsic.get() - 120.0).abs() < 0.01,
1555 "measure_intrinsic should size the dormant widget, got {}",
1556 intrinsic.get()
1557 );
1558 // …and the normal gated query (run AFTER) still returns None — proving
1559 // the measure bypassed, and did not seed, the per-pass cache.
1560 assert_eq!(
1561 active.get(),
1562 -1.0,
1563 "child_size must stay None for a dormant widget (no cache pollution)"
1564 );
1565 }
1566
1567 /// A box whose height is driven by a signal and whose width echoes the
1568 /// proposed width (height-for-width) — models a widget (e.g. a `MessageBox`
1569 /// "Show details" expander) whose intrinsic height changes with content.
1570 /// Echoing the width lets a fixed-width intrinsic measurement be exercised.
1571 #[derive(Debug)]
1572 struct SignalBox {
1573 h: crate::signal::Signal<f32>,
1574 }
1575 impl Widget for SignalBox {
1576 fn layout_response(
1577 &self,
1578 p: SizeProposal,
1579 _ctx: &LayoutContext,
1580 ) -> crate::widget::LayoutResponse {
1581 teksilo_canvas::Size::new(p.width.unwrap_or(0.0), self.h.get()).into()
1582 }
1583 fn cacheable_layout(&self) -> bool {
1584 false
1585 }
1586 }
1587
1588 /// Sums the ACTIVE children's heights via `child_size` (which returns
1589 /// `None` for a dormant child, so a hidden child contributes nothing) —
1590 /// lets a test assert size-to-content excludes dormant subtrees.
1591 #[derive(Debug)]
1592 struct VSumBox {
1593 children: Vec<WidgetId>,
1594 }
1595 impl Widget for VSumBox {
1596 fn layout_response(
1597 &self,
1598 p: SizeProposal,
1599 ctx: &LayoutContext,
1600 ) -> crate::widget::LayoutResponse {
1601 let h: f32 = self
1602 .children
1603 .iter()
1604 .filter_map(|&c| ctx.child_size(c, p))
1605 .map(|s| s.height)
1606 .sum();
1607 teksilo_canvas::Size::new(p.width.unwrap_or(0.0), h).into()
1608 }
1609 fn children(&self) -> Vec<WidgetId> {
1610 self.children.clone()
1611 }
1612 }
1613
1614 #[test]
1615 fn measure_root_intrinsic_honors_fixed_width_and_tracks_content() {
1616 let h = crate::signal::Signal::new(140.0);
1617 let mut tree = WidgetTree::new();
1618 let _root = tree.add(SignalBox { h: h.clone() });
1619 // Lay the root out constrained to a fixed native-modal size.
1620 tree.layout(SizeProposal::exact(460.0, 140.0));
1621
1622 // Intrinsic measurement at a fixed width / unbounded height reports the
1623 // proposed width and the content's natural height — the size a
1624 // size-to-content window grows to, independent of the constrained pass.
1625 let m = tree
1626 .measure_root_intrinsic(SizeProposal {
1627 width: Some(460.0),
1628 height: None,
1629 })
1630 .expect("one active primary root");
1631 assert!(
1632 (m.width - 460.0).abs() < 0.01,
1633 "fixed width honored, got {}",
1634 m.width
1635 );
1636 assert!(
1637 (m.height - 140.0).abs() < 0.01,
1638 "natural height, got {}",
1639 m.height
1640 );
1641
1642 // A different fixed width flows through (the proposal really is used).
1643 let narrow = tree
1644 .measure_root_intrinsic(SizeProposal {
1645 width: Some(300.0),
1646 height: None,
1647 })
1648 .expect("root active");
1649 assert!(
1650 (narrow.width - 300.0).abs() < 0.01,
1651 "proposal width, got {}",
1652 narrow.width
1653 );
1654
1655 // Content growth (a "Show details" expander) is reflected.
1656 h.set(300.0);
1657 let grown = tree
1658 .measure_root_intrinsic(SizeProposal {
1659 width: Some(460.0),
1660 height: None,
1661 })
1662 .expect("root active");
1663 assert!(
1664 (grown.height - 300.0).abs() < 0.01,
1665 "grows with content, got {}",
1666 grown.height
1667 );
1668 }
1669
1670 #[test]
1671 fn measure_root_intrinsic_excludes_dormant_content() {
1672 let mut tree = WidgetTree::new();
1673 let shown = tree.add(SignalBox {
1674 h: crate::signal::Signal::new(200.0),
1675 });
1676 let hidden = tree.add(SignalBox {
1677 h: crate::signal::Signal::new(1000.0),
1678 });
1679 tree.set_dormant(hidden);
1680 let _root = tree.add(VSumBox {
1681 children: vec![shown, hidden],
1682 });
1683 tree.layout(SizeProposal::exact(460.0, 200.0));
1684
1685 // The dormant child must NOT contribute — a size-to-content window is
1686 // sized to what is actually shown. Regression guard for measuring via
1687 // `layout_response` (activation-respecting) rather than the
1688 // activation-ignoring `measure_intrinsic` (which would return 1200).
1689 let m = tree
1690 .measure_root_intrinsic(SizeProposal {
1691 width: Some(460.0),
1692 height: None,
1693 })
1694 .expect("one active primary root");
1695 assert!(
1696 (m.height - 200.0).abs() < 0.01,
1697 "dormant child must be excluded, got {}",
1698 m.height
1699 );
1700 }
1701
1702 #[test]
1703 fn single_widget_fills_proposal() {
1704 let mut tree = WidgetTree::new();
1705 let widget = tree.add(FillWidget::new().background(Color::RED));
1706 tree.layout(SizeProposal::exact(200.0, 40.0));
1707 let bounds = tree.bounds(widget);
1708 assert_eq!(bounds.width, 200.0);
1709 assert_eq!(bounds.height, 40.0);
1710 }
1711
1712 #[test]
1713 fn stack_children_overlap() {
1714 let mut tree = WidgetTree::new();
1715 let a = tree.add(FillWidget::new());
1716 let b = tree.add(FillWidget::new());
1717 let stack = tree.add(StackWidget::new().child(a).child(b));
1718 tree.layout(SizeProposal::exact(100.0, 50.0));
1719 let children = tree.children(stack);
1720 assert_eq!(children.len(), 2);
1721 let a_bounds = tree.bounds(children[0]);
1722 let b_bounds = tree.bounds(children[1]);
1723 assert_eq!(a_bounds.origin(), b_bounds.origin());
1724 assert_eq!(a_bounds.size(), b_bounds.size());
1725 }
1726
1727 #[test]
1728 fn inset_widget_insets_child() {
1729 let mut tree = WidgetTree::new();
1730 let child = tree.add(FillWidget::new());
1731 let parent = tree.add(InsetWidget::new(10.0).set_child(child));
1732 tree.layout(SizeProposal::exact(100.0, 50.0));
1733 let children = tree.children(parent);
1734 let child_bounds = tree.bounds(children[0]);
1735 assert_eq!(child_bounds.x, 10.0);
1736 assert_eq!(child_bounds.y, 10.0);
1737 assert_eq!(child_bounds.width, 80.0);
1738 assert_eq!(child_bounds.height, 30.0);
1739 }
1740
1741 #[test]
1742 fn recursive_layout_preserves_exact_parent_placement_for_containers() {
1743 let mut tree = WidgetTree::new();
1744 let leaf = tree.add(FillWidget::new());
1745 let shrink = tree.add(ShrinkWrapContainer {
1746 child: leaf,
1747 inset: 8.0,
1748 });
1749 let root = tree.add(StackWidget::new().child(shrink));
1750
1751 tree.layout(SizeProposal::exact(120.0, 80.0));
1752
1753 assert_eq!(tree.bounds(root), Rect::new(0.0, 0.0, 120.0, 80.0));
1754 assert_eq!(
1755 tree.bounds(shrink),
1756 Rect::new(0.0, 0.0, 120.0, 80.0),
1757 "child container should keep the exact size assigned by its parent"
1758 );
1759 assert_eq!(tree.bounds(leaf), Rect::new(8.0, 8.0, 104.0, 64.0));
1760 }
1761
1762 #[test]
1763 fn needs_paint_after_layout() {
1764 let mut tree = WidgetTree::new();
1765 tree.add(FillWidget::new());
1766 assert!(tree.needs_layout());
1767 tree.layout(SizeProposal::exact(100.0, 50.0));
1768 assert!(!tree.needs_layout());
1769 }
1770
1771 #[test]
1772 fn signal_binding_marks_widget_dirty_on_layout() {
1773 use crate::signal::Signal;
1774
1775 let mut tree = WidgetTree::new();
1776 let widget = tree.add(FillWidget::new().background(Color::RED));
1777 tree.layout(SizeProposal::exact(100.0, 50.0));
1778 tree.render();
1779
1780 assert!(!tree.needs_paint());
1781
1782 let visible = Signal::new(true);
1783 visible.bind_to(
1784 widget,
1785 tree.binding_registry(),
1786 crate::binding::BindingLevel::RepaintOnly,
1787 );
1788
1789 visible.set(false);
1790 tree.layout(SizeProposal::exact(100.0, 50.0));
1791 assert!(tree.needs_paint());
1792 }
1793
1794 /// `culls_children` as a framework primitive, without a scene.
1795 ///
1796 /// The mechanism is one field and two rules: a widget that opts in is
1797 /// handed every child, parked ones included, and whatever it leaves in
1798 /// `WidgetPlacement::dormant` is applied — cleared wakes in the same pass,
1799 /// set parks after it.
1800 mod culling_containers {
1801 use super::*;
1802 use crate::signal::Signal;
1803 use crate::widget::{LayoutResponse, WidgetPlacement};
1804 use crate::widget_builder::WidgetBuilder;
1805 use std::cell::Cell;
1806 use std::rc::Rc;
1807
1808 /// Parks every child whose index is set in the `park` bitmask, and
1809 /// reports how many children its `place_children` was handed.
1810 ///
1811 /// `park` is a `Signal` bound at `BindingLevel::Relayout` — the same
1812 /// level a `SceneView` binds its camera at — because that is what makes
1813 /// changing it run a pass at all: `layout_with_ops` returns early when
1814 /// the proposal is unchanged and nothing needs layout.
1815 #[derive(Debug)]
1816 struct Culler {
1817 kids: Vec<WidgetId>,
1818 park: Signal<u64>,
1819 seen: Rc<Cell<usize>>,
1820 opts_in: bool,
1821 /// Stop writing `dormant` at all, so what the framework pre-set
1822 /// there is what gets applied.
1823 ignore_dormant: Rc<Cell<bool>>,
1824 /// One per child, so "was this subtree recursed into" is
1825 /// observable and not merely inferred from the child's activation.
1826 grandkids: Rc<std::cell::RefCell<Vec<WidgetId>>>,
1827 /// How many times the culler has been asked to decide. The
1828 /// question "was the decision re-taken?" has no other witness — a
1829 /// re-run that reaches the same answer changes nothing else.
1830 passes: Rc<Cell<usize>>,
1831 }
1832
1833 impl Culler {
1834 fn new(park: Signal<u64>, seen: Rc<Cell<usize>>, opts_in: bool) -> Self {
1835 Self {
1836 kids: Vec::new(),
1837 park,
1838 seen,
1839 opts_in,
1840 ignore_dormant: Rc::new(Cell::new(false)),
1841 grandkids: Rc::new(std::cell::RefCell::new(Vec::new())),
1842 passes: Rc::new(Cell::new(0)),
1843 }
1844 }
1845 }
1846
1847 impl Widget for Culler {
1848 fn build(&mut self, ctx: &mut crate::build_context::BuildContext) -> Vec<WidgetId> {
1849 self.park.bind_to(
1850 ctx.self_id(),
1851 ctx.binding_registry(),
1852 crate::binding::BindingLevel::Relayout,
1853 );
1854 // Each child has a child of its own, so "was this subtree
1855 // recursed into" is observable from the grandchild's bounds
1856 // and not only from the child's activation.
1857 self.kids = (0..3)
1858 .map(|i| {
1859 let grandkid = ctx.add(FillWidget::new().label(format!("grandkid{i}")));
1860 self.grandkids.borrow_mut().push(grandkid);
1861 ctx.add(StackWidget::new().child(grandkid).focusable(true))
1862 })
1863 .collect();
1864 self.kids.clone()
1865 }
1866 fn layout_response(
1867 &self,
1868 _p: SizeProposal,
1869 _c: &crate::widget::LayoutContext,
1870 ) -> LayoutResponse {
1871 teksilo_canvas::Size::new(100.0, 100.0).into()
1872 }
1873 fn children(&self) -> Vec<WidgetId> {
1874 self.kids.clone()
1875 }
1876 fn culls_children(&self) -> bool {
1877 self.opts_in
1878 }
1879 fn place_children(
1880 &self,
1881 bounds: Rect,
1882 _proposal: SizeProposal,
1883 children: &mut [WidgetPlacement],
1884 _ctx: &crate::widget::LayoutContext,
1885 ) {
1886 self.seen.set(children.len());
1887 self.passes.set(self.passes.get() + 1);
1888 let mask = self.park.get();
1889 for placement in children.iter_mut() {
1890 let Some(i) = self.kids.iter().position(|&k| k == placement.id) else {
1891 continue;
1892 };
1893 placement.origin = teksilo_canvas::Point::new(0.0, i as f32 * 20.0);
1894 // Width follows the proposal so a *grandchild*'s size says
1895 // whether the recursion reached it — a child's own size is
1896 // written here, before any cull decision, and so proves
1897 // nothing.
1898 placement.size = teksilo_canvas::Size::new(bounds.width, 20.0);
1899 if !self.ignore_dormant.get() {
1900 placement.dormant = mask & (1 << i) != 0;
1901 }
1902 }
1903 }
1904 }
1905
1906 struct Rig {
1907 tree: WidgetTree,
1908 id: WidgetId,
1909 park: Signal<u64>,
1910 seen: Rc<Cell<usize>>,
1911 ignore_dormant: Rc<Cell<bool>>,
1912 grandkids: Rc<std::cell::RefCell<Vec<WidgetId>>>,
1913 passes: Rc<Cell<usize>>,
1914 }
1915
1916 fn tree_with(opts_in: bool) -> Rig {
1917 let park = Signal::new(0u64);
1918 let seen = Rc::new(Cell::new(0usize));
1919 let culler = Culler::new(park.clone(), seen.clone(), opts_in);
1920 let ignore_dormant = culler.ignore_dormant.clone();
1921 let grandkids = culler.grandkids.clone();
1922 let passes = culler.passes.clone();
1923 let mut tree = WidgetTree::new();
1924 let id = tree.add(culler);
1925 tree.layout(SizeProposal::exact(100.0, 100.0));
1926 Rig {
1927 tree,
1928 id,
1929 park,
1930 seen,
1931 ignore_dormant,
1932 grandkids,
1933 passes,
1934 }
1935 }
1936
1937 #[test]
1938 fn focus_moving_re_asks_the_culling_parent_that_owns_it() {
1939 // A culling parent is told to keep what the user is in the middle
1940 // of, and it is only asked during layout — but focus moving from
1941 // one child to another moves nothing and resizes nothing, so the
1942 // idle early-return would skip the pass and leave the parent
1943 // answering with a stale anchor set. It would go on pinning the
1944 // child the user has left, and never pin the one they arrived in.
1945 //
1946 // Harmless while pinning only keeps a child *alive* — a newly
1947 // focused child is active by definition. Not harmless for a parent
1948 // that publishes a narrower set than it keeps alive, as
1949 // `SceneView` does: the published tree names its focused node, and
1950 // a focus the walk did not emit is a broken update.
1951 let Rig {
1952 mut tree,
1953 id,
1954 passes,
1955 ..
1956 } = tree_with(true);
1957 let kids = tree.children(id).to_vec();
1958
1959 let before = passes.get();
1960 tree.layout(SizeProposal::exact(100.0, 100.0));
1961 assert_eq!(
1962 passes.get(),
1963 before,
1964 "precondition: a settled tree skips the pass entirely"
1965 );
1966
1967 tree.focus(kids[0]);
1968 tree.layout(SizeProposal::exact(100.0, 100.0));
1969 assert_eq!(
1970 passes.get(),
1971 before + 1,
1972 "focus arriving is a change to the culler's inputs"
1973 );
1974
1975 tree.focus(kids[2]);
1976 tree.layout(SizeProposal::exact(100.0, 100.0));
1977 assert_eq!(
1978 passes.get(),
1979 before + 2,
1980 "…and so is focus moving between two of its children"
1981 );
1982
1983 tree.layout(SizeProposal::exact(100.0, 100.0));
1984 assert_eq!(
1985 passes.get(),
1986 before + 2,
1987 "…while a pass with the same anchors is still skipped"
1988 );
1989 }
1990
1991 #[test]
1992 fn focus_moving_forces_no_pass_where_nothing_culls() {
1993 // The scoping half. The invalidation walks up from the moved
1994 // anchor and marks only `culls_children` ancestors, so a tree
1995 // without one pays a parent-chain walk and forces no layout — the
1996 // cost lands on the trees that asked for the mechanism.
1997 let Rig {
1998 mut tree,
1999 id,
2000 passes,
2001 ..
2002 } = tree_with(false);
2003 let kids = tree.children(id).to_vec();
2004 let before = passes.get();
2005
2006 tree.focus(kids[0]);
2007 tree.layout(SizeProposal::exact(100.0, 100.0));
2008 tree.focus(kids[2]);
2009 tree.layout(SizeProposal::exact(100.0, 100.0));
2010
2011 assert_eq!(
2012 passes.get(),
2013 before,
2014 "no culling ancestor, no reason to re-run layout"
2015 );
2016 }
2017
2018 #[test]
2019 fn a_parked_child_leaves_the_tab_ring_and_the_at_tree_in_the_same_pass() {
2020 let Rig {
2021 mut tree, id, park, ..
2022 } = tree_with(true);
2023 let kids = tree.children(id).to_vec();
2024 assert_eq!(tree.tab_stops_within(id).len(), 3);
2025 let before = tree.accessibility_tree_snapshot().nodes.len();
2026
2027 park.set(0b010);
2028 tree.layout(SizeProposal::exact(100.0, 100.0));
2029
2030 assert!(!tree.is_active(kids[1]), "parked in the pass that asked");
2031 assert!(tree.is_active(kids[0]) && tree.is_active(kids[2]));
2032 let stops = tree.tab_stops_within(id);
2033 assert_eq!(stops.len(), 2, "stops = {stops:?}");
2034 assert!(!stops.contains(&kids[1]));
2035 assert_eq!(
2036 tree.accessibility_tree_snapshot().nodes.len(),
2037 before - 2,
2038 "the parked child AND its own child leave the AccessKit tree — \
2039 parking is a subtree operation"
2040 );
2041 }
2042
2043 #[test]
2044 fn a_parked_child_takes_its_subtree_out_of_the_layout_recursion() {
2045 // The activation flag alone does not prove this: a child could be
2046 // dormant and still have been recursed into. Watch the grandchild's
2047 // bounds, which only the recursion writes.
2048 let Rig {
2049 mut tree,
2050 park,
2051 grandkids,
2052 ..
2053 } = tree_with(true);
2054 let grandkid = grandkids.borrow()[1];
2055 assert_eq!(tree.bounds(grandkid).size(), Size::new(100.0, 20.0));
2056
2057 park.set(0b010);
2058 tree.layout(SizeProposal::exact(100.0, 300.0));
2059 let parked_bounds = tree.bounds(grandkid);
2060
2061 // Change the geometry the recursion would have written, and check
2062 // it does not reach the parked subtree.
2063 park.set(0b010);
2064 tree.layout(SizeProposal::exact(100.0, 300.0));
2065 assert_eq!(
2066 tree.bounds(grandkid),
2067 parked_bounds,
2068 "nothing below a parked child is laid out"
2069 );
2070
2071 park.set(0);
2072 tree.layout(SizeProposal::exact(100.0, 300.0));
2073 assert_eq!(
2074 tree.bounds(grandkid).size(),
2075 Size::new(100.0, 20.0),
2076 "…and the recursion resumes when it wakes"
2077 );
2078 }
2079
2080 #[test]
2081 fn a_parent_that_leaves_dormant_alone_changes_nothing() {
2082 // `dormant` arrives pre-set to the child's current state, so a
2083 // culling parent that does not write it keeps whatever it decided
2084 // last time. Without that, every pass in which the parent declines
2085 // to answer would silently wake everything it had parked.
2086 let Rig {
2087 mut tree,
2088 park,
2089 ignore_dormant,
2090 id,
2091 ..
2092 } = tree_with(true);
2093 let kids = tree.children(id).to_vec();
2094
2095 park.set(0b101);
2096 tree.layout(SizeProposal::exact(100.0, 100.0));
2097 assert!(!tree.is_active(kids[0]) && !tree.is_active(kids[2]));
2098
2099 ignore_dormant.set(true);
2100 park.set(0);
2101 tree.layout(SizeProposal::exact(100.0, 100.0));
2102 assert!(
2103 !tree.is_active(kids[0]) && !tree.is_active(kids[2]),
2104 "a parent that ignores the field must not resurrect anything"
2105 );
2106 assert!(tree.is_active(kids[1]), "…nor park anything");
2107 }
2108
2109 #[test]
2110 fn a_woken_child_is_laid_out_in_the_same_pass() {
2111 // The half a signal-based gate cannot do: a gate written during
2112 // layout is not read until the next pass, so the woken child would
2113 // paint at a stale rectangle for a frame.
2114 let Rig {
2115 mut tree, id, park, ..
2116 } = tree_with(true);
2117 let kids = tree.children(id).to_vec();
2118
2119 park.set(0b100);
2120 tree.layout(SizeProposal::exact(100.0, 100.0));
2121 assert!(!tree.is_active(kids[2]));
2122
2123 park.set(0);
2124 tree.layout(SizeProposal::exact(100.0, 100.0));
2125 assert!(tree.is_active(kids[2]), "woken");
2126 assert_eq!(
2127 tree.bounds(kids[2]),
2128 Rect::new(0.0, 40.0, 100.0, 20.0),
2129 "…and laid out this pass, not the next"
2130 );
2131 }
2132
2133 #[test]
2134 fn a_culling_parent_is_handed_its_parked_children() {
2135 // Otherwise it could never ask one back, having parked it.
2136 let Rig {
2137 mut tree,
2138 park,
2139 seen,
2140 ..
2141 } = tree_with(true);
2142 assert_eq!(seen.get(), 3);
2143 park.set(0b111);
2144 tree.layout(SizeProposal::exact(100.0, 100.0));
2145 park.set(0b111);
2146 tree.layout(SizeProposal::exact(100.0, 100.0));
2147 assert_eq!(
2148 seen.get(),
2149 3,
2150 "all three are parked, and all three are still offered"
2151 );
2152 }
2153
2154 #[test]
2155 fn a_widget_that_did_not_opt_in_cannot_park_anything() {
2156 // `dormant` is documented as read only for a `culls_children`
2157 // parent. A widget that writes it anyway must change nothing —
2158 // otherwise the field is a trapdoor on every container in the
2159 // framework.
2160 let Rig {
2161 mut tree,
2162 id,
2163 park,
2164 seen,
2165 grandkids,
2166 ..
2167 } = tree_with(false);
2168 let kids = tree.children(id).to_vec();
2169 park.set(0b111);
2170 tree.layout(SizeProposal::exact(100.0, 100.0));
2171 assert_eq!(seen.get(), 3, "active children only, which is all of them");
2172 for kid in &kids {
2173 assert!(tree.is_active(*kid), "{kid:?} must stay active");
2174 }
2175 assert_eq!(tree.tab_stops_within(id).len(), 3);
2176 // Widen the view so a subtree that was recursed into changes size.
2177 tree.layout(SizeProposal::exact(200.0, 100.0));
2178 for grandkid in grandkids.borrow().iter() {
2179 assert_eq!(
2180 tree.bounds(*grandkid).size(),
2181 Size::new(200.0, 20.0),
2182 "…and its subtree must still be laid out: reading `dormant` \
2183 from a widget that did not opt in would take the subtree \
2184 out of the recursion",
2185 );
2186 }
2187 }
2188
2189 #[test]
2190 fn parking_the_focused_child_does_not_leave_focus_on_a_dormant_node() {
2191 // The backstop behind the pin. A culling parent is expected to keep
2192 // what the user is using, but if it parks it anyway, focus must not
2193 // survive the pass pointing at a node dispatch will refuse — a
2194 // keystroke into the void is worse than a focus loss the user can
2195 // see.
2196 let Rig {
2197 mut tree, id, park, ..
2198 } = tree_with(true);
2199 let kids = tree.children(id).to_vec();
2200 tree.focus(kids[0]);
2201 assert_eq!(tree.focused(), Some(kids[0]));
2202
2203 park.set(0b001);
2204 tree.layout(SizeProposal::exact(100.0, 100.0));
2205
2206 assert!(!tree.is_active(kids[0]));
2207 assert_eq!(
2208 tree.focused(),
2209 None,
2210 "focus must not point into a subtree this pass parked"
2211 );
2212 let _ = id;
2213 }
2214 }
2215}