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