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