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