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