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