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