Skip to main content

teksilo_core/widget_tree/
rendering_impl.rs

1// SPDX-License-Identifier: MPL-2.0
2// SPDX-FileCopyrightText: 2026 FernTech
3
4use super::*;
5
6use super::lazy_theme::LazyTheme;
7use teksilo_canvas::quantize_raster_scale;
8
9/// Accessibility preferences passed through the paint recursion.
10struct A11yPaintPrefs {
11    high_contrast: bool,
12    reduced_motion: bool,
13    large_text: bool,
14    /// Combined user×OS text-scale factor (the logical accessibility
15    /// magnification). Surfaced to widgets via `PaintContext::text_scale`.
16    text_scale: f32,
17    /// Window-active state (`focused AND not occluded`). Surfaced to widgets
18    /// via `PaintContext::window_active`. (Carried alongside the a11y prefs as
19    /// a per-paint ambient flag; not itself an accessibility preference.)
20    window_active: bool,
21}
22
23impl WidgetTree {
24    /// Paint all active widgets and produce a RenderFrame.
25    /// Uses per-widget paint caching: only widgets with `needs_paint` are
26    /// re-painted; clean widgets reuse their cached paint output.
27    /// Also caches the full assembled frame — if no widget needs painting,
28    /// the previous frame is returned immediately.
29    pub fn render(&mut self) -> std::rc::Rc<RenderFrame> {
30        let mut noop = crate::window::NoopWindowOps;
31        self.render_with_ops(&mut noop)
32    }
33
34    /// Render a frame, threading the app's
35    /// [`WindowOps`](crate::window::WindowOps) sink through any
36    /// state-change-triggered handlers (data-driven rebuild, binding
37    /// flush). Called by `teksilo-app` during its paint pipeline.
38    pub fn render_with_ops(
39        &mut self,
40        ops: &mut dyn crate::window::WindowOps,
41    ) -> std::rc::Rc<RenderFrame> {
42        self.process_state_changes(&mut *ops);
43
44        // Always tick the animated-quad registry — even on the cache-hit
45        // early-out we still need fresh phase in the frame's
46        // anim_params, because every looping slot advances. Widgets
47        // whose paint() wasn't re-run (all of them on cache hit) keep
48        // their last DrawCommand::AnimatedQuad in the cached frame;
49        // the renderer reads the live params from `frame.anim_params`
50        // at the slot index stored in the draw command.
51        //
52        // The registry's internal `scratch` buffer owns the params; we
53        // only copy when actually writing them into the frame (below).
54        // Taking a borrow here lets us skip the copy entirely in the
55        // non-cache-hit branch where we allocate a fresh frame anyway.
56        let now = std::time::Instant::now();
57        let has_animations = self.animated_quads.has_running();
58        if has_animations {
59            self.animated_quads
60                .tick(now, &self.arena, self.paint_epoch, &self.theme);
61        }
62
63        // Cache-hit short-circuit: nothing in the tree was marked
64        // needs_paint, so the pixels are identical to the previous
65        // frame apart from the animated-quad uniforms. We deliberately
66        // do NOT bump `paint_epoch` here — if we did, every widget's
67        // `last_painted_epoch` would silently age out and the animation
68        // scheduler would treat them as "off-screen" on the next tick.
69        // Holding the epoch steady preserves the visibility gate
70        // through arbitrarily many idle cache-hit frames. The fresh
71        // `anim_params` we just computed are attached so shader-driven
72        // animations keep advancing even when paint() doesn't run.
73        //
74        // `Rc::make_mut` short-circuits to a mutable borrow when the
75        // tree is the sole owner of the cached frame — which is the
76        // common case, since the app-side caller typically drops the
77        // previous frame before calling `render()` again. If the
78        // caller holds a second Rc clone (e.g. two back-to-back
79        // renders without letting the first drop) we fall back to a
80        // single deep clone for that frame.
81        if !self.arena.any_needs_paint() && self.cached_frame.is_some() {
82            // Cache-hit path. paint_epoch is frozen, so visible
83            // subscribers' `last_painted_epoch == paint_epoch` still
84            // holds. Re-arm the frame-tick chain BEFORE refreshing the
85            // cached frame so we don't tangle borrows.
86            self.arm_frame_tick_for_visible_subscribers();
87
88            if let Some(cached) = self.cached_frame.as_mut() {
89                let frame = std::rc::Rc::make_mut(cached);
90                if has_animations {
91                    let src = self.animated_quads.scratch_slice();
92                    frame.anim_params.clear();
93                    frame.anim_params.extend_from_slice(src);
94                }
95                // Refresh the text backend's glyph timestamps for every
96                // layout baked into the reused frame — same contract as
97                // the per-widget cached_paint path below. Without this,
98                // a window that idles on the full-frame cache while
99                // text work elsewhere (another window, or measure-only
100                // layout passes) advances the atlas generation would
101                // have its still-visible glyphs evicted and their atlas
102                // slots reused, garbling the cached quads.
103                if !frame.layout_keys.is_empty()
104                    && let Some(tb) = &self.text_backend
105                {
106                    let mut tb = tb.borrow_mut();
107                    for key in &frame.layout_keys {
108                        tb.touch_layout(*key);
109                    }
110                    #[cfg(debug_assertions)]
111                    debug_validate_layout_keys(&*tb, &frame.layout_keys, None);
112                }
113                return std::rc::Rc::clone(cached);
114            }
115        }
116
117        self.paint_epoch = self.paint_epoch.saturating_add(1);
118        let paint_epoch = self.paint_epoch;
119
120        let mut frame = RenderFrame::new();
121        // `effective_theme` carries the user/OS text-scale multiplier baked into
122        // its typography, so painted glyphs match the scaled layout sizes. The
123        // palette is then projected for this window's paint state: an inactive
124        // window greys out every accent-coloured control (default button,
125        // Toggle, checked Checkbox/Radio, selected Tab/Segment, Slider fill,
126        // ProgressBar, focus rings), the Qt `QPalette::Inactive` model resolved
127        // once theme-side instead of per widget, and the OS "increase
128        // contrast" preference swaps in the high-contrast variant (WCAG 1.4.6
129        // Enhanced / EN 301 549 11.7). A theme's own `PaintProjection` decides
130        // both when it registers one; see `Theme::for_paint_state`. Colours
131        // only; typography is unchanged, so this is repaint-only (geometry
132        // stable).
133        let base_theme = self.effective_theme.for_paint_state(self.paint_state());
134        let text_backend = self.text_backend.clone();
135        let a11y_prefs = A11yPaintPrefs {
136            high_contrast: self.prefers_high_contrast(),
137            reduced_motion: self.prefers_reduced_motion,
138            large_text: self.text_scale_factor > 1.0,
139            text_scale: self.effective_text_scale,
140            window_active: self.is_window_active(),
141        };
142
143        let overlay_skip: std::collections::HashSet<WidgetId> = self
144            .overlay_manager
145            .active_content_ids()
146            .into_iter()
147            .collect();
148
149        // Interactive overlay rects for this frame, handed to
150        // `after_paint` via `WidgetTreeView`. Chrome aggregators
151        // (`TitleBar`) subtract them from the geometry they publish to
152        // the OS — an overlay floats above the caption, so its pixels
153        // must not be reported as draggable chrome.
154        let overlay_rects = self.overlay_rects_for_view();
155
156        for root_id in self.arena.roots() {
157            // Don't descend into overlay content via its anchor parent — it
158            // is painted via the dedicated overlay loop below. Without this,
159            // the overlay content paints twice per frame.
160            if overlay_skip.contains(&root_id) {
161                continue;
162            }
163            let inherited = LazyTheme::entry(&self.arena, root_id, &base_theme);
164            paint_widget_cached(
165                &mut self.arena,
166                root_id,
167                &mut frame,
168                &inherited,
169                None,
170                &text_backend,
171                None,
172                &a11y_prefs,
173                paint_epoch,
174                &overlay_skip,
175                &overlay_rects,
176                self.layout_direction,
177                // Root starts enabled; the walker ANDs in each node's
178                // own `enabled_state` as it descends.
179                true,
180                // Root is at screen scale; transform scopes below
181                // multiply in their own scale.
182                1.0,
183            );
184        }
185
186        for content_id in self.overlay_manager.active_content_ids() {
187            // Overlay content may hang below its anchor rather than sit at a
188            // root, and then it inherits the overrides above it.
189            let inherited = LazyTheme::entry(&self.arena, content_id, &base_theme);
190            // The content's language comes from its anchor, as in layout.
191            let inherited_language = self.content_language(content_id);
192            paint_widget_cached(
193                &mut self.arena,
194                content_id,
195                &mut frame,
196                &inherited,
197                inherited_language.as_ref(),
198                &text_backend,
199                None,
200                &a11y_prefs,
201                paint_epoch,
202                &overlay_skip,
203                &overlay_rects,
204                self.layout_direction,
205                // Overlays detach from their anchor's enabled-state.
206                // A tooltip / popover stays enabled even if its
207                // anchor was disabled — overlays receive their own
208                // explicit enabled-state if they need one.
209                true,
210                // Overlays render at screen scale regardless of their
211                // anchor's transform scopes.
212                1.0,
213            );
214        }
215
216        // Clear `needs_paint` on every active node. Mutation during
217        // iter — fill the reusable scratch first (zero-alloc once
218        // warm), then drive the loop from the snapshot.
219        //
220        // A node still dirty whose `paint()` did not run this render was
221        // skipped by the walker: clipped out, or under a sub-perceptual
222        // opacity. Its caches predate the change that dirtied it, so drop
223        // them. Clearing the flag alone would let the node replay that
224        // stale paint once it is visible again without having moved, since
225        // nothing else would mark it.
226        self.arena.fill_active_ids(&mut self.active_ids_scratch);
227        let ids = std::mem::take(&mut self.active_ids_scratch);
228        for &id in &ids {
229            if let Some(node) = self.arena.get_mut(id) {
230                if node.dirty.needs_paint && node.paint_consumed_epoch != paint_epoch {
231                    node.cached_paint = None;
232                    node.cached_post_paint = None;
233                }
234                node.dirty.needs_paint = false;
235            }
236        }
237        self.active_ids_scratch = ids;
238
239        if has_animations {
240            frame
241                .anim_params
242                .extend_from_slice(self.animated_quads.scratch_slice());
243        }
244        frame.debug_validate_stacks();
245        let rc = std::rc::Rc::new(frame);
246        self.cached_frame = Some(std::rc::Rc::clone(&rc));
247        // Full-render path: subscribers whose owners were just painted
248        // have `last_painted_epoch == paint_epoch`. Re-arm the
249        // frame-tick chain so per-frame effects keep ticking. When all
250        // subscribers are off-screen this returns false and the chain
251        // dies — exactly the bug fix that motivated this scheduler.
252        self.arm_frame_tick_for_visible_subscribers();
253        rc
254    }
255
256    /// Walk the frame-tick subscriber set and arm
257    /// `frame_tick_armed_by_subscribers` if any subscriber's owner is
258    /// currently visible. Called from `render_with_ops` (both cache-hit and
259    /// full-render paths).
260    ///
261    /// Not `frame_tick_requested`: that flag is paced at 60 Hz, this one at
262    /// the subscribers' own interval, and `frame_tick_deadline` has to tell
263    /// them apart or a throttled subscriber slows every requested frame.
264    pub(crate) fn arm_frame_tick_for_visible_subscribers(&mut self) {
265        if self
266            .frame_tick_scheduler
267            .should_arm_frame_tick(&self.arena, self.paint_epoch)
268        {
269            self.frame_tick_armed_by_subscribers = true;
270        }
271    }
272
273    /// The overlay rects `after_paint` reads through `WidgetTreeView`, taken
274    /// once a frame: what of each open overlay takes a press.
275    ///
276    /// A pass-through overlay takes a press only where something in it does,
277    /// as the hit test falls through it everywhere else, so it counts only by
278    /// its outermost active nodes that are not pass-through themselves (a
279    /// text-affordance layer's handles, while they show). Counted whole, the
280    /// full-window layer a text field mounts covered everything: on Windows a
281    /// custom title bar became client area and lost its Snap layouts, and an
282    /// embedded `WebView` hid for as long as the layer stood.
283    ///
284    /// `over_chrome` leaves out a modal's scrim as well, the window's chrome
285    /// staying live above it; `all` keeps it, so a `WebView` stands down
286    /// under a modal.
287    pub(crate) fn overlay_rects_for_view(&self) -> crate::widget::OverlayRects {
288        let mut rects = crate::widget::OverlayRects::default();
289        for overlay in self.overlay_manager.interactive() {
290            let content = overlay.content_id;
291            let mut parts = Vec::new();
292            if self
293                .arena
294                .get(content)
295                .is_some_and(|node| node.event_pass_through)
296            {
297                self.collect_press_takers(content, &mut parts);
298            } else {
299                parts.push(overlay.bounds);
300            }
301            parts.retain(|r| r.width > 0.0 && r.height > 0.0);
302            if !self.overlay_manager.is_modal_scrim(overlay) {
303                rects.over_chrome.extend(parts.iter().copied());
304            }
305            rects.all.extend(parts);
306        }
307        rects
308    }
309
310    /// The bounds of `id`'s outermost active descendants that are not
311    /// pass-through, into `out`.
312    fn collect_press_takers(&self, id: WidgetId, out: &mut Vec<Rect>) {
313        for &child in self.arena.children(id) {
314            if !self.arena.is_active(child) {
315                continue;
316            }
317            if self
318                .arena
319                .get(child)
320                .is_some_and(|node| node.event_pass_through)
321            {
322                self.collect_press_takers(child, out);
323            } else {
324                out.push(self.arena.bounds(child));
325            }
326        }
327    }
328}
329
330/// Recursive paint pass with per-widget caching.
331/// Only re-runs `paint()` for widgets with `needs_paint` set; clean widgets
332/// reuse their `cached_paint` output. The tree walk still runs for clip/child
333/// ordering, but skips the expensive `paint()` call for clean widgets.
334///
335/// `parent_effective_enabled` is the AND of every ancestor's `enabled_state`
336/// resolved value (start `true` at root). The walker ANDs this with the
337/// current node's `enabled_state` to produce `this_effective_enabled`, which
338/// it both injects into the node's `PaintContext` and forwards as the parent
339/// value to children. This is the single mechanism by which leaf widgets see
340/// the arena's enabled-state at paint time without needing to walk ancestors
341/// themselves (`PaintContext` carries no `WidgetId` or arena reference).
342///
343/// `accumulated_raster_scale` is the quantized product of every ancestor
344/// transform scope's scale (start `1.0` at root). The walker multiplies in
345/// this node's own transform scale, sets the result as the text backend's
346/// ambient raster scale around the node's paint (so text drawn here
347/// rasterizes densely enough for the GPU transform that will stretch it),
348/// stamps it on the node's paint cache, and forwards it to children.
349#[allow(clippy::too_many_arguments)]
350fn paint_widget_cached(
351    arena: &mut WidgetArena,
352    id: WidgetId,
353    frame: &mut RenderFrame,
354    // The parent's theme scope; `id` adds its own override, if any.
355    inherited_theme: &LazyTheme<'_>,
356    // The language of the parent's content; `id`'s own declaration wins.
357    inherited_language: Option<&crate::language::LanguageTag>,
358    text_backend: &Option<Rc<RefCell<dyn teksilo_canvas::TextBackend>>>,
359    clip_bounds: Option<Rect>,
360    a11y_prefs: &A11yPaintPrefs,
361    paint_epoch: u64,
362    overlay_skip: &std::collections::HashSet<WidgetId>,
363    overlay_rects: &crate::widget::OverlayRects,
364    layout_direction: crate::environment::LayoutDirection,
365    parent_effective_enabled: bool,
366    accumulated_raster_scale: f32,
367) {
368    if !arena.is_active(id) {
369        return;
370    }
371
372    // Compute this node's effective enabled-state once: AND the
373    // ancestor-derived value with our own `enabled_state` if set.
374    // Used both for our own paint context and for the recursion into
375    // children below.
376    let this_effective_enabled = parent_effective_enabled
377        && arena
378            .get(id)
379            .and_then(|n| n.enabled_state.as_ref())
380            .is_none_or(|p| p.get());
381    let language = if arena.content_language_count == 0 {
382        None
383    } else {
384        arena
385            .own_content_language(id)
386            .or_else(|| inherited_language.cloned())
387    };
388
389    let node = arena.get(id).expect("node id is active (guarded above)");
390    let bounds = node.bounds;
391    if let Some(clip) = clip_bounds {
392        let x0 = bounds.x.max(clip.x);
393        let y0 = bounds.y.max(clip.y);
394        let x1 = bounds.right().min(clip.right());
395        let y1 = bounds.bottom().min(clip.bottom());
396        if x1 <= x0 || y1 <= y0 {
397            // Clipped to nothing — widget is offscreen. Skip its paint
398            // AND skip stamping `last_painted_epoch`, so the animation
399            // scheduler will notice it is no longer visible and pause
400            // its looping animations.
401            return;
402        }
403    }
404
405    // Mark this widget as "painted in epoch N" regardless of whether
406    // we hit the cache-path or ran `paint()` — both outcomes mean the
407    // widget's bounds landed inside the viewport this frame, which is
408    // all the animation scheduler cares about.
409    if let Some(node_mut) = arena.get_mut(id) {
410        node_mut.last_painted_epoch = paint_epoch;
411    }
412
413    // Read the optional opacity scope before borrowing the node again
414    // for the paint/cache path. The scope wraps both this widget's own
415    // paint and its children's paint, composing with any ancestor
416    // opacity via the canvas's stacked-opacity model.
417    let node = arena.get(id).expect("node id is active (guarded above)");
418    let opacity = node.opacity_prop.as_ref().map(|p| p.get().clamp(0.0, 1.0));
419    if let Some(o) = opacity
420        && o < 1.0 / 512.0
421    {
422        // Sub-perceptual: skip the subtree entirely. Saves a draw
423        // pass when a `Fade` is fully transparent (e.g. just-dismissed
424        // tooltip waiting for cleanup) and prevents 0.0 from emitting
425        // a spurious blend pass on the GPU. We do this before any blur
426        // scope emit so the Begin/End pair stays balanced.
427        return;
428    }
429
430    // Optional blur scope is the OUTERMOST per-node scope: it captures
431    // the entire rendered subtree (including any opacity/transform scopes
432    // we're about to push) into an intermediate texture, blurs it via
433    // the renderer's dual-Kawase chain, and composites the blurred
434    // result back at the widget's bounds. Sub-perceptual radii skip the
435    // pair entirely so animated 0→target_radius patterns have zero cost
436    // when fully off.
437    let node = arena.get(id).expect("node id is active (guarded above)");
438    let blur_radius = node
439        .blur_prop
440        .as_ref()
441        .map(|p| p.get())
442        .filter(|r| *r >= 0.5);
443    let blur_bounds = arena.bounds(id);
444    if let Some(r) = blur_radius {
445        frame
446            .draw_order
447            .push(teksilo_canvas::DrawCommand::BeginBlurredSubtree {
448                bounds: blur_bounds,
449                radius: r,
450            });
451    }
452
453    if let Some(o) = opacity {
454        frame
455            .draw_order
456            .push(teksilo_canvas::DrawCommand::SetOpacity(o));
457    }
458
459    // Optional transform scope — wraps both this widget's own paint
460    // and its children's paint. The renderer composes the pushed
461    // transform onto its stack so widget-internal canvas transforms
462    // (canvas.translate / scale / rotate) compose with this wrapper
463    // transform instead of clobbering it. Skip the push entirely when
464    // the transform is identity — saves a flush on every wrapper that
465    // happens to be at its rest pose.
466    let node = arena.get(id).expect("node id is active (guarded above)");
467    let transform = node.transform_prop.as_ref().map(|p| p.get());
468    let push_transform = transform.filter(|t| *t != teksilo_canvas::Transform2D::IDENTITY);
469    let clips = node.clips_children;
470    let content_transform = node.content_transform;
471    let bounds = node.bounds;
472
473    // Accumulated raster scale for this node and its subtree: multiply
474    // the ancestors' scale by this node's own transform scale (a
475    // SceneView zoom or a `Scale` wrapper) and re-quantize. Text painted
476    // inside the scope rasterizes at this density so the GPU transform
477    // lands a ~1:1 texel-to-pixel mapping instead of stretching a 1×
478    // bitmap. Pure translations/rotations have `geometric_scale() == 1`
479    // and inherit the parent value bit-identically.
480    let this_raster_scale = match push_transform {
481        Some(t) => quantize_raster_scale(accumulated_raster_scale * t.geometric_scale()),
482        None => accumulated_raster_scale,
483    };
484    // The backend currently holds the parent's ambient scale (root
485    // callers start at 1.0; every recursion level restores on exit), so
486    // it only needs touching when this node's scale differs.
487    let raster_scale_changed = this_raster_scale != accumulated_raster_scale;
488    if raster_scale_changed && let Some(tb) = text_backend {
489        tb.borrow_mut().set_raster_scale(this_raster_scale);
490    }
491    // A *content* transform (a SceneView's pan/zoom) leaves the node's bounds a
492    // fixed parent-space viewport and only moves the content. Emit its clip
493    // BEFORE the transform so the renderer scissors to that fixed viewport
494    // (transformed by ancestors only — correct for nested scenes too) instead
495    // of the pan/zoom-shifted rect, and so the node's own paint (background
496    // grid / lightweight items) is clipped to the viewport as well. A *self*
497    // transform (Scale/Rotate) keeps its clip INSIDE the transform — there the
498    // clip is meant to be the scaled visual region.
499    let clip_outside_transform = clips && content_transform;
500    if clip_outside_transform {
501        frame
502            .draw_order
503            .push(teksilo_canvas::DrawCommand::SetClip(bounds));
504    }
505    if let Some(t) = push_transform {
506        frame
507            .draw_order
508            .push(teksilo_canvas::DrawCommand::PushTransform(t));
509    }
510
511    let node = arena.get(id).expect("node id is active (guarded above)");
512    // A clean widget's cached frames bake glyph quads at the raster
513    // scale current when they were recorded; when the ambient scale
514    // moved (a scene zoom crossed a quantization bucket), those quads
515    // sample wrong-density bitmaps — treat the node as needing paint.
516    let needs_paint = node.dirty.needs_paint || node.paint_raster_scale != this_raster_scale;
517
518    // This node's theme scope, for its own paint hooks and its children. A
519    // node without an override hands on its parent's scope; one with an
520    // override gets its own, which resolves (cloning the theme and running
521    // the override) only if something here or below asks, and then once for
522    // the whole subtree. Something asks when it repaints, and on every frame
523    // when it wants `after_paint` (the hook below runs on cache hits too).
524    let own_scope;
525    let theme_scope = if arena.has_theme_override(id) {
526        own_scope = LazyTheme::below(inherited_theme, id);
527        &own_scope
528    } else {
529        inherited_theme
530    };
531
532    if needs_paint || node.cached_paint.is_none() {
533        let ctx = PaintContext {
534            theme: theme_scope.get(arena),
535            scale_factor: this_raster_scale,
536            text_scale: a11y_prefs.text_scale,
537            layout_direction,
538            effective_enabled: this_effective_enabled,
539            prefers_high_contrast: a11y_prefs.high_contrast,
540            prefers_reduced_motion: a11y_prefs.reduced_motion,
541            prefers_large_text: a11y_prefs.large_text,
542            window_active: a11y_prefs.window_active,
543            clip_bounds,
544            content_language: language.clone(),
545        };
546
547        let bounds = arena.bounds(id);
548        let node = arena.get(id).expect("node id is active (guarded above)");
549
550        let mut canvas = match text_backend {
551            Some(tb) => Canvas::with_text_backend(tb.clone()),
552            None => Canvas::new(),
553        };
554        // The paint about to run serves every repaint requested off the UI
555        // thread so far: take the request before reading the state.
556        if let Some(wake) = &node.repaint_wake {
557            wake.consume_repaint();
558        }
559        node.widget.paint(bounds, &mut canvas, &ctx);
560        let widget_frame = canvas.into_render_frame();
561
562        frame.merge(&widget_frame);
563        if let Some(node) = arena.get_mut(id) {
564            node.cached_paint = Some(widget_frame);
565            node.paint_raster_scale = this_raster_scale;
566            node.paint_consumed_epoch = paint_epoch;
567        }
568    } else {
569        let node = arena.get(id).expect("node id is active (guarded above)");
570        if let Some(cached) = &node.cached_paint {
571            // Refresh the text backend's glyph timestamps for every
572            // layout baked into this cached paint. Without this,
573            // widgets that stay clean for ~180 frames (e.g. static
574            // labels next to an animation) can have their atlas slots
575            // evicted and reused, and the cached UVs then sample the
576            // wrong glyph. `TextBackend::touch_layout` is a no-op for
577            // backends without a glyph cache (the mock).
578            if !cached.layout_keys.is_empty()
579                && let Some(tb) = text_backend
580            {
581                let mut tb = tb.borrow_mut();
582                for key in &cached.layout_keys {
583                    tb.touch_layout(*key);
584                }
585                #[cfg(debug_assertions)]
586                debug_validate_layout_keys(&*tb, &cached.layout_keys, Some(id));
587            }
588            frame.merge(cached);
589        }
590    }
591
592    let node = arena.get(id).expect("node id is active (guarded above)");
593    let children: Vec<WidgetId> = node.children.clone();
594    let next_clip = if clips {
595        Some(match clip_bounds {
596            Some(clip) => {
597                let x0 = bounds.x.max(clip.x);
598                let y0 = bounds.y.max(clip.y);
599                let x1 = bounds.right().min(clip.right());
600                let y1 = bounds.bottom().min(clip.bottom());
601                Rect::new(x0, y0, (x1 - x0).max(0.0), (y1 - y0).max(0.0))
602            }
603            None => bounds,
604        })
605    } else {
606        clip_bounds
607    };
608
609    // A *content*-transform node (a `SceneView`'s pan/zoom) places its children
610    // in the transformed (content) coordinate space — `place_children` writes
611    // each child's `node.bounds` in scene coords, and the pan/zoom is applied
612    // only at draw time via the `PushTransform` above. The cull clip we hand the
613    // children must therefore be in that same content space; otherwise the
614    // per-child offscreen check at the top of this fn compares scene-space child
615    // bounds against a screen-space clip and drops content that is panned into
616    // view (a card far down in scene coords reads as "outside the viewport"
617    // regardless of pan — the lightweight tier, painted in the node's own
618    // `paint()`, is unaffected, hence "connectors render but cards don't").
619    // Inverse-transform the screen-space clip into content space. The GPU
620    // `SetClip` (emitted in parent/screen space) is untouched — it stays the
621    // real viewport scissor.
622    let next_clip = match (
623        content_transform,
624        next_clip,
625        transform.and_then(|t| t.inverse()),
626    ) {
627        (true, Some(screen_clip), Some(inv)) => Some(inv.apply_rect(screen_clip)),
628        _ => next_clip,
629    };
630
631    // Self-transform / plain clipping nodes emit their clip here — after the
632    // node's own paint, inside any transform scope. Content-transform nodes
633    // already emitted theirs above (in parent space).
634    if clips && !clip_outside_transform {
635        frame
636            .draw_order
637            .push(teksilo_canvas::DrawCommand::SetClip(bounds));
638    }
639
640    for child_id in children {
641        // Skip overlay-managed content here — it is painted via the
642        // dedicated overlay loop in render_with_ops. Without this, an
643        // overlay (e.g. a tooltip) attached as a child of its anchor
644        // would paint twice per frame: once via the parent walk and
645        // once via the overlay loop.
646        if overlay_skip.contains(&child_id) {
647            continue;
648        }
649        paint_widget_cached(
650            arena,
651            child_id,
652            frame,
653            theme_scope,
654            language.as_ref(),
655            text_backend,
656            next_clip,
657            a11y_prefs,
658            paint_epoch,
659            overlay_skip,
660            overlay_rects,
661            layout_direction,
662            this_effective_enabled,
663            this_raster_scale,
664        );
665    }
666
667    // Post-order `after_paint` hook. Fires after every descendant has
668    // painted and committed its bounds, so a parent can read those
669    // bounds via `WidgetTreeView::bounds(child_id)`. Gated on
670    // `wants_after_paint()` to avoid a virtual call per widget per
671    // frame for the 99% of widgets that don't aggregate. The arena
672    // mutable borrow from the recursive child loop has dropped by
673    // this point, so an immutable reborrow is safe.
674    {
675        let arena_ref: &WidgetArena = &*arena;
676        if let Some(node) = arena_ref.get(id)
677            && node.widget.wants_after_paint()
678        {
679            let view = crate::widget::WidgetTreeView::new(arena_ref, overlay_rects);
680            let ctx = PaintContext {
681                theme: theme_scope.get(arena_ref),
682                scale_factor: this_raster_scale,
683                text_scale: a11y_prefs.text_scale,
684                layout_direction,
685                effective_enabled: this_effective_enabled,
686                prefers_high_contrast: a11y_prefs.high_contrast,
687                prefers_reduced_motion: a11y_prefs.reduced_motion,
688                prefers_large_text: a11y_prefs.large_text,
689                window_active: a11y_prefs.window_active,
690                clip_bounds,
691                content_language: language.clone(),
692            };
693            node.widget.after_paint(&view, &ctx);
694        }
695    }
696
697    // Foreground pass — `post_paint` emits *after* the whole child
698    // subtree, so its draws land on top of this node's descendants. Still
699    // inside this node's clip / transform / opacity / blur scopes (their
700    // closers come below), so a foreground decoration pans, scales and
701    // clips consistently with the subtree it covers. Same `needs_paint`
702    // cache gate as the main paint above, with its own `cached_post_paint`
703    // frame. Gated on `wants_post_paint` so non-foreground widgets pay
704    // nothing.
705    let wants_post_paint = arena
706        .get(id)
707        .map(|n| n.widget.wants_post_paint())
708        .unwrap_or(false);
709    if wants_post_paint {
710        let has_post_cache = arena
711            .get(id)
712            .map(|n| n.cached_post_paint.is_some())
713            .unwrap_or(false);
714        if needs_paint || !has_post_cache {
715            // Children restored the backend to this node's ambient scale
716            // on their way out; re-assert defensively so post_paint text
717            // (e.g. a SceneView's foreground lightweight items) can't
718            // bake at a child-leaked scale.
719            if raster_scale_changed && let Some(tb) = text_backend {
720                tb.borrow_mut().set_raster_scale(this_raster_scale);
721            }
722            let ctx = PaintContext {
723                theme: theme_scope.get(arena),
724                scale_factor: this_raster_scale,
725                text_scale: a11y_prefs.text_scale,
726                layout_direction,
727                effective_enabled: this_effective_enabled,
728                prefers_high_contrast: a11y_prefs.high_contrast,
729                prefers_reduced_motion: a11y_prefs.reduced_motion,
730                prefers_large_text: a11y_prefs.large_text,
731                window_active: a11y_prefs.window_active,
732                clip_bounds,
733                content_language: language.clone(),
734            };
735            let bounds = arena.bounds(id);
736            let node = arena.get(id).expect("node id is active (guarded above)");
737            let mut canvas = match text_backend {
738                Some(tb) => Canvas::with_text_backend(tb.clone()),
739                None => Canvas::new(),
740            };
741            node.widget.post_paint(bounds, &mut canvas, &ctx);
742            let post_frame = canvas.into_render_frame();
743            frame.merge(&post_frame);
744            if let Some(node) = arena.get_mut(id) {
745                node.cached_post_paint = Some(post_frame);
746            }
747        } else if let Some(cached) = arena.get(id).and_then(|n| n.cached_post_paint.as_ref()) {
748            if !cached.layout_keys.is_empty()
749                && let Some(tb) = text_backend
750            {
751                let mut tb = tb.borrow_mut();
752                for key in &cached.layout_keys {
753                    tb.touch_layout(*key);
754                }
755                #[cfg(debug_assertions)]
756                debug_validate_layout_keys(&*tb, &cached.layout_keys, Some(id));
757            }
758            frame.merge(cached);
759        }
760    }
761
762    if clips && !clip_outside_transform {
763        frame
764            .draw_order
765            .push(teksilo_canvas::DrawCommand::ClearClip);
766    }
767
768    if push_transform.is_some() {
769        frame
770            .draw_order
771            .push(teksilo_canvas::DrawCommand::PopTransform);
772    }
773
774    // A content-transform clip opened before the transform, so it closes after
775    // the transform pops (clip { transform { … } } nesting).
776    if clip_outside_transform {
777        frame
778            .draw_order
779            .push(teksilo_canvas::DrawCommand::ClearClip);
780    }
781
782    if opacity.is_some() {
783        frame
784            .draw_order
785            .push(teksilo_canvas::DrawCommand::RestoreOpacity);
786    }
787
788    if blur_radius.is_some() {
789        frame
790            .draw_order
791            .push(teksilo_canvas::DrawCommand::EndBlurredSubtree);
792    }
793
794    // Unwind the ambient raster scale to the parent's value so siblings
795    // painted after this subtree see their own ancestor scale.
796    if raster_scale_changed && let Some(tb) = text_backend {
797        tb.borrow_mut().set_raster_scale(accumulated_raster_scale);
798    }
799}
800
801/// Debug-build corruption catcher: before a retained paint frame is
802/// replayed, verify that every layout baked into it still matches the
803/// live glyph atlas.
804///
805/// A `RectMismatch` means the frame's glyph quads reference atlas pixels
806/// that were evicted and reused — replaying them draws the wrong
807/// characters (the historical "random text corruption fixed by a
808/// repaint" bug). That is always a missing cache-invalidation path, so
809/// abort with a diagnostic. A `StaleKey` (backend forgot the layout
810/// entirely — its caches were cleared after this frame was baked) is the
811/// same bug class but can transiently occur around legitimate wholesale
812/// clears, so it logs loudly (once per key) instead of aborting.
813#[cfg(debug_assertions)]
814fn debug_validate_layout_keys(
815    tb: &dyn teksilo_canvas::TextBackend,
816    layout_keys: &[u64],
817    widget: Option<WidgetId>,
818) {
819    use teksilo_canvas::GlyphValidation;
820    std::thread_local! {
821        static REPORTED_STALE_KEYS: std::cell::RefCell<std::collections::HashSet<u64>> =
822            std::cell::RefCell::new(std::collections::HashSet::new());
823    }
824    for key in layout_keys {
825        match tb.debug_validate_layout(*key) {
826            GlyphValidation::Valid => {}
827            GlyphValidation::StaleKey => {
828                let first_report = REPORTED_STALE_KEYS.with(|set| set.borrow_mut().insert(*key));
829                if first_report {
830                    eprintln!(
831                        "[teksilo] WARNING: retained paint cache replays layout_key={key} \
832                         (widget={widget:?}) that the text backend no longer knows — the \
833                         frame survived a backend cache clear, so a paint-cache \
834                         invalidation path is likely missing."
835                    );
836                }
837            }
838            GlyphValidation::RectMismatch => {
839                panic!(
840                    "stale glyph UVs in retained paint cache (layout_key={key}, \
841                     widget={widget:?}): cached quads no longer match the live glyph \
842                     atlas — a cache-invalidation path is missing"
843                );
844            }
845        }
846    }
847}
848
849#[cfg(test)]
850mod tests {
851    use super::*;
852    use crate::test_widgets::{FillWidget, StackWidget};
853    use teksilo_tokens::{Color, CornerRadius};
854
855    /// Headless text backend that records every `touch_layout` call and
856    /// hands out layouts with a fixed non-zero `layout_key`, so tests
857    /// can assert that paint-cache reuse keeps glyph timestamps fresh.
858    /// Also tracks the ambient raster scale (`set_raster_scale`) and the
859    /// scale every `layout_single_line` call ran under, so walker tests
860    /// can assert the set/restore discipline around transform scopes.
861    #[derive(Default)]
862    struct RecordingTextBackend {
863        touched: std::rc::Rc<std::cell::RefCell<Vec<u64>>>,
864        raster_scale: f32,
865        /// Ambient raster scale observed by each `layout_single_line`
866        /// call, in call order.
867        layout_scales: std::rc::Rc<std::cell::RefCell<Vec<f32>>>,
868    }
869
870    impl RecordingTextBackend {
871        fn new(touched: std::rc::Rc<std::cell::RefCell<Vec<u64>>>) -> Self {
872            Self {
873                touched,
874                raster_scale: 1.0,
875                layout_scales: Default::default(),
876            }
877        }
878    }
879
880    impl teksilo_canvas::TextBackend for RecordingTextBackend {
881        fn set_raster_scale(&mut self, raster_scale: f32) {
882            self.raster_scale = raster_scale;
883        }
884
885        fn raster_scale(&self) -> f32 {
886            self.raster_scale
887        }
888
889        fn layout_single_line(
890            &mut self,
891            text: &str,
892            _style: &teksilo_tokens::TextStyle,
893            _max_width: Option<f32>,
894        ) -> teksilo_canvas::TextLayout {
895            self.layout_scales.borrow_mut().push(self.raster_scale);
896            teksilo_canvas::TextLayout {
897                width: text.len() as f32 * 8.0,
898                height: 16.0,
899                ascent: 12.0,
900                descent: 4.0,
901                underline_offset: 1.0,
902                underline_thickness: 1.0,
903                layout_key: 42,
904                line_count: 1,
905                spans: Vec::new(),
906                raster_scale: self.raster_scale,
907                geometry: None,
908            }
909        }
910
911        fn ensure_glyphs(
912            &mut self,
913            _layout: &teksilo_canvas::TextLayout,
914        ) -> Vec<teksilo_canvas::GlyphQuad> {
915            Vec::new()
916        }
917
918        fn touch_layout(&mut self, layout_key: u64) {
919            self.touched.borrow_mut().push(layout_key);
920        }
921    }
922
923    /// Leaf widget that draws one line of text so its emitted frame
924    /// carries a `layout_key`.
925    #[derive(Debug)]
926    struct TextPaintWidget;
927
928    impl Widget for TextPaintWidget {
929        fn layout_response(
930            &self,
931            proposal: SizeProposal,
932            _ctx: &LayoutContext,
933        ) -> crate::widget::LayoutResponse {
934            proposal.resolve(100.0, 20.0).into()
935        }
936
937        fn paint(
938            &self,
939            bounds: teksilo_canvas::Rect,
940            canvas: &mut teksilo_canvas::Canvas,
941            _ctx: &PaintContext,
942        ) {
943            let style = teksilo_tokens::TextStyle::default();
944            let _ = canvas.draw_text("hello", bounds, &style, Color::BLACK);
945        }
946    }
947
948    #[test]
949    fn full_frame_cache_hit_touches_layout_keys() {
950        let touched = std::rc::Rc::new(std::cell::RefCell::new(Vec::new()));
951        let backend = RecordingTextBackend::new(touched.clone());
952        let mut tree = WidgetTree::new()
953            .with_theme(crate::presets::intui::light())
954            .with_text_backend(std::rc::Rc::new(std::cell::RefCell::new(backend)));
955        tree.add(TextPaintWidget);
956        tree.layout(SizeProposal::exact(200.0, 50.0));
957
958        // First render paints for real; no cache reuse yet.
959        let _ = tree.render();
960        touched.borrow_mut().clear();
961
962        // Nothing is dirty: this render takes the full-frame early-out.
963        // The reused frame's layout keys must still be touched, or the
964        // backend's LRU ages out glyphs that are on screen.
965        let _ = tree.render();
966        assert!(
967            touched.borrow().contains(&42),
968            "full-frame cache hit must touch_layout every baked layout key; \
969             touched = {:?}",
970            touched.borrow()
971        );
972    }
973
974    /// Shared fixture: a root stack with a text leaf before, inside, and
975    /// after a transform-scoped wrapper:
976    ///
977    /// ```text
978    /// root Stack
979    /// ├── TextPaintWidget          (A, screen scale)
980    /// ├── Stack [transform]        (wrapper)
981    /// │   └── TextPaintWidget      (B, scaled)
982    /// └── TextPaintWidget          (C, screen scale)
983    /// ```
984    fn scaled_subtree_tree(
985        transform: impl Into<crate::signal::Prop<teksilo_canvas::Transform2D>>,
986    ) -> (
987        WidgetTree,
988        std::rc::Rc<std::cell::RefCell<RecordingTextBackend>>,
989        std::rc::Rc<std::cell::RefCell<Vec<f32>>>,
990    ) {
991        let backend = RecordingTextBackend::new(Default::default());
992        let layout_scales = backend.layout_scales.clone();
993        let backend_rc = std::rc::Rc::new(std::cell::RefCell::new(backend));
994        let mut tree = WidgetTree::new()
995            .with_theme(crate::presets::intui::light())
996            .with_text_backend(backend_rc.clone()
997                as std::rc::Rc<std::cell::RefCell<dyn teksilo_canvas::TextBackend>>);
998
999        let root = tree.add(StackWidget::new());
1000        tree.add_child(root, TextPaintWidget); // A
1001        let wrapper = tree.add_child(root, StackWidget::new());
1002        tree.add_child(wrapper, TextPaintWidget); // B
1003        tree.add_child(root, TextPaintWidget); // C
1004        tree.set_transform(wrapper, transform);
1005
1006        tree.layout(SizeProposal::exact(400.0, 300.0));
1007        (tree, backend_rc, layout_scales)
1008    }
1009
1010    #[test]
1011    fn walker_sets_raster_scale_for_scaled_subtree_and_restores() {
1012        let (mut tree, backend_rc, layout_scales) =
1013            scaled_subtree_tree(teksilo_canvas::Transform2D::scale(2.0, 2.0));
1014        let _ = tree.render();
1015
1016        // Paint order is child order: A (screen), B (inside the 2x
1017        // scope, quantized onto the 1.25^n ladder), C (screen again —
1018        // the wrapper restored the ambient scale on exit).
1019        let expected_b = 1.25_f32.powi(3); // quantize(2.0)
1020        assert_eq!(
1021            layout_scales.borrow().as_slice(),
1022            &[1.0, expected_b, 1.0],
1023            "text inside the transform scope must lay out at the quantized \
1024             scale; siblings before/after at screen scale"
1025        );
1026        // The walk unwound to the root ambient scale.
1027        assert_eq!(backend_rc.borrow().raster_scale, 1.0);
1028    }
1029
1030    #[test]
1031    fn raster_scale_change_repaints_clean_descendants() {
1032        let transform = crate::signal::Signal::new(teksilo_canvas::Transform2D::scale(2.0, 2.0));
1033        let (mut tree, _backend_rc, layout_scales) = scaled_subtree_tree(transform.clone());
1034        let _ = tree.render();
1035        layout_scales.borrow_mut().clear();
1036
1037        // Zoom changes: only the wrapper node is dirtied (RepaintOnly
1038        // binding); its text child B stays clean — the raster-scale
1039        // stamp on B's paint cache must force the repaint anyway.
1040        transform.set(teksilo_canvas::Transform2D::scale(3.0, 3.0));
1041        let _ = tree.render();
1042        assert_eq!(
1043            layout_scales.borrow().as_slice(),
1044            &[1.25_f32.powi(5)],
1045            "the clean text leaf inside the scope must re-rasterize at the \
1046             new quantized scale (A and C stay cached: no layout calls)"
1047        );
1048
1049        // And back down to identity: B re-bakes once more at 1.0.
1050        layout_scales.borrow_mut().clear();
1051        transform.set(teksilo_canvas::Transform2D::IDENTITY);
1052        let _ = tree.render();
1053        assert_eq!(layout_scales.borrow().as_slice(), &[1.0]);
1054
1055        // Steady state: nothing dirty, no scale movement → full-frame
1056        // cache hit, zero layout calls.
1057        layout_scales.borrow_mut().clear();
1058        let _ = tree.render();
1059        assert!(layout_scales.borrow().is_empty());
1060    }
1061
1062    #[test]
1063    fn nested_scale_transforms_multiply() {
1064        let backend = RecordingTextBackend::new(Default::default());
1065        let layout_scales = backend.layout_scales.clone();
1066        let mut tree = WidgetTree::new()
1067            .with_theme(crate::presets::intui::light())
1068            .with_text_backend(std::rc::Rc::new(std::cell::RefCell::new(backend)));
1069
1070        // outer [2x] → inner [1.5x] → text. Accumulation:
1071        // quantize(2.0) = 1.25^3, then quantize(1.25^3 × 1.5) = 1.25^5.
1072        let outer = tree.add(StackWidget::new());
1073        let inner = tree.add_child(outer, StackWidget::new());
1074        tree.add_child(inner, TextPaintWidget);
1075        tree.set_transform(outer, teksilo_canvas::Transform2D::scale(2.0, 2.0));
1076        tree.set_content_transform(inner, teksilo_canvas::Transform2D::scale(1.5, 1.5));
1077
1078        tree.layout(SizeProposal::exact(400.0, 300.0));
1079        let _ = tree.render();
1080        assert_eq!(layout_scales.borrow().as_slice(), &[1.25_f32.powi(5)]);
1081    }
1082
1083    #[test]
1084    fn invalidate_all_paints_clears_post_paint_cache() {
1085        /// Widget that draws chrome in the foreground pass so the walker
1086        /// populates `cached_post_paint`.
1087        #[derive(Debug)]
1088        struct PostPaintWidget;
1089
1090        impl Widget for PostPaintWidget {
1091            fn layout_response(
1092                &self,
1093                proposal: SizeProposal,
1094                _ctx: &LayoutContext,
1095            ) -> crate::widget::LayoutResponse {
1096                proposal.resolve(50.0, 50.0).into()
1097            }
1098
1099            fn wants_post_paint(&self) -> bool {
1100                true
1101            }
1102
1103            fn post_paint(
1104                &self,
1105                bounds: teksilo_canvas::Rect,
1106                canvas: &mut teksilo_canvas::Canvas,
1107                _ctx: &PaintContext,
1108            ) {
1109                canvas.fill_rect(bounds, Color::RED);
1110            }
1111        }
1112
1113        let mut tree = WidgetTree::new().with_theme(crate::presets::intui::light());
1114        let id = tree.add(PostPaintWidget);
1115        tree.layout(SizeProposal::exact(100.0, 100.0));
1116        let _ = tree.render();
1117        assert!(
1118            tree.arena
1119                .get(id)
1120                .and_then(|n| n.cached_post_paint.as_ref())
1121                .is_some(),
1122            "render must populate cached_post_paint for a post-painting widget"
1123        );
1124
1125        tree.invalidate_all_paints();
1126        assert!(
1127            tree.arena
1128                .get(id)
1129                .and_then(|n| n.cached_post_paint.as_ref())
1130                .is_none(),
1131            "invalidate_all_paints must clear cached_post_paint too — a retained \
1132             post-paint frame can hold stale glyph UVs after atlas eviction"
1133        );
1134    }
1135
1136    #[derive(Debug)]
1137    struct ThemeAwareWidget;
1138
1139    impl Widget for ThemeAwareWidget {
1140        fn layout_response(
1141            &self,
1142            proposal: SizeProposal,
1143            _ctx: &LayoutContext,
1144        ) -> crate::widget::LayoutResponse {
1145            proposal.resolve(0.0, 0.0).into()
1146        }
1147
1148        fn paint(
1149            &self,
1150            bounds: teksilo_canvas::Rect,
1151            canvas: &mut teksilo_canvas::Canvas,
1152            ctx: &PaintContext,
1153        ) {
1154            canvas.fill_rounded_rect(
1155                bounds,
1156                teksilo_tokens::CornerRadius::uniform(4.0),
1157                ctx.theme.colors.accent,
1158            );
1159        }
1160    }
1161
1162    #[test]
1163    fn fill_widget_produces_shape_in_frame() {
1164        let mut tree = WidgetTree::new().with_theme(crate::presets::intui::light());
1165        tree.add(
1166            FillWidget::new()
1167                .background(Color::RED)
1168                .corner_radius(CornerRadius::uniform(6.0)),
1169        );
1170        tree.layout(SizeProposal::exact(100.0, 40.0));
1171        let frame = tree.render();
1172        assert_eq!(frame.shapes.len(), 1);
1173        assert_eq!(
1174            frame.shapes[0].shape,
1175            teksilo_canvas::ShapeKind::RoundedRect
1176        );
1177    }
1178
1179    #[test]
1180    fn empty_tree_renders_empty_frame() {
1181        let mut tree = WidgetTree::new();
1182        let frame = tree.render();
1183        assert!(frame.is_empty());
1184    }
1185
1186    #[test]
1187    fn render_clears_paint_dirty() {
1188        let mut tree = WidgetTree::new();
1189        tree.add(FillWidget::new().background(Color::RED));
1190        tree.layout(SizeProposal::exact(100.0, 50.0));
1191        assert!(tree.needs_paint());
1192        tree.render();
1193        assert!(!tree.needs_paint());
1194    }
1195
1196    #[test]
1197    fn dormant_widget_not_rendered() {
1198        let mut tree = WidgetTree::new();
1199        let widget = tree.add(
1200            FillWidget::new()
1201                .background(Color::RED)
1202                .corner_radius(CornerRadius::uniform(4.0)),
1203        );
1204        tree.layout(SizeProposal::exact(100.0, 50.0));
1205        let frame = tree.render();
1206        assert!(!frame.shapes.is_empty());
1207
1208        tree.set_dormant(widget);
1209        tree.layout(SizeProposal::exact(100.0, 50.0));
1210        let frame = tree.render();
1211        assert!(frame.shapes.is_empty());
1212    }
1213
1214    #[test]
1215    fn dormancy_is_recursive() {
1216        let mut tree = WidgetTree::new();
1217        let child = tree.add(
1218            FillWidget::new()
1219                .background(Color::RED)
1220                .corner_radius(CornerRadius::uniform(4.0)),
1221        );
1222        let parent = tree.add(StackWidget::new().child(child));
1223        tree.layout(SizeProposal::exact(100.0, 50.0));
1224
1225        let frame = tree.render();
1226        assert_eq!(frame.shapes.len(), 1);
1227
1228        tree.set_dormant(parent);
1229        tree.layout(SizeProposal::exact(100.0, 50.0));
1230        let frame = tree.render();
1231        assert!(frame.shapes.is_empty());
1232
1233        tree.activate(parent);
1234        tree.layout(SizeProposal::exact(100.0, 50.0));
1235        let frame = tree.render();
1236        assert_eq!(frame.shapes.len(), 1);
1237    }
1238
1239    #[test]
1240    fn set_theme_marks_all_dirty() {
1241        let mut tree = WidgetTree::new().with_theme(crate::presets::intui::light());
1242        tree.add(FillWidget::new().background(Color::RED));
1243        tree.layout(SizeProposal::exact(100.0, 50.0));
1244        tree.render();
1245
1246        assert!(!tree.needs_layout());
1247        assert!(!tree.needs_paint());
1248
1249        tree.set_theme(crate::presets::intui::dark());
1250        assert!(tree.needs_layout());
1251        assert!(tree.needs_paint());
1252    }
1253
1254    #[test]
1255    fn set_theme_changes_rendered_colors() {
1256        let mut tree = WidgetTree::new().with_theme(crate::presets::intui::light());
1257        tree.add(ThemeAwareWidget);
1258        tree.layout(SizeProposal::exact(100.0, 50.0));
1259        let light_frame = tree.render();
1260        let light_color = light_frame.shapes[0].color;
1261
1262        tree.set_theme(crate::presets::intui::dark());
1263        tree.layout(SizeProposal::exact(100.0, 50.0));
1264        let dark_frame = tree.render();
1265        let dark_color = dark_frame.shapes[0].color;
1266
1267        assert_ne!(light_color, dark_color);
1268    }
1269
1270    #[test]
1271    fn subtree_theme_override() {
1272        let mut tree = WidgetTree::new().with_theme(crate::presets::intui::light());
1273        let parent = tree.add(ThemeAwareWidget);
1274        let _child = tree.add_child(parent, ThemeAwareWidget);
1275
1276        tree.set_theme_override(parent, |theme| {
1277            theme.colors = teksilo_tokens::ColorTokens::dark_default();
1278        });
1279
1280        tree.layout(SizeProposal::exact(100.0, 50.0));
1281        let frame = tree.render();
1282
1283        let dark_accent = teksilo_tokens::ColorTokens::dark_default()
1284            .accent
1285            .to_array();
1286        assert_eq!(frame.shapes[0].color, dark_accent);
1287        assert_eq!(frame.shapes[1].color, dark_accent);
1288    }
1289
1290    #[test]
1291    fn theme_override_only_affects_subtree() {
1292        let mut tree = WidgetTree::new().with_theme(crate::presets::intui::light());
1293
1294        let _unaffected = tree.add(ThemeAwareWidget);
1295        let overridden = tree.add(ThemeAwareWidget);
1296
1297        tree.set_theme_override(overridden, |theme| {
1298            theme.colors = teksilo_tokens::ColorTokens::dark_default();
1299        });
1300
1301        tree.layout(SizeProposal::exact(100.0, 50.0));
1302        let frame = tree.render();
1303
1304        let light_accent = teksilo_tokens::ColorTokens::light_default()
1305            .accent
1306            .to_array();
1307        let dark_accent = teksilo_tokens::ColorTokens::dark_default()
1308            .accent
1309            .to_array();
1310
1311        assert_eq!(frame.shapes[0].color, light_accent);
1312        assert_eq!(frame.shapes[1].color, dark_accent);
1313    }
1314
1315    #[test]
1316    fn resolved_theme_reflects_overrides() {
1317        let mut tree = WidgetTree::new().with_theme(crate::presets::intui::light());
1318
1319        let parent = tree.add(FillWidget::new());
1320        let child = tree.add_child(parent, FillWidget::new());
1321
1322        tree.set_theme_override(parent, |theme| {
1323            theme.colors.accent = Color::RED;
1324        });
1325
1326        tree.layout(SizeProposal::exact(100.0, 50.0));
1327
1328        let parent_theme = tree.resolved_theme(parent);
1329        assert_eq!(parent_theme.colors.accent, Color::RED);
1330
1331        let child_theme = tree.resolved_theme(child);
1332        assert_eq!(child_theme.colors.accent, Color::RED);
1333    }
1334
1335    #[test]
1336    fn opacity_prop_emits_set_and_restore_around_subtree() {
1337        // A widget with opacity_prop = Some(Static(0.5)) wraps its
1338        // own paint AND its children's paint inside a SetOpacity /
1339        // RestoreOpacity pair, so the canvas's stacked-opacity model
1340        // multiplies through.
1341        let mut tree = WidgetTree::new().with_theme(crate::presets::intui::light());
1342        let parent = tree.add(StackWidget::new());
1343        let _child = tree.add_child(parent, FillWidget::new().background(Color::RED));
1344        tree.set_opacity(parent, 0.5_f32);
1345        tree.layout(SizeProposal::exact(100.0, 50.0));
1346        let frame = tree.render();
1347
1348        let mut set_count = 0;
1349        let mut restore_count = 0;
1350        for cmd in &frame.draw_order {
1351            match cmd {
1352                teksilo_canvas::DrawCommand::SetOpacity(v) => {
1353                    assert!((v - 0.5).abs() < 1e-6, "expected 0.5, got {}", v);
1354                    set_count += 1;
1355                }
1356                teksilo_canvas::DrawCommand::RestoreOpacity => restore_count += 1,
1357                _ => {}
1358            }
1359        }
1360        assert_eq!(set_count, 1, "draw_order = {:?}", frame.draw_order);
1361        assert_eq!(restore_count, 1);
1362    }
1363
1364    #[test]
1365    fn opacity_prop_zero_skips_subtree_entirely() {
1366        // Sub-perceptual opacity (< 1/512) returns early — no
1367        // SetOpacity, no children draw commands. Saves a blend pass.
1368        let mut tree = WidgetTree::new().with_theme(crate::presets::intui::light());
1369        let parent = tree.add(StackWidget::new());
1370        tree.add_child(parent, FillWidget::new().background(Color::RED));
1371        tree.set_opacity(parent, 0.0_f32);
1372        tree.layout(SizeProposal::exact(100.0, 50.0));
1373        let frame = tree.render();
1374
1375        for cmd in &frame.draw_order {
1376            assert!(
1377                !matches!(cmd, teksilo_canvas::DrawCommand::SetOpacity(_)),
1378                "fully-transparent subtree should not emit SetOpacity"
1379            );
1380        }
1381        // The red FillWidget child must not appear either.
1382        assert!(
1383            !frame
1384                .shapes
1385                .iter()
1386                .any(|s| s.color == Color::RED.to_array()),
1387            "fully-transparent subtree should not paint its descendants"
1388        );
1389    }
1390
1391    #[test]
1392    fn transform_prop_emits_push_and_pop_around_subtree() {
1393        // A widget with transform_prop = Some(Static(scale(2))) wraps
1394        // both its own paint AND its children's paint inside a
1395        // PushTransform / PopTransform pair, mirroring the opacity
1396        // pattern.
1397        let mut tree = WidgetTree::new().with_theme(crate::presets::intui::light());
1398        let parent = tree.add(StackWidget::new());
1399        let _child = tree.add_child(parent, FillWidget::new().background(Color::RED));
1400        let scale_2x = teksilo_canvas::Transform2D::scale(2.0, 2.0);
1401        tree.set_transform(parent, scale_2x);
1402        tree.layout(SizeProposal::exact(100.0, 50.0));
1403        let frame = tree.render();
1404
1405        let mut push_count = 0;
1406        let mut pop_count = 0;
1407        let mut push_value = None;
1408        for cmd in &frame.draw_order {
1409            match cmd {
1410                teksilo_canvas::DrawCommand::PushTransform(t) => {
1411                    push_count += 1;
1412                    push_value = Some(*t);
1413                }
1414                teksilo_canvas::DrawCommand::PopTransform => pop_count += 1,
1415                _ => {}
1416            }
1417        }
1418        assert_eq!(push_count, 1, "draw_order = {:?}", frame.draw_order);
1419        assert_eq!(pop_count, 1);
1420        assert_eq!(push_value, Some(scale_2x));
1421    }
1422
1423    #[test]
1424    fn content_transform_clip_wraps_outside_the_transform() {
1425        // A *content* transform (the SceneView pattern: clips_children + a
1426        // content transform set via set_content_transform) must emit its clip
1427        // OUTSIDE the transform — SetClip before PushTransform, ClearClip after
1428        // PopTransform — so the renderer scissors to the fixed parent-space
1429        // viewport instead of the pan/zoom-shifted rect. (A *self* transform
1430        // like Scale keeps the clip inside the transform; see
1431        // transform_prop_emits_push_and_pop_around_subtree.)
1432        let mut tree = WidgetTree::new().with_theme(crate::presets::intui::light());
1433        let parent = tree.add(StackWidget::new());
1434        tree.add_child(parent, FillWidget::new().background(Color::RED));
1435        tree.layout(SizeProposal::exact(100.0, 50.0));
1436        // Set after layout so no rebuild can clear the flags before render.
1437        tree.set_clips_children(parent, true);
1438        tree.set_content_transform(parent, teksilo_canvas::Transform2D::translate(50.0, 30.0));
1439        let frame = tree.render();
1440
1441        let mut set_clip = None;
1442        let mut push = None;
1443        let mut pop = None;
1444        let mut clear = None;
1445        for (i, cmd) in frame.draw_order.iter().enumerate() {
1446            match cmd {
1447                teksilo_canvas::DrawCommand::SetClip(_) => set_clip = set_clip.or(Some(i)),
1448                teksilo_canvas::DrawCommand::PushTransform(_) => push = push.or(Some(i)),
1449                teksilo_canvas::DrawCommand::PopTransform => pop = Some(i),
1450                teksilo_canvas::DrawCommand::ClearClip => clear = Some(i),
1451                _ => {}
1452            }
1453        }
1454        let (sc, pt, pop, cc) = (
1455            set_clip.expect("SetClip emitted"),
1456            push.expect("PushTransform emitted"),
1457            pop.expect("PopTransform emitted"),
1458            clear.expect("ClearClip emitted"),
1459        );
1460        assert!(
1461            sc < pt,
1462            "clip must open before the transform: SetClip@{sc}, PushTransform@{pt}; order={:?}",
1463            frame.draw_order
1464        );
1465        assert!(
1466            pop < cc,
1467            "clip must close after the transform: PopTransform@{pop}, ClearClip@{cc}"
1468        );
1469    }
1470
1471    #[test]
1472    fn identity_transform_prop_skipped() {
1473        // transform_prop = Some(Static(IDENTITY)) is a no-op — the
1474        // walker should NOT emit a PushTransform / PopTransform pair
1475        // for the rest pose. Saves a flush per identity wrapper per
1476        // frame (Scale at full visibility, Rotate at angle=0).
1477        let mut tree = WidgetTree::new().with_theme(crate::presets::intui::light());
1478        let parent = tree.add(StackWidget::new());
1479        tree.add_child(parent, FillWidget::new().background(Color::RED));
1480        tree.set_transform(parent, teksilo_canvas::Transform2D::IDENTITY);
1481        tree.layout(SizeProposal::exact(100.0, 50.0));
1482        let frame = tree.render();
1483
1484        for cmd in &frame.draw_order {
1485            assert!(
1486                !matches!(
1487                    cmd,
1488                    teksilo_canvas::DrawCommand::PushTransform(_)
1489                        | teksilo_canvas::DrawCommand::PopTransform
1490                ),
1491                "identity transform must not emit a push/pop scope"
1492            );
1493        }
1494    }
1495
1496    #[test]
1497    fn transform_scope_paint_order_opacity_outer_transform_inner() {
1498        // When both opacity_prop AND transform_prop are set on the
1499        // same node, the framework's contract is opacity OUTER and
1500        // transform INNER. This pins down the order so future
1501        // refactors don't silently flip composability.
1502        let mut tree = WidgetTree::new().with_theme(crate::presets::intui::light());
1503        let parent = tree.add(StackWidget::new());
1504        tree.add_child(parent, FillWidget::new().background(Color::RED));
1505        tree.set_opacity(parent, 0.7_f32);
1506        tree.set_transform(parent, teksilo_canvas::Transform2D::scale(2.0, 2.0));
1507        tree.layout(SizeProposal::exact(100.0, 50.0));
1508        let frame = tree.render();
1509
1510        // Find the indices of each command kind.
1511        let mut set_opacity_idx = None;
1512        let mut push_transform_idx = None;
1513        let mut pop_transform_idx = None;
1514        let mut restore_opacity_idx = None;
1515        for (i, cmd) in frame.draw_order.iter().enumerate() {
1516            match cmd {
1517                teksilo_canvas::DrawCommand::SetOpacity(_) => set_opacity_idx = Some(i),
1518                teksilo_canvas::DrawCommand::PushTransform(_) => push_transform_idx = Some(i),
1519                teksilo_canvas::DrawCommand::PopTransform => pop_transform_idx = Some(i),
1520                teksilo_canvas::DrawCommand::RestoreOpacity => restore_opacity_idx = Some(i),
1521                _ => {}
1522            }
1523        }
1524        let so = set_opacity_idx.expect("SetOpacity emitted");
1525        let pt = push_transform_idx.expect("PushTransform emitted");
1526        let popt = pop_transform_idx.expect("PopTransform emitted");
1527        let ro = restore_opacity_idx.expect("RestoreOpacity emitted");
1528        assert!(so < pt, "opacity must open before transform: {so} < {pt}");
1529        assert!(pt < popt, "transform push must precede its pop");
1530        assert!(
1531            popt < ro,
1532            "transform must close before opacity: {popt} < {ro}"
1533        );
1534    }
1535
1536    /// A composing widget that paints a RED backdrop in `paint()`, hosts a
1537    /// GREEN child, and paints a BLUE foreground in `post_paint()`. Pins the
1538    /// P-C-AP draw order: backdrop (P) → child (C) → foreground (AP).
1539    #[derive(Debug)]
1540    struct Sandwich {
1541        child: Option<crate::WidgetId>,
1542    }
1543
1544    impl Widget for Sandwich {
1545        fn build(&mut self, ctx: &mut crate::build_context::BuildContext) -> Vec<crate::WidgetId> {
1546            let c = ctx.add(FillWidget::new().background(Color::GREEN));
1547            self.child = Some(c);
1548            vec![c]
1549        }
1550
1551        fn layout_response(
1552            &self,
1553            proposal: SizeProposal,
1554            _ctx: &LayoutContext,
1555        ) -> crate::widget::LayoutResponse {
1556            proposal.resolve(0.0, 0.0).into()
1557        }
1558
1559        fn place_children(
1560            &self,
1561            bounds: teksilo_canvas::Rect,
1562            _proposal: SizeProposal,
1563            children: &mut [crate::widget::WidgetPlacement],
1564            _ctx: &LayoutContext,
1565        ) {
1566            for child in children.iter_mut() {
1567                child.origin = bounds.origin();
1568                child.size = bounds.size();
1569            }
1570        }
1571
1572        fn children(&self) -> Vec<crate::WidgetId> {
1573            self.child.iter().copied().collect()
1574        }
1575
1576        fn paint(
1577            &self,
1578            bounds: teksilo_canvas::Rect,
1579            canvas: &mut teksilo_canvas::Canvas,
1580            _ctx: &PaintContext,
1581        ) {
1582            canvas.fill_rounded_rect(bounds, CornerRadius::uniform(0.0), Color::RED);
1583        }
1584
1585        fn wants_post_paint(&self) -> bool {
1586            true
1587        }
1588
1589        fn post_paint(
1590            &self,
1591            bounds: teksilo_canvas::Rect,
1592            canvas: &mut teksilo_canvas::Canvas,
1593            _ctx: &PaintContext,
1594        ) {
1595            canvas.fill_rounded_rect(bounds, CornerRadius::uniform(0.0), Color::BLUE);
1596        }
1597    }
1598
1599    #[test]
1600    fn post_paint_emits_after_children() {
1601        // P-C-AP ordering: a composing widget's own paint() is a backdrop
1602        // (before children) and post_paint() is a foreground (after the whole
1603        // child subtree). Backdrop=RED, child=GREEN, foreground=BLUE; assert
1604        // RED < GREEN < BLUE in draw_order.
1605        let mut tree = WidgetTree::new().with_theme(crate::presets::intui::light());
1606        tree.add(Sandwich { child: None });
1607        tree.layout(SizeProposal::exact(100.0, 50.0));
1608        let frame = tree.render();
1609
1610        let color_of = |cmd: &teksilo_canvas::DrawCommand| -> Option<[f32; 4]> {
1611            match cmd {
1612                teksilo_canvas::DrawCommand::Shape(i) => frame.shapes.get(*i).map(|s| s.color),
1613                teksilo_canvas::DrawCommand::Decoration(i) => {
1614                    frame.decorations.get(*i).map(|d| d.color)
1615                }
1616                _ => None,
1617            }
1618        };
1619        // Find the first draw whose color is dominated by `dominant` channel.
1620        let find = |dominant: usize| -> Option<usize> {
1621            frame.draw_order.iter().position(|cmd| {
1622                color_of(cmd).is_some_and(|c| {
1623                    c[dominant] > 0.5 && (0..3).all(|ch| ch == dominant || c[ch] < 0.5)
1624                })
1625            })
1626        };
1627        let red = find(0).expect("backdrop (RED) painted");
1628        let green = find(1).expect("child (GREEN) painted");
1629        let blue = find(2).expect("foreground (BLUE) painted");
1630        assert!(
1631            red < green && green < blue,
1632            "expected backdrop < child < foreground; RED@{red}, GREEN@{green}, BLUE@{blue}; order={:?}",
1633            frame.draw_order
1634        );
1635    }
1636
1637    #[test]
1638    fn blur_prop_emits_begin_end_pair_around_subtree() {
1639        // A widget with blur_prop = Some(Static(8.0)) wraps both its
1640        // own paint AND its children's paint inside a BeginBlurredSubtree
1641        // / EndBlurredSubtree pair, mirroring the opacity and transform
1642        // patterns. The Begin command carries the widget's bounds and
1643        // the requested radius.
1644        let mut tree = WidgetTree::new().with_theme(crate::presets::intui::light());
1645        let parent = tree.add(StackWidget::new());
1646        let _child = tree.add_child(parent, FillWidget::new().background(Color::RED));
1647        tree.set_blur(parent, 8.0_f32);
1648        tree.layout(SizeProposal::exact(100.0, 50.0));
1649        let frame = tree.render();
1650
1651        let mut begin_count = 0;
1652        let mut end_count = 0;
1653        let mut begin_radius = None;
1654        for cmd in &frame.draw_order {
1655            match cmd {
1656                teksilo_canvas::DrawCommand::BeginBlurredSubtree { radius, .. } => {
1657                    begin_count += 1;
1658                    begin_radius = Some(*radius);
1659                }
1660                teksilo_canvas::DrawCommand::EndBlurredSubtree => end_count += 1,
1661                _ => {}
1662            }
1663        }
1664        assert_eq!(begin_count, 1, "draw_order = {:?}", frame.draw_order);
1665        assert_eq!(end_count, 1);
1666        assert_eq!(begin_radius, Some(8.0));
1667    }
1668
1669    #[test]
1670    fn blur_prop_subperceptual_radius_skipped() {
1671        // blur_prop = Some(Static(0.2)) is below the 0.5 threshold —
1672        // the walker emits no Begin/End pair so animated 0→target
1673        // patterns have zero per-frame cost when fully off.
1674        let mut tree = WidgetTree::new().with_theme(crate::presets::intui::light());
1675        let parent = tree.add(StackWidget::new());
1676        tree.add_child(parent, FillWidget::new().background(Color::RED));
1677        tree.set_blur(parent, 0.2_f32);
1678        tree.layout(SizeProposal::exact(100.0, 50.0));
1679        let frame = tree.render();
1680
1681        for cmd in &frame.draw_order {
1682            assert!(
1683                !matches!(
1684                    cmd,
1685                    teksilo_canvas::DrawCommand::BeginBlurredSubtree { .. }
1686                        | teksilo_canvas::DrawCommand::EndBlurredSubtree
1687                ),
1688                "sub-perceptual blur must not emit Begin/End"
1689            );
1690        }
1691    }
1692
1693    #[test]
1694    fn blur_scope_is_outermost_when_combined_with_opacity_and_transform() {
1695        // Architectural pin: blur is the OUTERMOST scope so it captures
1696        // the already-faded, already-transformed subtree into the
1697        // intermediate texture.  Order on enter:
1698        //   Begin → SetOpacity → PushTransform → ...paint...
1699        // Order on exit (LIFO):
1700        //   PopTransform → RestoreOpacity → End
1701        let mut tree = WidgetTree::new().with_theme(crate::presets::intui::light());
1702        let parent = tree.add(StackWidget::new());
1703        tree.add_child(parent, FillWidget::new().background(Color::RED));
1704        tree.set_blur(parent, 8.0_f32);
1705        tree.set_opacity(parent, 0.7_f32);
1706        tree.set_transform(parent, teksilo_canvas::Transform2D::scale(2.0, 2.0));
1707        tree.layout(SizeProposal::exact(100.0, 50.0));
1708        let frame = tree.render();
1709
1710        let mut begin_idx = None;
1711        let mut set_opacity_idx = None;
1712        let mut push_transform_idx = None;
1713        let mut pop_transform_idx = None;
1714        let mut restore_opacity_idx = None;
1715        let mut end_idx = None;
1716        for (i, cmd) in frame.draw_order.iter().enumerate() {
1717            match cmd {
1718                teksilo_canvas::DrawCommand::BeginBlurredSubtree { .. } => begin_idx = Some(i),
1719                teksilo_canvas::DrawCommand::SetOpacity(_) => set_opacity_idx = Some(i),
1720                teksilo_canvas::DrawCommand::PushTransform(_) => push_transform_idx = Some(i),
1721                teksilo_canvas::DrawCommand::PopTransform => pop_transform_idx = Some(i),
1722                teksilo_canvas::DrawCommand::RestoreOpacity => restore_opacity_idx = Some(i),
1723                teksilo_canvas::DrawCommand::EndBlurredSubtree => end_idx = Some(i),
1724                _ => {}
1725            }
1726        }
1727        let bg = begin_idx.expect("Begin emitted");
1728        let so = set_opacity_idx.expect("SetOpacity emitted");
1729        let pt = push_transform_idx.expect("PushTransform emitted");
1730        let popt = pop_transform_idx.expect("PopTransform emitted");
1731        let ro = restore_opacity_idx.expect("RestoreOpacity emitted");
1732        let en = end_idx.expect("End emitted");
1733        assert!(bg < so, "blur opens before opacity");
1734        assert!(so < pt, "opacity opens before transform");
1735        assert!(pt < popt);
1736        assert!(popt < ro, "transform closes before opacity");
1737        assert!(ro < en, "opacity closes before blur");
1738    }
1739
1740    #[test]
1741    fn nested_theme_overrides_compose() {
1742        let mut tree = WidgetTree::new().with_theme(crate::presets::intui::light());
1743
1744        let grandparent = tree.add(FillWidget::new());
1745        let parent = tree.add_child(grandparent, FillWidget::new());
1746        let child = tree.add_child(parent, FillWidget::new());
1747
1748        tree.set_theme_override(grandparent, |theme| {
1749            theme.colors.accent = Color::RED;
1750        });
1751        tree.set_theme_override(parent, |theme| {
1752            theme.colors.text_secondary = Color::GREEN;
1753        });
1754
1755        tree.layout(SizeProposal::exact(100.0, 50.0));
1756
1757        let child_theme = tree.resolved_theme(child);
1758        assert_eq!(child_theme.colors.accent, Color::RED);
1759        assert_eq!(child_theme.colors.text_secondary, Color::GREEN);
1760    }
1761
1762    fn painted_accents(frame: &RenderFrame) -> Vec<[f32; 4]> {
1763        frame.shapes.iter().map(|s| s.color).collect()
1764    }
1765
1766    /// The paint walk resolves the theme top-down, each node starting from its
1767    /// parent's answer, so an inner override has to see what the outer one
1768    /// wrote, and the inner one's sibling must see the outer one only.
1769    #[test]
1770    fn nested_overrides_compose_in_the_paint_walk() {
1771        let mut tree = WidgetTree::new().with_theme(crate::presets::intui::light());
1772        let outer = tree.add(ThemeAwareWidget);
1773        let inner = tree.add_child(outer, ThemeAwareWidget);
1774        let inner_leaf = tree.add_child(inner, ThemeAwareWidget);
1775        let _outer_leaf = tree.add_child(outer, ThemeAwareWidget);
1776        let _outside = tree.add(ThemeAwareWidget);
1777
1778        tree.set_theme_override(outer, |theme| {
1779            theme.colors.accent = Color::RED;
1780        });
1781        // Green only if it ran on top of the outer override.
1782        tree.set_theme_override(inner, |theme| {
1783            if theme.colors.accent == Color::RED {
1784                theme.colors.accent = Color::GREEN;
1785            }
1786        });
1787
1788        tree.layout(SizeProposal::exact(100.0, 50.0));
1789        let frame = tree.render();
1790
1791        let light = teksilo_tokens::ColorTokens::light_default()
1792            .accent
1793            .to_array();
1794        let red = Color::RED.to_array();
1795        let green = Color::GREEN.to_array();
1796        assert_eq!(
1797            painted_accents(&frame),
1798            vec![red, green, green, red, light],
1799            "outer, inner, inner's leaf, outer's other leaf, then the root outside"
1800        );
1801        assert_eq!(tree.resolved_theme(inner_leaf).colors.accent, Color::GREEN);
1802    }
1803
1804    /// A theme set at the root after an override was installed reaches a
1805    /// subtree that has no override, and passes under the override too: the
1806    /// override edits the new theme rather than freezing the old one.
1807    #[test]
1808    fn a_root_theme_change_reaches_every_subtree() {
1809        let mut tree = WidgetTree::new().with_theme(crate::presets::intui::light());
1810        let plain = tree.add(ThemeAwareWidget);
1811        let _plain_leaf = tree.add_child(plain, ThemeAwareWidget);
1812        let overridden = tree.add(ThemeAwareWidget);
1813        let _overridden_leaf = tree.add_child(overridden, ThemeAwareWidget);
1814
1815        // Touches a token the probes do not paint, so the accent they paint
1816        // is whatever the root theme says.
1817        tree.set_theme_override(overridden, |theme| {
1818            theme.colors.text_secondary = Color::GREEN;
1819        });
1820
1821        tree.layout(SizeProposal::exact(100.0, 50.0));
1822        let light = teksilo_tokens::ColorTokens::light_default()
1823            .accent
1824            .to_array();
1825        assert_eq!(painted_accents(&tree.render()), vec![light; 4]);
1826
1827        tree.set_theme(crate::presets::intui::dark());
1828        tree.layout(SizeProposal::exact(100.0, 50.0));
1829        let dark = teksilo_tokens::ColorTokens::dark_default()
1830            .accent
1831            .to_array();
1832        assert_eq!(painted_accents(&tree.render()), vec![dark; 4]);
1833        assert_eq!(
1834            tree.resolved_theme(overridden).colors.text_secondary,
1835            Color::GREEN,
1836            "the override still applies on top of the new root theme"
1837        );
1838    }
1839
1840    /// An override that stops applying (the closure reads live state, the
1841    /// way an app switches a themed surface off) takes effect at the next
1842    /// pass that repaints the subtree: nothing keeps the theme it produced
1843    /// earlier.
1844    #[test]
1845    fn an_override_that_stops_applying_is_not_remembered() {
1846        let mut tree = WidgetTree::new().with_theme(crate::presets::intui::light());
1847        let surface = tree.add(ThemeAwareWidget);
1848        let _leaf = tree.add_child(surface, ThemeAwareWidget);
1849
1850        let enabled = Rc::new(std::cell::Cell::new(true));
1851        let live = enabled.clone();
1852        tree.set_theme_override(surface, move |theme| {
1853            if live.get() {
1854                theme.colors.accent = Color::RED;
1855            }
1856        });
1857
1858        tree.layout(SizeProposal::exact(100.0, 50.0));
1859        let red = Color::RED.to_array();
1860        assert_eq!(painted_accents(&tree.render()), vec![red; 2]);
1861
1862        enabled.set(false);
1863        tree.arena.mark_subtree_needs_paint(surface);
1864        tree.arena.mark_needs_layout(surface);
1865        tree.layout(SizeProposal::exact(100.0, 50.0));
1866        let light = teksilo_tokens::ColorTokens::light_default()
1867            .accent
1868            .to_array();
1869        assert_eq!(painted_accents(&tree.render()), vec![light; 2]);
1870        assert_eq!(
1871            tree.resolved_theme(surface).colors.accent,
1872            teksilo_tokens::ColorTokens::light_default().accent
1873        );
1874    }
1875
1876    /// Records the accent of the theme the layout walk hands it.
1877    #[derive(Debug)]
1878    struct AccentRecorder {
1879        seen: Rc<std::cell::Cell<Option<Color>>>,
1880    }
1881
1882    impl Widget for AccentRecorder {
1883        fn layout_response(
1884            &self,
1885            proposal: SizeProposal,
1886            ctx: &LayoutContext,
1887        ) -> crate::widget::LayoutResponse {
1888            self.seen.set(Some(ctx.theme.colors.accent));
1889            proposal.resolve(0.0, 0.0).into()
1890        }
1891    }
1892
1893    /// The layout walk hands each node the theme its ancestors' overrides
1894    /// produce, however deep it sits, and leaves a sibling subtree alone.
1895    #[test]
1896    fn the_layout_walk_honours_an_override_at_depth() {
1897        let mut tree = WidgetTree::new().with_theme(crate::presets::intui::light());
1898        let deep_seen = Rc::new(std::cell::Cell::new(None));
1899        let plain_seen = Rc::new(std::cell::Cell::new(None));
1900
1901        let themed = tree.add(crate::test_widgets::StackWidget::new());
1902        let middle = tree.add_child(themed, crate::test_widgets::StackWidget::new());
1903        let deep = tree.add_child(
1904            middle,
1905            AccentRecorder {
1906                seen: deep_seen.clone(),
1907            },
1908        );
1909        // A child, so the walk visits `deep` itself rather than only placing
1910        // it from its parent.
1911        tree.add_child(deep, FillWidget::new());
1912        let plain = tree.add(crate::test_widgets::StackWidget::new());
1913        let plain_deep = tree.add_child(
1914            plain,
1915            AccentRecorder {
1916                seen: plain_seen.clone(),
1917            },
1918        );
1919        tree.add_child(plain_deep, FillWidget::new());
1920
1921        tree.set_theme_override(themed, |theme| {
1922            theme.colors.accent = Color::RED;
1923        });
1924        tree.layout(SizeProposal::exact(400.0, 300.0));
1925
1926        assert_eq!(deep_seen.get(), Some(Color::RED), "under the override");
1927        assert_eq!(
1928            plain_seen.get(),
1929            Some(teksilo_tokens::ColorTokens::light_default().accent),
1930            "beside it"
1931        );
1932    }
1933
1934    /// Overlay content that hangs below an overridden widget is laid out and
1935    /// painted by its own walk, started at the content rather than at a root,
1936    /// and still sees the override above it.
1937    #[test]
1938    fn overlay_content_below_an_override_inherits_it() {
1939        let mut tree = WidgetTree::new().with_theme(crate::presets::intui::light());
1940        let anchor = tree.add(ThemeAwareWidget);
1941        let content = tree.add_child(anchor, ThemeAwareWidget);
1942        tree.set_theme_override(anchor, |theme| {
1943            theme.colors.accent = Color::RED;
1944        });
1945        tree.show_overlay(crate::overlay::OverlayRequest::new(
1946            content,
1947            anchor,
1948            crate::overlay::OverlayPlacement::Centered,
1949            crate::overlay::DismissBehavior::Manual,
1950        ));
1951
1952        tree.layout(SizeProposal::exact(100.0, 50.0));
1953        let red = Color::RED.to_array();
1954        assert_eq!(
1955            painted_accents(&tree.render()),
1956            vec![red; 2],
1957            "the anchor, then its overlay content in the overlay loop"
1958        );
1959    }
1960
1961    /// The cost this guards: a theme override used to be re-run, on a fresh
1962    /// clone of the whole `Theme`, for every widget below it and on every
1963    /// pass. One override at a window's root therefore cloned the theme once
1964    /// per widget per layout. Each walk now runs it once, at the node that
1965    /// carries it, and lends the result to the subtree.
1966    #[test]
1967    fn an_override_runs_once_per_walk_however_large_its_subtree() {
1968        let mut tree = WidgetTree::new().with_theme(crate::presets::intui::light());
1969        let root = tree.add(ThemeAwareWidget);
1970        let mut leaves = Vec::new();
1971        for _ in 0..8 {
1972            let branch = tree.add_child(root, ThemeAwareWidget);
1973            for _ in 0..8 {
1974                leaves.push(tree.add_child(branch, ThemeAwareWidget));
1975            }
1976        }
1977        let runs = Rc::new(std::cell::Cell::new(0_usize));
1978        let counter = runs.clone();
1979        tree.set_theme_override(root, move |theme| {
1980            counter.set(counter.get() + 1);
1981            theme.colors.accent = Color::RED;
1982        });
1983
1984        tree.layout(SizeProposal::exact(400.0, 300.0));
1985        assert_eq!(runs.get(), 1, "one layout walk over 73 widgets");
1986
1987        let frame = tree.render();
1988        assert_eq!(runs.get(), 2, "one paint walk over 73 widgets");
1989        assert_eq!(frame.shapes.len(), 73);
1990        assert!(
1991            painted_accents(&frame)
1992                .iter()
1993                .all(|c| *c == Color::RED.to_array())
1994        );
1995
1996        // A new proposal lays every widget out again, and a repaint of the
1997        // whole subtree paints every widget again; still one run each.
1998        tree.layout(SizeProposal::exact(401.0, 300.0));
1999        assert_eq!(runs.get(), 3, "one more layout walk");
2000        tree.arena.mark_subtree_needs_paint(root);
2001        tree.render();
2002        assert_eq!(runs.get(), 4, "one more paint walk");
2003    }
2004
2005    /// A frame repaints what is dirty and replays the cache for the rest. An
2006    /// override over a subtree that is all cache hits has nothing to theme,
2007    /// so it must not run (and clone the theme) just because the walk passed
2008    /// through it; once something below it repaints, it runs, once.
2009    #[test]
2010    fn an_override_over_a_clean_subtree_does_not_run_in_paint() {
2011        let mut tree = WidgetTree::new().with_theme(crate::presets::intui::light());
2012        let themed = tree.add(ThemeAwareWidget);
2013        let branch = tree.add_child(themed, ThemeAwareWidget);
2014        let deep = tree.add_child(branch, ThemeAwareWidget);
2015        let _deep_leaf = tree.add_child(deep, ThemeAwareWidget);
2016        let elsewhere = ColorProbe::new(Color::BLUE);
2017        let elsewhere_paints = elsewhere.paints.clone();
2018        let elsewhere = tree.add(elsewhere);
2019
2020        let runs = Rc::new(std::cell::Cell::new(0_usize));
2021        let counter = runs.clone();
2022        tree.set_theme_override(themed, move |theme| {
2023            counter.set(counter.get() + 1);
2024            theme.colors.accent = Color::RED;
2025        });
2026        tree.layout(SizeProposal::exact(400.0, 300.0));
2027        tree.render();
2028        let after_first_frame = runs.get();
2029
2030        // Only the widget outside the override repaints: the walk still
2031        // passes through the overridden subtree to replay its cache.
2032        tree.mark_needs_paint(elsewhere);
2033        let painted_before = elsewhere_paints.get();
2034        tree.render();
2035        assert_eq!(
2036            elsewhere_paints.get(),
2037            painted_before + 1,
2038            "the frame did walk and paint"
2039        );
2040        assert_eq!(
2041            runs.get(),
2042            after_first_frame,
2043            "nothing under the override repainted, so it did not run"
2044        );
2045
2046        // One widget deep under the override repaints: the override runs once
2047        // for it, and the widget still paints in the overridden colour.
2048        tree.mark_needs_paint(deep);
2049        let frame = tree.render();
2050        assert_eq!(runs.get(), after_first_frame + 1);
2051        assert_eq!(
2052            painted_accents(&frame),
2053            vec![Color::RED.to_array(); 4],
2054            "the replayed cache and the repainted widget alike"
2055        );
2056    }
2057
2058    /// Records the accent its `after_paint` and `post_paint` are handed.
2059    #[derive(Debug)]
2060    struct HookThemeRecorder {
2061        after: Rc<std::cell::Cell<Option<Color>>>,
2062        post: Rc<std::cell::Cell<Option<Color>>>,
2063    }
2064
2065    impl Widget for HookThemeRecorder {
2066        fn layout_response(
2067            &self,
2068            proposal: SizeProposal,
2069            _ctx: &LayoutContext,
2070        ) -> crate::widget::LayoutResponse {
2071            proposal.resolve(0.0, 0.0).into()
2072        }
2073
2074        fn wants_after_paint(&self) -> bool {
2075            true
2076        }
2077
2078        fn after_paint(&self, _view: &crate::widget::WidgetTreeView<'_>, ctx: &PaintContext) {
2079            self.after.set(Some(ctx.theme.colors.accent));
2080        }
2081
2082        fn wants_post_paint(&self) -> bool {
2083            true
2084        }
2085
2086        fn post_paint(&self, _bounds: Rect, _canvas: &mut Canvas, ctx: &PaintContext) {
2087            self.post.set(Some(ctx.theme.colors.accent));
2088        }
2089    }
2090
2091    /// `after_paint` runs on every frame, cached or not, and `post_paint` on a
2092    /// repaint; both read the theme through the same deferred scope as
2093    /// `paint`, and both get the override's.
2094    #[test]
2095    fn the_other_paint_hooks_see_the_override() {
2096        let mut tree = WidgetTree::new().with_theme(crate::presets::intui::light());
2097        let themed = tree.add(ThemeAwareWidget);
2098        let after = Rc::new(std::cell::Cell::new(None));
2099        let post = Rc::new(std::cell::Cell::new(None));
2100        tree.add_child(
2101            themed,
2102            HookThemeRecorder {
2103                after: after.clone(),
2104                post: post.clone(),
2105            },
2106        );
2107        let elsewhere = tree.add(ThemeAwareWidget);
2108        tree.set_theme_override(themed, |theme| {
2109            theme.colors.accent = Color::RED;
2110        });
2111        tree.layout(SizeProposal::exact(400.0, 300.0));
2112        tree.render();
2113        assert_eq!(after.get(), Some(Color::RED));
2114        assert_eq!(post.get(), Some(Color::RED));
2115
2116        // A frame that repaints only outside the override: the recorder is a
2117        // cache hit, but its `after_paint` still runs, with the override.
2118        after.set(None);
2119        tree.mark_needs_paint(elsewhere);
2120        tree.render();
2121        assert_eq!(after.get(), Some(Color::RED));
2122    }
2123
2124    /// Leaf that paints one rect in a colour read at paint time, in its own
2125    /// pass and optionally in its foreground pass, and counts its paints.
2126    #[derive(Debug)]
2127    struct ColorProbe {
2128        color: Rc<std::cell::Cell<Color>>,
2129        paints: Rc<std::cell::Cell<u32>>,
2130        post_paints: Rc<std::cell::Cell<u32>>,
2131        foreground: bool,
2132    }
2133
2134    impl ColorProbe {
2135        fn new(color: Color) -> Self {
2136            Self {
2137                color: Rc::new(std::cell::Cell::new(color)),
2138                paints: Rc::new(std::cell::Cell::new(0)),
2139                post_paints: Rc::new(std::cell::Cell::new(0)),
2140                foreground: false,
2141            }
2142        }
2143    }
2144
2145    impl Widget for ColorProbe {
2146        fn layout_response(
2147            &self,
2148            proposal: SizeProposal,
2149            _ctx: &LayoutContext,
2150        ) -> crate::widget::LayoutResponse {
2151            proposal.resolve(40.0, 40.0).into()
2152        }
2153
2154        fn paint(&self, bounds: Rect, canvas: &mut Canvas, _ctx: &PaintContext) {
2155            self.paints.set(self.paints.get() + 1);
2156            canvas.fill_rect(bounds, self.color.get());
2157        }
2158
2159        fn wants_post_paint(&self) -> bool {
2160            self.foreground
2161        }
2162
2163        fn post_paint(&self, bounds: Rect, canvas: &mut Canvas, _ctx: &PaintContext) {
2164            self.post_paints.set(self.post_paints.get() + 1);
2165            canvas.fill_rect(bounds, self.color.get());
2166        }
2167    }
2168
2169    /// Container that places each child 40×40 at a fixed offset from its own
2170    /// origin, whatever its own size, so a child can leave and re-enter the
2171    /// container's clip without moving.
2172    #[derive(Debug)]
2173    struct OffsetContainer {
2174        offset: f32,
2175    }
2176
2177    impl Widget for OffsetContainer {
2178        fn layout_response(
2179            &self,
2180            proposal: SizeProposal,
2181            _ctx: &LayoutContext,
2182        ) -> crate::widget::LayoutResponse {
2183            proposal.resolve(0.0, 0.0).into()
2184        }
2185
2186        fn place_children(
2187            &self,
2188            bounds: Rect,
2189            _proposal: SizeProposal,
2190            children: &mut [WidgetPlacement],
2191            _ctx: &LayoutContext,
2192        ) {
2193            for child in children.iter_mut() {
2194                child.origin = teksilo_canvas::Point::new(bounds.x + self.offset, bounds.y);
2195                child.size = teksilo_canvas::Size::new(40.0, 40.0);
2196            }
2197        }
2198    }
2199
2200    fn painted_colors(frame: &RenderFrame) -> Vec<[f32; 4]> {
2201        frame.decorations.iter().map(|d| d.color).collect()
2202    }
2203
2204    /// A clipping root 200 px wide with a probe at x = 150. Narrowing the
2205    /// root to 100 px clips the probe out without moving it.
2206    fn clipped_probe_tree(probe: ColorProbe) -> (WidgetTree, WidgetId) {
2207        let mut tree = WidgetTree::new().with_theme(crate::presets::intui::light());
2208        let root = tree.add(OffsetContainer { offset: 150.0 });
2209        tree.set_clips_children(root, true);
2210        let child = tree.add_child(root, probe);
2211        tree.layout(SizeProposal::exact(200.0, 50.0));
2212        (tree, child)
2213    }
2214
2215    #[test]
2216    fn clipped_out_dirty_node_repaints_when_it_comes_back_into_view() {
2217        let probe = ColorProbe::new(Color::RED);
2218        let (color, paints) = (probe.color.clone(), probe.paints.clone());
2219        let (mut tree, child) = clipped_probe_tree(probe);
2220        assert!(painted_colors(&tree.render()).contains(&Color::RED.to_array()));
2221
2222        tree.layout(SizeProposal::exact(100.0, 50.0));
2223        assert_eq!(tree.bounds(child).x, 150.0, "the probe must not move");
2224        color.set(Color::BLUE);
2225        tree.arena.mark_needs_paint(child);
2226        let frame = tree.render();
2227        assert!(
2228            painted_colors(&frame).is_empty(),
2229            "the probe is clipped out"
2230        );
2231        assert_eq!(paints.get(), 1, "a clipped-out node does not paint");
2232
2233        tree.layout(SizeProposal::exact(200.0, 50.0));
2234        let colors = painted_colors(&tree.render());
2235        assert_eq!(
2236            colors,
2237            vec![Color::BLUE.to_array()],
2238            "a node dirtied while clipped out must not replay its old paint"
2239        );
2240        assert_eq!(paints.get(), 2);
2241    }
2242
2243    #[test]
2244    fn clipped_out_clean_node_keeps_its_cache() {
2245        let probe = ColorProbe::new(Color::RED);
2246        let paints = probe.paints.clone();
2247        let (mut tree, child) = clipped_probe_tree(probe);
2248        let _ = tree.render();
2249
2250        tree.layout(SizeProposal::exact(100.0, 50.0));
2251        let _ = tree.render();
2252        assert!(
2253            tree.arena.get(child).unwrap().cached_paint.is_some(),
2254            "a clean node keeps its cache while clipped out"
2255        );
2256
2257        tree.layout(SizeProposal::exact(200.0, 50.0));
2258        let colors = painted_colors(&tree.render());
2259        assert_eq!(colors, vec![Color::RED.to_array()]);
2260        assert_eq!(paints.get(), 1, "the clean node replays its cache");
2261    }
2262
2263    #[test]
2264    fn node_dirtied_under_a_transparent_ancestor_repaints_when_it_fades_in() {
2265        let probe = ColorProbe::new(Color::RED);
2266        let (color, paints) = (probe.color.clone(), probe.paints.clone());
2267        let mut tree = WidgetTree::new().with_theme(crate::presets::intui::light());
2268        let parent = tree.add(StackWidget::new());
2269        let child = tree.add_child(parent, probe);
2270        let opacity = crate::signal::Signal::new(1.0_f32);
2271        tree.set_opacity(parent, opacity.clone());
2272        tree.layout(SizeProposal::exact(100.0, 50.0));
2273        let _ = tree.render();
2274
2275        opacity.set(0.0);
2276        tree.layout(SizeProposal::exact(100.0, 50.0));
2277        color.set(Color::BLUE);
2278        tree.arena.mark_needs_paint(child);
2279        let _ = tree.render();
2280        assert_eq!(paints.get(), 1, "a transparent subtree does not paint");
2281
2282        opacity.set(1.0);
2283        tree.layout(SizeProposal::exact(100.0, 50.0));
2284        let colors = painted_colors(&tree.render());
2285        assert_eq!(colors, vec![Color::BLUE.to_array()]);
2286    }
2287
2288    #[test]
2289    fn transparent_dirty_node_repaints_when_it_fades_in() {
2290        let probe = ColorProbe::new(Color::RED);
2291        let color = probe.color.clone();
2292        let mut tree = WidgetTree::new().with_theme(crate::presets::intui::light());
2293        let node = tree.add(probe);
2294        let opacity = crate::signal::Signal::new(1.0_f32);
2295        tree.set_opacity(node, opacity.clone());
2296        tree.layout(SizeProposal::exact(100.0, 50.0));
2297        let _ = tree.render();
2298
2299        // The node's own opacity scope stamps it as visited before the
2300        // sub-perceptual early return, so only the paint stamp tells the
2301        // clear loop that `paint()` never ran. Nothing visible depends on it
2302        // here: the opacity binding re-marks the node on fade-in, so it
2303        // repaints either way. This pins the cache itself, which must not
2304        // outlive the change that dirtied it.
2305        opacity.set(0.0);
2306        tree.layout(SizeProposal::exact(100.0, 50.0));
2307        color.set(Color::BLUE);
2308        tree.arena.mark_needs_paint(node);
2309        let _ = tree.render();
2310        assert!(
2311            tree.arena.get(node).unwrap().cached_paint.is_none(),
2312            "a node dirtied while transparent drops its stale cache"
2313        );
2314
2315        opacity.set(1.0);
2316        tree.layout(SizeProposal::exact(100.0, 50.0));
2317        let colors = painted_colors(&tree.render());
2318        assert_eq!(colors, vec![Color::BLUE.to_array()]);
2319    }
2320
2321    /// A guard, not a test of the stale-cache fix: dormant nodes never reach
2322    /// the end-of-render clear, and activation marks a node for repaint on
2323    /// its own. It keeps that path covered beside the cases the fix does
2324    /// change.
2325    #[test]
2326    fn a_node_changed_while_dormant_repaints_when_activated() {
2327        let probe = ColorProbe::new(Color::RED);
2328        let color = probe.color.clone();
2329        let mut tree = WidgetTree::new().with_theme(crate::presets::intui::light());
2330        let node = tree.add(probe);
2331        tree.layout(SizeProposal::exact(100.0, 50.0));
2332        let _ = tree.render();
2333
2334        tree.set_dormant(node);
2335        color.set(Color::BLUE);
2336        tree.arena.mark_needs_paint(node);
2337        tree.layout(SizeProposal::exact(100.0, 50.0));
2338        let _ = tree.render();
2339
2340        tree.activate(node);
2341        tree.layout(SizeProposal::exact(100.0, 50.0));
2342        let colors = painted_colors(&tree.render());
2343        assert_eq!(colors, vec![Color::BLUE.to_array()]);
2344    }
2345
2346    /// Stacks its children at its origin, as `StackWidget` does, and counts
2347    /// its layouts.
2348    #[derive(Debug)]
2349    struct CountingStack {
2350        children: Vec<WidgetId>,
2351        layouts: Rc<std::cell::Cell<u32>>,
2352    }
2353
2354    impl Widget for CountingStack {
2355        fn layout_response(
2356            &self,
2357            proposal: SizeProposal,
2358            _ctx: &LayoutContext,
2359        ) -> crate::widget::LayoutResponse {
2360            self.layouts.set(self.layouts.get() + 1);
2361            proposal.resolve(0.0, 0.0).into()
2362        }
2363
2364        fn place_children(
2365            &self,
2366            bounds: Rect,
2367            _proposal: SizeProposal,
2368            children: &mut [WidgetPlacement],
2369            _ctx: &LayoutContext,
2370        ) {
2371            for child in children.iter_mut() {
2372                child.origin = bounds.origin();
2373                child.size = bounds.size();
2374            }
2375        }
2376
2377        fn children(&self) -> Vec<WidgetId> {
2378            self.children.clone()
2379        }
2380    }
2381
2382    /// A destroyed subtree is not in the next frame, though nothing else
2383    /// changed and the frame would otherwise be replayed whole, and its
2384    /// parent lays out again without it.
2385    #[test]
2386    fn a_destroyed_subtree_leaves_the_next_frame() {
2387        let mut tree = WidgetTree::new().with_theme(crate::presets::intui::light());
2388        let red = tree.add(ColorProbe::new(Color::RED));
2389        let blue = tree.add(ColorProbe::new(Color::BLUE));
2390        let layouts = Rc::new(std::cell::Cell::new(0));
2391        let root = tree.add(CountingStack {
2392            children: vec![red, blue],
2393            layouts: layouts.clone(),
2394        });
2395        tree.layout(SizeProposal::exact(100.0, 50.0));
2396        assert_eq!(painted_colors(&tree.render()).len(), 2);
2397        tree.layout(SizeProposal::exact(100.0, 50.0));
2398        let settled = layouts.get();
2399
2400        tree.destroy_subtree_for_testing(red);
2401        tree.layout(SizeProposal::exact(100.0, 50.0));
2402        assert!(layouts.get() > settled, "the parent laid out again");
2403        assert_eq!(painted_colors(&tree.render()), vec![Color::BLUE.to_array()]);
2404
2405        // A root has no parent to mark: the composed frame goes all the same.
2406        tree.destroy_subtree_for_testing(root);
2407        tree.layout(SizeProposal::exact(100.0, 50.0));
2408        assert!(painted_colors(&tree.render()).is_empty());
2409    }
2410
2411    /// The same through a handler's `EventContext::destroy`, the door an
2412    /// application takes at run time.
2413    #[test]
2414    fn a_subtree_a_handler_destroys_leaves_the_next_frame() {
2415        use crate::widget_builder::WidgetBuilder;
2416        let mut tree = WidgetTree::new().with_theme(crate::presets::intui::light());
2417        let red = tree.add(ColorProbe::new(Color::RED));
2418        let button =
2419            tree.add(ColorProbe::new(Color::BLUE).on_tap(move |_tap, ctx| ctx.destroy(red)));
2420        tree.add(StackWidget::new().child(red).child(button));
2421        tree.layout(SizeProposal::exact(100.0, 50.0));
2422        assert_eq!(painted_colors(&tree.render()).len(), 2);
2423
2424        tree.synthesise_tap(button);
2425        assert!(tree.arena.get(red).is_none(), "the tap destroyed it");
2426        tree.layout(SizeProposal::exact(100.0, 50.0));
2427        assert_eq!(painted_colors(&tree.render()), vec![Color::BLUE.to_array()]);
2428    }
2429
2430    #[test]
2431    fn clipped_out_dirty_node_reruns_its_foreground_pass() {
2432        let mut probe = ColorProbe::new(Color::RED);
2433        probe.foreground = true;
2434        let (color, post_paints) = (probe.color.clone(), probe.post_paints.clone());
2435        let (mut tree, child) = clipped_probe_tree(probe);
2436        let _ = tree.render();
2437        assert_eq!(post_paints.get(), 1);
2438
2439        tree.layout(SizeProposal::exact(100.0, 50.0));
2440        color.set(Color::BLUE);
2441        tree.arena.mark_needs_paint(child);
2442        let _ = tree.render();
2443        assert!(
2444            tree.arena.get(child).unwrap().cached_post_paint.is_none(),
2445            "the stale foreground cache is dropped with the main one"
2446        );
2447
2448        tree.layout(SizeProposal::exact(200.0, 50.0));
2449        let colors = painted_colors(&tree.render());
2450        assert_eq!(
2451            colors,
2452            vec![Color::BLUE.to_array(), Color::BLUE.to_array()],
2453            "both passes repaint in the new colour"
2454        );
2455        assert_eq!(post_paints.get(), 2);
2456    }
2457}