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 teksilo_canvas::quantize_raster_scale;
7
8/// Accessibility preferences passed through the paint recursion.
9struct A11yPaintPrefs {
10    high_contrast: bool,
11    reduced_motion: bool,
12    large_text: bool,
13    /// Combined user×OS text-scale factor (the logical accessibility
14    /// magnification). Surfaced to widgets via `PaintContext::text_scale`.
15    text_scale: f32,
16    /// Window-active state (`focused AND not occluded`). Surfaced to widgets
17    /// via `PaintContext::window_active`. (Carried alongside the a11y prefs as
18    /// a per-paint ambient flag; not itself an accessibility preference.)
19    window_active: bool,
20}
21
22impl WidgetTree {
23    /// Paint all active widgets and produce a RenderFrame.
24    /// Uses per-widget paint caching: only widgets with `needs_paint` are
25    /// re-painted; clean widgets reuse their cached paint output.
26    /// Also caches the full assembled frame — if no widget needs painting,
27    /// the previous frame is returned immediately.
28    pub fn render(&mut self) -> std::rc::Rc<RenderFrame> {
29        let mut noop = crate::window::NoopWindowOps;
30        self.render_with_ops(&mut noop)
31    }
32
33    /// Render a frame, threading the app's
34    /// [`WindowOps`](crate::window::WindowOps) sink through any
35    /// state-change-triggered handlers (data-driven rebuild, binding
36    /// flush). Called by `teksilo-app` during its paint pipeline.
37    pub fn render_with_ops(
38        &mut self,
39        ops: &mut dyn crate::window::WindowOps,
40    ) -> std::rc::Rc<RenderFrame> {
41        self.process_state_changes(&mut *ops);
42
43        // Always tick the animated-quad registry — even on the cache-hit
44        // early-out we still need fresh phase in the frame's
45        // anim_params, because every looping slot advances. Widgets
46        // whose paint() wasn't re-run (all of them on cache hit) keep
47        // their last DrawCommand::AnimatedQuad in the cached frame;
48        // the renderer reads the live params from `frame.anim_params`
49        // at the slot index stored in the draw command.
50        //
51        // The registry's internal `scratch` buffer owns the params; we
52        // only copy when actually writing them into the frame (below).
53        // Taking a borrow here lets us skip the copy entirely in the
54        // non-cache-hit branch where we allocate a fresh frame anyway.
55        let now = std::time::Instant::now();
56        let has_animations = self.animated_quads.has_running();
57        if has_animations {
58            self.animated_quads
59                .tick(now, &self.arena, self.paint_epoch, &self.theme);
60        }
61
62        // Cache-hit short-circuit: nothing in the tree was marked
63        // needs_paint, so the pixels are identical to the previous
64        // frame apart from the animated-quad uniforms. We deliberately
65        // do NOT bump `paint_epoch` here — if we did, every widget's
66        // `last_painted_epoch` would silently age out and the animation
67        // scheduler would treat them as "off-screen" on the next tick.
68        // Holding the epoch steady preserves the visibility gate
69        // through arbitrarily many idle cache-hit frames. The fresh
70        // `anim_params` we just computed are attached so shader-driven
71        // animations keep advancing even when paint() doesn't run.
72        //
73        // `Rc::make_mut` short-circuits to a mutable borrow when the
74        // tree is the sole owner of the cached frame — which is the
75        // common case, since the app-side caller typically drops the
76        // previous frame before calling `render()` again. If the
77        // caller holds a second Rc clone (e.g. two back-to-back
78        // renders without letting the first drop) we fall back to a
79        // single deep clone for that frame.
80        if !self.arena.any_needs_paint() && self.cached_frame.is_some() {
81            // Cache-hit path. paint_epoch is frozen, so visible
82            // subscribers' `last_painted_epoch == paint_epoch` still
83            // holds. Re-arm the frame-tick chain BEFORE refreshing the
84            // cached frame so we don't tangle borrows.
85            self.arm_frame_tick_for_visible_subscribers();
86
87            if let Some(cached) = self.cached_frame.as_mut() {
88                let frame = std::rc::Rc::make_mut(cached);
89                if has_animations {
90                    let src = self.animated_quads.scratch_slice();
91                    frame.anim_params.clear();
92                    frame.anim_params.extend_from_slice(src);
93                }
94                // Refresh the text backend's glyph timestamps for every
95                // layout baked into the reused frame — same contract as
96                // the per-widget cached_paint path below. Without this,
97                // a window that idles on the full-frame cache while
98                // text work elsewhere (another window, or measure-only
99                // layout passes) advances the atlas generation would
100                // have its still-visible glyphs evicted and their atlas
101                // slots reused, garbling the cached quads.
102                if !frame.layout_keys.is_empty()
103                    && let Some(tb) = &self.text_backend
104                {
105                    let mut tb = tb.borrow_mut();
106                    for key in &frame.layout_keys {
107                        tb.touch_layout(*key);
108                    }
109                    #[cfg(debug_assertions)]
110                    debug_validate_layout_keys(&*tb, &frame.layout_keys, None);
111                }
112                return std::rc::Rc::clone(cached);
113            }
114        }
115
116        self.paint_epoch = self.paint_epoch.saturating_add(1);
117        let paint_epoch = self.paint_epoch;
118
119        let mut frame = RenderFrame::new();
120        // `effective_theme` carries the user/OS text-scale multiplier baked into
121        // its typography, so painted glyphs match the scaled layout sizes. When
122        // the window is inactive, paint against the accent-desaturated
123        // projection so every accent-coloured control (default button, Toggle,
124        // checked Checkbox/Radio, selected Tab/Segment, Slider fill,
125        // ProgressBar, focus rings) greys out — the Qt `QPalette::Inactive`
126        // model, resolved once theme-side instead of per widget. Colours only;
127        // typography is unchanged, so this is repaint-only (geometry stable).
128        let base_theme = if self.is_window_active() {
129            self.effective_theme.clone()
130        } else {
131            self.effective_theme.for_inactive_window()
132        };
133        // When the OS "increase contrast" preference is set, project the
134        // (already active/inactive-adjusted) palette into its high-contrast
135        // variant (WCAG 1.4.6 Enhanced / EN 301 549 11.7). Colours only, so
136        // this stays repaint-only like the inactive-window swap; the HC accent
137        // / focus overrides win over the inactive desaturation while it's on.
138        let base_theme = if self.prefers_high_contrast {
139            base_theme.for_high_contrast()
140        } else {
141            base_theme
142        };
143        let text_backend = self.text_backend.clone();
144        let a11y_prefs = A11yPaintPrefs {
145            high_contrast: self.prefers_high_contrast,
146            reduced_motion: self.prefers_reduced_motion,
147            large_text: self.text_scale_factor > 1.0,
148            text_scale: self.effective_text_scale,
149            window_active: self.is_window_active(),
150        };
151
152        let overlay_skip: std::collections::HashSet<WidgetId> = self
153            .overlay_manager
154            .active_content_ids()
155            .into_iter()
156            .collect();
157
158        // Interactive overlay rects for this frame, handed to
159        // `after_paint` via `WidgetTreeView`. Chrome aggregators
160        // (`TitleBar`) subtract them from the geometry they publish to
161        // the OS — an overlay floats above the caption, so its pixels
162        // must not be reported as draggable chrome.
163        let overlay_rects: Vec<Rect> = self.overlay_manager.interactive_rects();
164
165        for root_id in self.arena.roots() {
166            // Don't descend into overlay content via its anchor parent — it
167            // is painted via the dedicated overlay loop below. Without this,
168            // the overlay content paints twice per frame.
169            if overlay_skip.contains(&root_id) {
170                continue;
171            }
172            paint_widget_cached(
173                &mut self.arena,
174                root_id,
175                &mut frame,
176                &base_theme,
177                &text_backend,
178                None,
179                &a11y_prefs,
180                paint_epoch,
181                &overlay_skip,
182                &overlay_rects,
183                self.layout_direction,
184                // Root starts enabled; the walker ANDs in each node's
185                // own `enabled_state` as it descends.
186                true,
187                // Root is at screen scale; transform scopes below
188                // multiply in their own scale.
189                1.0,
190            );
191        }
192
193        for content_id in self.overlay_manager.active_content_ids() {
194            paint_widget_cached(
195                &mut self.arena,
196                content_id,
197                &mut frame,
198                &base_theme,
199                &text_backend,
200                None,
201                &a11y_prefs,
202                paint_epoch,
203                &overlay_skip,
204                &overlay_rects,
205                self.layout_direction,
206                // Overlays detach from their anchor's enabled-state.
207                // A tooltip / popover stays enabled even if its
208                // anchor was disabled — overlays receive their own
209                // explicit enabled-state if they need one.
210                true,
211                // Overlays render at screen scale regardless of their
212                // anchor's transform scopes.
213                1.0,
214            );
215        }
216
217        // Clear `needs_paint` on every active node. Mutation during
218        // iter — fill the reusable scratch first (zero-alloc once
219        // warm), then drive the loop from the snapshot.
220        self.arena.fill_active_ids(&mut self.active_ids_scratch);
221        let ids = std::mem::take(&mut self.active_ids_scratch);
222        for &id in &ids {
223            if let Some(node) = self.arena.get_mut(id) {
224                node.dirty.needs_paint = false;
225            }
226        }
227        self.active_ids_scratch = ids;
228
229        if has_animations {
230            frame
231                .anim_params
232                .extend_from_slice(self.animated_quads.scratch_slice());
233        }
234        frame.debug_validate_stacks();
235        let rc = std::rc::Rc::new(frame);
236        self.cached_frame = Some(std::rc::Rc::clone(&rc));
237        // Full-render path: subscribers whose owners were just painted
238        // have `last_painted_epoch == paint_epoch`. Re-arm the
239        // frame-tick chain so per-frame effects keep ticking. When all
240        // subscribers are off-screen this returns false and the chain
241        // dies — exactly the bug fix that motivated this scheduler.
242        self.arm_frame_tick_for_visible_subscribers();
243        rc
244    }
245
246    /// Walk the frame-tick subscriber set and arm `frame_tick_requested`
247    /// if any subscriber's owner is currently visible. Called from
248    /// `render_with_ops` (both cache-hit and full-render paths).
249    pub(crate) fn arm_frame_tick_for_visible_subscribers(&self) {
250        if self
251            .frame_tick_scheduler
252            .should_arm_frame_tick(&self.arena, self.paint_epoch)
253        {
254            self.frame_tick_requested.set(true);
255        }
256    }
257}
258
259/// Recursive paint pass with per-widget caching.
260/// Only re-runs `paint()` for widgets with `needs_paint` set; clean widgets
261/// reuse their `cached_paint` output. The tree walk still runs for clip/child
262/// ordering, but skips the expensive `paint()` call for clean widgets.
263///
264/// `parent_effective_enabled` is the AND of every ancestor's `enabled_state`
265/// resolved value (start `true` at root). The walker ANDs this with the
266/// current node's `enabled_state` to produce `this_effective_enabled`, which
267/// it both injects into the node's `PaintContext` and forwards as the parent
268/// value to children. This is the single mechanism by which leaf widgets see
269/// the arena's enabled-state at paint time without needing to walk ancestors
270/// themselves (`PaintContext` carries no `WidgetId` or arena reference).
271///
272/// `accumulated_raster_scale` is the quantized product of every ancestor
273/// transform scope's scale (start `1.0` at root). The walker multiplies in
274/// this node's own transform scale, sets the result as the text backend's
275/// ambient raster scale around the node's paint (so text drawn here
276/// rasterizes densely enough for the GPU transform that will stretch it),
277/// stamps it on the node's paint cache, and forwards it to children.
278#[allow(clippy::too_many_arguments)]
279fn paint_widget_cached(
280    arena: &mut WidgetArena,
281    id: WidgetId,
282    frame: &mut RenderFrame,
283    base_theme: &crate::styles::Theme,
284    text_backend: &Option<Rc<RefCell<dyn teksilo_canvas::TextBackend>>>,
285    clip_bounds: Option<Rect>,
286    a11y_prefs: &A11yPaintPrefs,
287    paint_epoch: u64,
288    overlay_skip: &std::collections::HashSet<WidgetId>,
289    overlay_rects: &[Rect],
290    layout_direction: crate::environment::LayoutDirection,
291    parent_effective_enabled: bool,
292    accumulated_raster_scale: f32,
293) {
294    if !arena.is_active(id) {
295        return;
296    }
297
298    // Compute this node's effective enabled-state once: AND the
299    // ancestor-derived value with our own `enabled_state` if set.
300    // Used both for our own paint context and for the recursion into
301    // children below.
302    let this_effective_enabled = parent_effective_enabled
303        && arena
304            .get(id)
305            .and_then(|n| n.enabled_state.as_ref())
306            .is_none_or(|p| p.get());
307
308    let node = arena.get(id).expect("node id is active (guarded above)");
309    let bounds = node.bounds;
310    if let Some(clip) = clip_bounds {
311        let x0 = bounds.x.max(clip.x);
312        let y0 = bounds.y.max(clip.y);
313        let x1 = bounds.right().min(clip.right());
314        let y1 = bounds.bottom().min(clip.bottom());
315        if x1 <= x0 || y1 <= y0 {
316            // Clipped to nothing — widget is offscreen. Skip its paint
317            // AND skip stamping `last_painted_epoch`, so the animation
318            // scheduler will notice it is no longer visible and pause
319            // its looping animations.
320            return;
321        }
322    }
323
324    // Mark this widget as "painted in epoch N" regardless of whether
325    // we hit the cache-path or ran `paint()` — both outcomes mean the
326    // widget's bounds landed inside the viewport this frame, which is
327    // all the animation scheduler cares about.
328    if let Some(node_mut) = arena.get_mut(id) {
329        node_mut.last_painted_epoch = paint_epoch;
330    }
331
332    // Read the optional opacity scope before borrowing the node again
333    // for the paint/cache path. The scope wraps both this widget's own
334    // paint and its children's paint, composing with any ancestor
335    // opacity via the canvas's stacked-opacity model.
336    let node = arena.get(id).expect("node id is active (guarded above)");
337    let opacity = node.opacity_prop.as_ref().map(|p| p.get().clamp(0.0, 1.0));
338    if let Some(o) = opacity
339        && o < 1.0 / 512.0
340    {
341        // Sub-perceptual: skip the subtree entirely. Saves a draw
342        // pass when a `Fade` is fully transparent (e.g. just-dismissed
343        // tooltip waiting for cleanup) and prevents 0.0 from emitting
344        // a spurious blend pass on the GPU. We do this before any blur
345        // scope emit so the Begin/End pair stays balanced.
346        return;
347    }
348
349    // Optional blur scope is the OUTERMOST per-node scope: it captures
350    // the entire rendered subtree (including any opacity/transform scopes
351    // we're about to push) into an intermediate texture, blurs it via
352    // the renderer's dual-Kawase chain, and composites the blurred
353    // result back at the widget's bounds. Sub-perceptual radii skip the
354    // pair entirely so animated 0→target_radius patterns have zero cost
355    // when fully off.
356    let node = arena.get(id).expect("node id is active (guarded above)");
357    let blur_radius = node
358        .blur_prop
359        .as_ref()
360        .map(|p| p.get())
361        .filter(|r| *r >= 0.5);
362    let blur_bounds = arena.bounds(id);
363    if let Some(r) = blur_radius {
364        frame
365            .draw_order
366            .push(teksilo_canvas::DrawCommand::BeginBlurredSubtree {
367                bounds: blur_bounds,
368                radius: r,
369            });
370    }
371
372    if let Some(o) = opacity {
373        frame
374            .draw_order
375            .push(teksilo_canvas::DrawCommand::SetOpacity(o));
376    }
377
378    // Optional transform scope — wraps both this widget's own paint
379    // and its children's paint. The renderer composes the pushed
380    // transform onto its stack so widget-internal canvas transforms
381    // (canvas.translate / scale / rotate) compose with this wrapper
382    // transform instead of clobbering it. Skip the push entirely when
383    // the transform is identity — saves a flush on every wrapper that
384    // happens to be at its rest pose.
385    let node = arena.get(id).expect("node id is active (guarded above)");
386    let transform = node.transform_prop.as_ref().map(|p| p.get());
387    let push_transform = transform.filter(|t| *t != teksilo_canvas::Transform2D::IDENTITY);
388    let clips = node.clips_children;
389    let content_transform = node.content_transform;
390    let bounds = node.bounds;
391
392    // Accumulated raster scale for this node and its subtree: multiply
393    // the ancestors' scale by this node's own transform scale (a
394    // SceneView zoom or a `Scale` wrapper) and re-quantize. Text painted
395    // inside the scope rasterizes at this density so the GPU transform
396    // lands a ~1:1 texel-to-pixel mapping instead of stretching a 1×
397    // bitmap. Pure translations/rotations have `geometric_scale() == 1`
398    // and inherit the parent value bit-identically.
399    let this_raster_scale = match push_transform {
400        Some(t) => quantize_raster_scale(accumulated_raster_scale * t.geometric_scale()),
401        None => accumulated_raster_scale,
402    };
403    // The backend currently holds the parent's ambient scale (root
404    // callers start at 1.0; every recursion level restores on exit), so
405    // it only needs touching when this node's scale differs.
406    let raster_scale_changed = this_raster_scale != accumulated_raster_scale;
407    if raster_scale_changed && let Some(tb) = text_backend {
408        tb.borrow_mut().set_raster_scale(this_raster_scale);
409    }
410    // A *content* transform (a SceneView's pan/zoom) leaves the node's bounds a
411    // fixed parent-space viewport and only moves the content. Emit its clip
412    // BEFORE the transform so the renderer scissors to that fixed viewport
413    // (transformed by ancestors only — correct for nested scenes too) instead
414    // of the pan/zoom-shifted rect, and so the node's own paint (background
415    // grid / lightweight items) is clipped to the viewport as well. A *self*
416    // transform (Scale/Rotate) keeps its clip INSIDE the transform — there the
417    // clip is meant to be the scaled visual region.
418    let clip_outside_transform = clips && content_transform;
419    if clip_outside_transform {
420        frame
421            .draw_order
422            .push(teksilo_canvas::DrawCommand::SetClip(bounds));
423    }
424    if let Some(t) = push_transform {
425        frame
426            .draw_order
427            .push(teksilo_canvas::DrawCommand::PushTransform(t));
428    }
429
430    let node = arena.get(id).expect("node id is active (guarded above)");
431    // A clean widget's cached frames bake glyph quads at the raster
432    // scale current when they were recorded; when the ambient scale
433    // moved (a scene zoom crossed a quantization bucket), those quads
434    // sample wrong-density bitmaps — treat the node as needing paint.
435    let needs_paint = node.dirty.needs_paint || node.paint_raster_scale != this_raster_scale;
436
437    if needs_paint || node.cached_paint.is_none() {
438        let resolved_theme = arena.resolve_theme(id, base_theme);
439        let ctx = PaintContext {
440            theme: &resolved_theme,
441            scale_factor: this_raster_scale,
442            text_scale: a11y_prefs.text_scale,
443            layout_direction,
444            effective_enabled: this_effective_enabled,
445            prefers_high_contrast: a11y_prefs.high_contrast,
446            prefers_reduced_motion: a11y_prefs.reduced_motion,
447            prefers_large_text: a11y_prefs.large_text,
448            window_active: a11y_prefs.window_active,
449            clip_bounds,
450        };
451
452        let bounds = arena.bounds(id);
453        let node = arena.get(id).expect("node id is active (guarded above)");
454
455        let mut canvas = match text_backend {
456            Some(tb) => Canvas::with_text_backend(tb.clone()),
457            None => Canvas::new(),
458        };
459        node.widget.paint(bounds, &mut canvas, &ctx);
460        let widget_frame = canvas.into_render_frame();
461
462        frame.merge(&widget_frame);
463        if let Some(node) = arena.get_mut(id) {
464            node.cached_paint = Some(widget_frame);
465            node.paint_raster_scale = this_raster_scale;
466        }
467    } else {
468        let node = arena.get(id).expect("node id is active (guarded above)");
469        if let Some(cached) = &node.cached_paint {
470            // Refresh the text backend's glyph timestamps for every
471            // layout baked into this cached paint. Without this,
472            // widgets that stay clean for ~180 frames (e.g. static
473            // labels next to an animation) can have their atlas slots
474            // evicted and reused, and the cached UVs then sample the
475            // wrong glyph. `TextBackend::touch_layout` is a no-op for
476            // backends without a glyph cache (the mock).
477            if !cached.layout_keys.is_empty()
478                && let Some(tb) = text_backend
479            {
480                let mut tb = tb.borrow_mut();
481                for key in &cached.layout_keys {
482                    tb.touch_layout(*key);
483                }
484                #[cfg(debug_assertions)]
485                debug_validate_layout_keys(&*tb, &cached.layout_keys, Some(id));
486            }
487            frame.merge(cached);
488        }
489    }
490
491    let node = arena.get(id).expect("node id is active (guarded above)");
492    let children: Vec<WidgetId> = node.children.clone();
493    let next_clip = if clips {
494        Some(match clip_bounds {
495            Some(clip) => {
496                let x0 = bounds.x.max(clip.x);
497                let y0 = bounds.y.max(clip.y);
498                let x1 = bounds.right().min(clip.right());
499                let y1 = bounds.bottom().min(clip.bottom());
500                Rect::new(x0, y0, (x1 - x0).max(0.0), (y1 - y0).max(0.0))
501            }
502            None => bounds,
503        })
504    } else {
505        clip_bounds
506    };
507
508    // A *content*-transform node (a `SceneView`'s pan/zoom) places its children
509    // in the transformed (content) coordinate space — `place_children` writes
510    // each child's `node.bounds` in scene coords, and the pan/zoom is applied
511    // only at draw time via the `PushTransform` above. The cull clip we hand the
512    // children must therefore be in that same content space; otherwise the
513    // per-child offscreen check at the top of this fn compares scene-space child
514    // bounds against a screen-space clip and drops content that is panned into
515    // view (a card far down in scene coords reads as "outside the viewport"
516    // regardless of pan — the lightweight tier, painted in the node's own
517    // `paint()`, is unaffected, hence "connectors render but cards don't").
518    // Inverse-transform the screen-space clip into content space. The GPU
519    // `SetClip` (emitted in parent/screen space) is untouched — it stays the
520    // real viewport scissor.
521    let next_clip = match (
522        content_transform,
523        next_clip,
524        transform.and_then(|t| t.inverse()),
525    ) {
526        (true, Some(screen_clip), Some(inv)) => Some(inv.apply_rect(screen_clip)),
527        _ => next_clip,
528    };
529
530    // Self-transform / plain clipping nodes emit their clip here — after the
531    // node's own paint, inside any transform scope. Content-transform nodes
532    // already emitted theirs above (in parent space).
533    if clips && !clip_outside_transform {
534        frame
535            .draw_order
536            .push(teksilo_canvas::DrawCommand::SetClip(bounds));
537    }
538
539    for child_id in children {
540        // Skip overlay-managed content here — it is painted via the
541        // dedicated overlay loop in render_with_ops. Without this, an
542        // overlay (e.g. a tooltip) attached as a child of its anchor
543        // would paint twice per frame: once via the parent walk and
544        // once via the overlay loop.
545        if overlay_skip.contains(&child_id) {
546            continue;
547        }
548        paint_widget_cached(
549            arena,
550            child_id,
551            frame,
552            base_theme,
553            text_backend,
554            next_clip,
555            a11y_prefs,
556            paint_epoch,
557            overlay_skip,
558            overlay_rects,
559            layout_direction,
560            this_effective_enabled,
561            this_raster_scale,
562        );
563    }
564
565    // Post-order `after_paint` hook. Fires after every descendant has
566    // painted and committed its bounds, so a parent can read those
567    // bounds via `WidgetTreeView::bounds(child_id)`. Gated on
568    // `wants_after_paint()` to avoid a virtual call per widget per
569    // frame for the 99% of widgets that don't aggregate. The arena
570    // mutable borrow from the recursive child loop has dropped by
571    // this point, so an immutable reborrow is safe.
572    {
573        let arena_ref: &WidgetArena = &*arena;
574        if let Some(node) = arena_ref.get(id)
575            && node.widget.wants_after_paint()
576        {
577            let view = crate::widget::WidgetTreeView::new(arena_ref, overlay_rects);
578            let resolved_theme = arena_ref.resolve_theme(id, base_theme);
579            let ctx = PaintContext {
580                theme: &resolved_theme,
581                scale_factor: this_raster_scale,
582                text_scale: a11y_prefs.text_scale,
583                layout_direction,
584                effective_enabled: this_effective_enabled,
585                prefers_high_contrast: a11y_prefs.high_contrast,
586                prefers_reduced_motion: a11y_prefs.reduced_motion,
587                prefers_large_text: a11y_prefs.large_text,
588                window_active: a11y_prefs.window_active,
589                clip_bounds,
590            };
591            node.widget.after_paint(&view, &ctx);
592        }
593    }
594
595    // Foreground pass — `post_paint` emits *after* the whole child
596    // subtree, so its draws land on top of this node's descendants. Still
597    // inside this node's clip / transform / opacity / blur scopes (their
598    // closers come below), so a foreground decoration pans, scales and
599    // clips consistently with the subtree it covers. Same `needs_paint`
600    // cache gate as the main paint above, with its own `cached_post_paint`
601    // frame. Gated on `wants_post_paint` so non-foreground widgets pay
602    // nothing.
603    let wants_post_paint = arena
604        .get(id)
605        .map(|n| n.widget.wants_post_paint())
606        .unwrap_or(false);
607    if wants_post_paint {
608        let has_post_cache = arena
609            .get(id)
610            .map(|n| n.cached_post_paint.is_some())
611            .unwrap_or(false);
612        if needs_paint || !has_post_cache {
613            // Children restored the backend to this node's ambient scale
614            // on their way out; re-assert defensively so post_paint text
615            // (e.g. a SceneView's foreground lightweight items) can't
616            // bake at a child-leaked scale.
617            if raster_scale_changed && let Some(tb) = text_backend {
618                tb.borrow_mut().set_raster_scale(this_raster_scale);
619            }
620            let resolved_theme = arena.resolve_theme(id, base_theme);
621            let ctx = PaintContext {
622                theme: &resolved_theme,
623                scale_factor: this_raster_scale,
624                text_scale: a11y_prefs.text_scale,
625                layout_direction,
626                effective_enabled: this_effective_enabled,
627                prefers_high_contrast: a11y_prefs.high_contrast,
628                prefers_reduced_motion: a11y_prefs.reduced_motion,
629                prefers_large_text: a11y_prefs.large_text,
630                window_active: a11y_prefs.window_active,
631                clip_bounds,
632            };
633            let bounds = arena.bounds(id);
634            let node = arena.get(id).expect("node id is active (guarded above)");
635            let mut canvas = match text_backend {
636                Some(tb) => Canvas::with_text_backend(tb.clone()),
637                None => Canvas::new(),
638            };
639            node.widget.post_paint(bounds, &mut canvas, &ctx);
640            let post_frame = canvas.into_render_frame();
641            frame.merge(&post_frame);
642            if let Some(node) = arena.get_mut(id) {
643                node.cached_post_paint = Some(post_frame);
644            }
645        } else if let Some(cached) = arena.get(id).and_then(|n| n.cached_post_paint.as_ref()) {
646            if !cached.layout_keys.is_empty()
647                && let Some(tb) = text_backend
648            {
649                let mut tb = tb.borrow_mut();
650                for key in &cached.layout_keys {
651                    tb.touch_layout(*key);
652                }
653                #[cfg(debug_assertions)]
654                debug_validate_layout_keys(&*tb, &cached.layout_keys, Some(id));
655            }
656            frame.merge(cached);
657        }
658    }
659
660    if clips && !clip_outside_transform {
661        frame
662            .draw_order
663            .push(teksilo_canvas::DrawCommand::ClearClip);
664    }
665
666    if push_transform.is_some() {
667        frame
668            .draw_order
669            .push(teksilo_canvas::DrawCommand::PopTransform);
670    }
671
672    // A content-transform clip opened before the transform, so it closes after
673    // the transform pops (clip { transform { … } } nesting).
674    if clip_outside_transform {
675        frame
676            .draw_order
677            .push(teksilo_canvas::DrawCommand::ClearClip);
678    }
679
680    if opacity.is_some() {
681        frame
682            .draw_order
683            .push(teksilo_canvas::DrawCommand::RestoreOpacity);
684    }
685
686    if blur_radius.is_some() {
687        frame
688            .draw_order
689            .push(teksilo_canvas::DrawCommand::EndBlurredSubtree);
690    }
691
692    // Unwind the ambient raster scale to the parent's value so siblings
693    // painted after this subtree see their own ancestor scale.
694    if raster_scale_changed && let Some(tb) = text_backend {
695        tb.borrow_mut().set_raster_scale(accumulated_raster_scale);
696    }
697}
698
699/// Debug-build corruption catcher: before a retained paint frame is
700/// replayed, verify that every layout baked into it still matches the
701/// live glyph atlas.
702///
703/// A `RectMismatch` means the frame's glyph quads reference atlas pixels
704/// that were evicted and reused — replaying them draws the wrong
705/// characters (the historical "random text corruption fixed by a
706/// repaint" bug). That is always a missing cache-invalidation path, so
707/// abort with a diagnostic. A `StaleKey` (backend forgot the layout
708/// entirely — its caches were cleared after this frame was baked) is the
709/// same bug class but can transiently occur around legitimate wholesale
710/// clears, so it logs loudly (once per key) instead of aborting.
711#[cfg(debug_assertions)]
712fn debug_validate_layout_keys(
713    tb: &dyn teksilo_canvas::TextBackend,
714    layout_keys: &[u64],
715    widget: Option<WidgetId>,
716) {
717    use teksilo_canvas::GlyphValidation;
718    std::thread_local! {
719        static REPORTED_STALE_KEYS: std::cell::RefCell<std::collections::HashSet<u64>> =
720            std::cell::RefCell::new(std::collections::HashSet::new());
721    }
722    for key in layout_keys {
723        match tb.debug_validate_layout(*key) {
724            GlyphValidation::Valid => {}
725            GlyphValidation::StaleKey => {
726                let first_report = REPORTED_STALE_KEYS.with(|set| set.borrow_mut().insert(*key));
727                if first_report {
728                    eprintln!(
729                        "[teksilo] WARNING: retained paint cache replays layout_key={key} \
730                         (widget={widget:?}) that the text backend no longer knows — the \
731                         frame survived a backend cache clear, so a paint-cache \
732                         invalidation path is likely missing."
733                    );
734                }
735            }
736            GlyphValidation::RectMismatch => {
737                panic!(
738                    "stale glyph UVs in retained paint cache (layout_key={key}, \
739                     widget={widget:?}): cached quads no longer match the live glyph \
740                     atlas — a cache-invalidation path is missing"
741                );
742            }
743        }
744    }
745}
746
747#[cfg(test)]
748mod tests {
749    use super::*;
750    use crate::test_widgets::{FillWidget, StackWidget};
751    use teksilo_tokens::{Color, CornerRadius};
752
753    /// Headless text backend that records every `touch_layout` call and
754    /// hands out layouts with a fixed non-zero `layout_key`, so tests
755    /// can assert that paint-cache reuse keeps glyph timestamps fresh.
756    /// Also tracks the ambient raster scale (`set_raster_scale`) and the
757    /// scale every `layout_single_line` call ran under, so walker tests
758    /// can assert the set/restore discipline around transform scopes.
759    #[derive(Default)]
760    struct RecordingTextBackend {
761        touched: std::rc::Rc<std::cell::RefCell<Vec<u64>>>,
762        raster_scale: f32,
763        /// Ambient raster scale observed by each `layout_single_line`
764        /// call, in call order.
765        layout_scales: std::rc::Rc<std::cell::RefCell<Vec<f32>>>,
766    }
767
768    impl RecordingTextBackend {
769        fn new(touched: std::rc::Rc<std::cell::RefCell<Vec<u64>>>) -> Self {
770            Self {
771                touched,
772                raster_scale: 1.0,
773                layout_scales: Default::default(),
774            }
775        }
776    }
777
778    impl teksilo_canvas::TextBackend for RecordingTextBackend {
779        fn set_raster_scale(&mut self, raster_scale: f32) {
780            self.raster_scale = raster_scale;
781        }
782
783        fn raster_scale(&self) -> f32 {
784            self.raster_scale
785        }
786
787        fn layout_single_line(
788            &mut self,
789            text: &str,
790            _style: &teksilo_tokens::TextStyle,
791            _max_width: Option<f32>,
792        ) -> teksilo_canvas::TextLayout {
793            self.layout_scales.borrow_mut().push(self.raster_scale);
794            teksilo_canvas::TextLayout {
795                width: text.len() as f32 * 8.0,
796                height: 16.0,
797                ascent: 12.0,
798                descent: 4.0,
799                underline_offset: 1.0,
800                underline_thickness: 1.0,
801                layout_key: 42,
802                line_count: 1,
803                spans: Vec::new(),
804                raster_scale: self.raster_scale,
805            }
806        }
807
808        fn ensure_glyphs(
809            &mut self,
810            _layout: &teksilo_canvas::TextLayout,
811        ) -> Vec<teksilo_canvas::GlyphQuad> {
812            Vec::new()
813        }
814
815        fn touch_layout(&mut self, layout_key: u64) {
816            self.touched.borrow_mut().push(layout_key);
817        }
818    }
819
820    /// Leaf widget that draws one line of text so its emitted frame
821    /// carries a `layout_key`.
822    #[derive(Debug)]
823    struct TextPaintWidget;
824
825    impl Widget for TextPaintWidget {
826        fn layout_response(
827            &self,
828            proposal: SizeProposal,
829            _ctx: &LayoutContext,
830        ) -> crate::widget::LayoutResponse {
831            proposal.resolve(100.0, 20.0).into()
832        }
833
834        fn paint(
835            &self,
836            bounds: teksilo_canvas::Rect,
837            canvas: &mut teksilo_canvas::Canvas,
838            _ctx: &PaintContext,
839        ) {
840            let style = teksilo_tokens::TextStyle::default();
841            let _ = canvas.draw_text("hello", bounds, &style, Color::BLACK);
842        }
843    }
844
845    #[test]
846    fn full_frame_cache_hit_touches_layout_keys() {
847        let touched = std::rc::Rc::new(std::cell::RefCell::new(Vec::new()));
848        let backend = RecordingTextBackend::new(touched.clone());
849        let mut tree = WidgetTree::new()
850            .with_theme(crate::presets::intui::light())
851            .with_text_backend(std::rc::Rc::new(std::cell::RefCell::new(backend)));
852        tree.add(TextPaintWidget);
853        tree.layout(SizeProposal::exact(200.0, 50.0));
854
855        // First render paints for real; no cache reuse yet.
856        let _ = tree.render();
857        touched.borrow_mut().clear();
858
859        // Nothing is dirty: this render takes the full-frame early-out.
860        // The reused frame's layout keys must still be touched, or the
861        // backend's LRU ages out glyphs that are on screen.
862        let _ = tree.render();
863        assert!(
864            touched.borrow().contains(&42),
865            "full-frame cache hit must touch_layout every baked layout key; \
866             touched = {:?}",
867            touched.borrow()
868        );
869    }
870
871    /// Shared fixture: a root stack with a text leaf before, inside, and
872    /// after a transform-scoped wrapper:
873    ///
874    /// ```text
875    /// root Stack
876    /// ├── TextPaintWidget          (A, screen scale)
877    /// ├── Stack [transform]        (wrapper)
878    /// │   └── TextPaintWidget      (B, scaled)
879    /// └── TextPaintWidget          (C, screen scale)
880    /// ```
881    fn scaled_subtree_tree(
882        transform: impl Into<crate::signal::Prop<teksilo_canvas::Transform2D>>,
883    ) -> (
884        WidgetTree,
885        std::rc::Rc<std::cell::RefCell<RecordingTextBackend>>,
886        std::rc::Rc<std::cell::RefCell<Vec<f32>>>,
887    ) {
888        let backend = RecordingTextBackend::new(Default::default());
889        let layout_scales = backend.layout_scales.clone();
890        let backend_rc = std::rc::Rc::new(std::cell::RefCell::new(backend));
891        let mut tree = WidgetTree::new()
892            .with_theme(crate::presets::intui::light())
893            .with_text_backend(backend_rc.clone()
894                as std::rc::Rc<std::cell::RefCell<dyn teksilo_canvas::TextBackend>>);
895
896        let root = tree.add(StackWidget::new());
897        tree.add_child(root, TextPaintWidget); // A
898        let wrapper = tree.add_child(root, StackWidget::new());
899        tree.add_child(wrapper, TextPaintWidget); // B
900        tree.add_child(root, TextPaintWidget); // C
901        tree.set_transform(wrapper, transform);
902
903        tree.layout(SizeProposal::exact(400.0, 300.0));
904        (tree, backend_rc, layout_scales)
905    }
906
907    #[test]
908    fn walker_sets_raster_scale_for_scaled_subtree_and_restores() {
909        let (mut tree, backend_rc, layout_scales) =
910            scaled_subtree_tree(teksilo_canvas::Transform2D::scale(2.0, 2.0));
911        let _ = tree.render();
912
913        // Paint order is child order: A (screen), B (inside the 2x
914        // scope, quantized onto the 1.25^n ladder), C (screen again —
915        // the wrapper restored the ambient scale on exit).
916        let expected_b = 1.25_f32.powi(3); // quantize(2.0)
917        assert_eq!(
918            layout_scales.borrow().as_slice(),
919            &[1.0, expected_b, 1.0],
920            "text inside the transform scope must lay out at the quantized \
921             scale; siblings before/after at screen scale"
922        );
923        // The walk unwound to the root ambient scale.
924        assert_eq!(backend_rc.borrow().raster_scale, 1.0);
925    }
926
927    #[test]
928    fn raster_scale_change_repaints_clean_descendants() {
929        let transform = crate::signal::Signal::new(teksilo_canvas::Transform2D::scale(2.0, 2.0));
930        let (mut tree, _backend_rc, layout_scales) = scaled_subtree_tree(transform.clone());
931        let _ = tree.render();
932        layout_scales.borrow_mut().clear();
933
934        // Zoom changes: only the wrapper node is dirtied (RepaintOnly
935        // binding); its text child B stays clean — the raster-scale
936        // stamp on B's paint cache must force the repaint anyway.
937        transform.set(teksilo_canvas::Transform2D::scale(3.0, 3.0));
938        let _ = tree.render();
939        assert_eq!(
940            layout_scales.borrow().as_slice(),
941            &[1.25_f32.powi(5)],
942            "the clean text leaf inside the scope must re-rasterize at the \
943             new quantized scale (A and C stay cached: no layout calls)"
944        );
945
946        // And back down to identity: B re-bakes once more at 1.0.
947        layout_scales.borrow_mut().clear();
948        transform.set(teksilo_canvas::Transform2D::IDENTITY);
949        let _ = tree.render();
950        assert_eq!(layout_scales.borrow().as_slice(), &[1.0]);
951
952        // Steady state: nothing dirty, no scale movement → full-frame
953        // cache hit, zero layout calls.
954        layout_scales.borrow_mut().clear();
955        let _ = tree.render();
956        assert!(layout_scales.borrow().is_empty());
957    }
958
959    #[test]
960    fn nested_scale_transforms_multiply() {
961        let backend = RecordingTextBackend::new(Default::default());
962        let layout_scales = backend.layout_scales.clone();
963        let mut tree = WidgetTree::new()
964            .with_theme(crate::presets::intui::light())
965            .with_text_backend(std::rc::Rc::new(std::cell::RefCell::new(backend)));
966
967        // outer [2x] → inner [1.5x] → text. Accumulation:
968        // quantize(2.0) = 1.25^3, then quantize(1.25^3 × 1.5) = 1.25^5.
969        let outer = tree.add(StackWidget::new());
970        let inner = tree.add_child(outer, StackWidget::new());
971        tree.add_child(inner, TextPaintWidget);
972        tree.set_transform(outer, teksilo_canvas::Transform2D::scale(2.0, 2.0));
973        tree.set_content_transform(inner, teksilo_canvas::Transform2D::scale(1.5, 1.5));
974
975        tree.layout(SizeProposal::exact(400.0, 300.0));
976        let _ = tree.render();
977        assert_eq!(layout_scales.borrow().as_slice(), &[1.25_f32.powi(5)]);
978    }
979
980    #[test]
981    fn invalidate_all_paints_clears_post_paint_cache() {
982        /// Widget that draws chrome in the foreground pass so the walker
983        /// populates `cached_post_paint`.
984        #[derive(Debug)]
985        struct PostPaintWidget;
986
987        impl Widget for PostPaintWidget {
988            fn layout_response(
989                &self,
990                proposal: SizeProposal,
991                _ctx: &LayoutContext,
992            ) -> crate::widget::LayoutResponse {
993                proposal.resolve(50.0, 50.0).into()
994            }
995
996            fn wants_post_paint(&self) -> bool {
997                true
998            }
999
1000            fn post_paint(
1001                &self,
1002                bounds: teksilo_canvas::Rect,
1003                canvas: &mut teksilo_canvas::Canvas,
1004                _ctx: &PaintContext,
1005            ) {
1006                canvas.fill_rect(bounds, Color::RED);
1007            }
1008        }
1009
1010        let mut tree = WidgetTree::new().with_theme(crate::presets::intui::light());
1011        let id = tree.add(PostPaintWidget);
1012        tree.layout(SizeProposal::exact(100.0, 100.0));
1013        let _ = tree.render();
1014        assert!(
1015            tree.arena
1016                .get(id)
1017                .and_then(|n| n.cached_post_paint.as_ref())
1018                .is_some(),
1019            "render must populate cached_post_paint for a post-painting widget"
1020        );
1021
1022        tree.invalidate_all_paints();
1023        assert!(
1024            tree.arena
1025                .get(id)
1026                .and_then(|n| n.cached_post_paint.as_ref())
1027                .is_none(),
1028            "invalidate_all_paints must clear cached_post_paint too — a retained \
1029             post-paint frame can hold stale glyph UVs after atlas eviction"
1030        );
1031    }
1032
1033    #[derive(Debug)]
1034    struct ThemeAwareWidget;
1035
1036    impl Widget for ThemeAwareWidget {
1037        fn layout_response(
1038            &self,
1039            proposal: SizeProposal,
1040            _ctx: &LayoutContext,
1041        ) -> crate::widget::LayoutResponse {
1042            proposal.resolve(0.0, 0.0).into()
1043        }
1044
1045        fn paint(
1046            &self,
1047            bounds: teksilo_canvas::Rect,
1048            canvas: &mut teksilo_canvas::Canvas,
1049            ctx: &PaintContext,
1050        ) {
1051            canvas.fill_rounded_rect(
1052                bounds,
1053                teksilo_tokens::CornerRadius::uniform(4.0),
1054                ctx.theme.colors.accent,
1055            );
1056        }
1057    }
1058
1059    #[test]
1060    fn fill_widget_produces_shape_in_frame() {
1061        let mut tree = WidgetTree::new().with_theme(crate::presets::intui::light());
1062        tree.add(
1063            FillWidget::new()
1064                .background(Color::RED)
1065                .corner_radius(CornerRadius::uniform(6.0)),
1066        );
1067        tree.layout(SizeProposal::exact(100.0, 40.0));
1068        let frame = tree.render();
1069        assert_eq!(frame.shapes.len(), 1);
1070        assert_eq!(
1071            frame.shapes[0].shape,
1072            teksilo_canvas::ShapeKind::RoundedRect
1073        );
1074    }
1075
1076    #[test]
1077    fn empty_tree_renders_empty_frame() {
1078        let mut tree = WidgetTree::new();
1079        let frame = tree.render();
1080        assert!(frame.is_empty());
1081    }
1082
1083    #[test]
1084    fn render_clears_paint_dirty() {
1085        let mut tree = WidgetTree::new();
1086        tree.add(FillWidget::new().background(Color::RED));
1087        tree.layout(SizeProposal::exact(100.0, 50.0));
1088        assert!(tree.needs_paint());
1089        tree.render();
1090        assert!(!tree.needs_paint());
1091    }
1092
1093    #[test]
1094    fn dormant_widget_not_rendered() {
1095        let mut tree = WidgetTree::new();
1096        let widget = tree.add(
1097            FillWidget::new()
1098                .background(Color::RED)
1099                .corner_radius(CornerRadius::uniform(4.0)),
1100        );
1101        tree.layout(SizeProposal::exact(100.0, 50.0));
1102        let frame = tree.render();
1103        assert!(!frame.shapes.is_empty());
1104
1105        tree.set_dormant(widget);
1106        tree.layout(SizeProposal::exact(100.0, 50.0));
1107        let frame = tree.render();
1108        assert!(frame.shapes.is_empty());
1109    }
1110
1111    #[test]
1112    fn dormancy_is_recursive() {
1113        let mut tree = WidgetTree::new();
1114        let child = tree.add(
1115            FillWidget::new()
1116                .background(Color::RED)
1117                .corner_radius(CornerRadius::uniform(4.0)),
1118        );
1119        let parent = tree.add(StackWidget::new().add_child(child));
1120        tree.layout(SizeProposal::exact(100.0, 50.0));
1121
1122        let frame = tree.render();
1123        assert_eq!(frame.shapes.len(), 1);
1124
1125        tree.set_dormant(parent);
1126        tree.layout(SizeProposal::exact(100.0, 50.0));
1127        let frame = tree.render();
1128        assert!(frame.shapes.is_empty());
1129
1130        tree.activate(parent);
1131        tree.layout(SizeProposal::exact(100.0, 50.0));
1132        let frame = tree.render();
1133        assert_eq!(frame.shapes.len(), 1);
1134    }
1135
1136    #[test]
1137    fn set_theme_marks_all_dirty() {
1138        let mut tree = WidgetTree::new().with_theme(crate::presets::intui::light());
1139        tree.add(FillWidget::new().background(Color::RED));
1140        tree.layout(SizeProposal::exact(100.0, 50.0));
1141        tree.render();
1142
1143        assert!(!tree.needs_layout());
1144        assert!(!tree.needs_paint());
1145
1146        tree.set_theme(crate::presets::intui::dark());
1147        assert!(tree.needs_layout());
1148        assert!(tree.needs_paint());
1149    }
1150
1151    #[test]
1152    fn set_theme_changes_rendered_colors() {
1153        let mut tree = WidgetTree::new().with_theme(crate::presets::intui::light());
1154        tree.add(ThemeAwareWidget);
1155        tree.layout(SizeProposal::exact(100.0, 50.0));
1156        let light_frame = tree.render();
1157        let light_color = light_frame.shapes[0].color;
1158
1159        tree.set_theme(crate::presets::intui::dark());
1160        tree.layout(SizeProposal::exact(100.0, 50.0));
1161        let dark_frame = tree.render();
1162        let dark_color = dark_frame.shapes[0].color;
1163
1164        assert_ne!(light_color, dark_color);
1165    }
1166
1167    #[test]
1168    fn subtree_theme_override() {
1169        let mut tree = WidgetTree::new().with_theme(crate::presets::intui::light());
1170        let parent = tree.add(ThemeAwareWidget);
1171        let _child = tree.add_child(parent, ThemeAwareWidget);
1172
1173        tree.set_theme_override(parent, |theme| {
1174            theme.colors = teksilo_tokens::ColorTokens::dark_default();
1175        });
1176
1177        tree.layout(SizeProposal::exact(100.0, 50.0));
1178        let frame = tree.render();
1179
1180        let dark_accent = teksilo_tokens::ColorTokens::dark_default()
1181            .accent
1182            .to_array();
1183        assert_eq!(frame.shapes[0].color, dark_accent);
1184        assert_eq!(frame.shapes[1].color, dark_accent);
1185    }
1186
1187    #[test]
1188    fn theme_override_only_affects_subtree() {
1189        let mut tree = WidgetTree::new().with_theme(crate::presets::intui::light());
1190
1191        let _unaffected = tree.add(ThemeAwareWidget);
1192        let overridden = tree.add(ThemeAwareWidget);
1193
1194        tree.set_theme_override(overridden, |theme| {
1195            theme.colors = teksilo_tokens::ColorTokens::dark_default();
1196        });
1197
1198        tree.layout(SizeProposal::exact(100.0, 50.0));
1199        let frame = tree.render();
1200
1201        let light_accent = teksilo_tokens::ColorTokens::light_default()
1202            .accent
1203            .to_array();
1204        let dark_accent = teksilo_tokens::ColorTokens::dark_default()
1205            .accent
1206            .to_array();
1207
1208        assert_eq!(frame.shapes[0].color, light_accent);
1209        assert_eq!(frame.shapes[1].color, dark_accent);
1210    }
1211
1212    #[test]
1213    fn resolved_theme_reflects_overrides() {
1214        let mut tree = WidgetTree::new().with_theme(crate::presets::intui::light());
1215
1216        let parent = tree.add(FillWidget::new());
1217        let child = tree.add_child(parent, FillWidget::new());
1218
1219        tree.set_theme_override(parent, |theme| {
1220            theme.colors.accent = Color::RED;
1221        });
1222
1223        tree.layout(SizeProposal::exact(100.0, 50.0));
1224
1225        let parent_theme = tree.resolved_theme(parent);
1226        assert_eq!(parent_theme.colors.accent, Color::RED);
1227
1228        let child_theme = tree.resolved_theme(child);
1229        assert_eq!(child_theme.colors.accent, Color::RED);
1230    }
1231
1232    #[test]
1233    fn opacity_prop_emits_set_and_restore_around_subtree() {
1234        // A widget with opacity_prop = Some(Static(0.5)) wraps its
1235        // own paint AND its children's paint inside a SetOpacity /
1236        // RestoreOpacity pair, so the canvas's stacked-opacity model
1237        // multiplies through.
1238        let mut tree = WidgetTree::new().with_theme(crate::presets::intui::light());
1239        let parent = tree.add(StackWidget::new());
1240        let _child = tree.add_child(parent, FillWidget::new().background(Color::RED));
1241        tree.set_opacity(parent, 0.5_f32);
1242        tree.layout(SizeProposal::exact(100.0, 50.0));
1243        let frame = tree.render();
1244
1245        let mut set_count = 0;
1246        let mut restore_count = 0;
1247        for cmd in &frame.draw_order {
1248            match cmd {
1249                teksilo_canvas::DrawCommand::SetOpacity(v) => {
1250                    assert!((v - 0.5).abs() < 1e-6, "expected 0.5, got {}", v);
1251                    set_count += 1;
1252                }
1253                teksilo_canvas::DrawCommand::RestoreOpacity => restore_count += 1,
1254                _ => {}
1255            }
1256        }
1257        assert_eq!(set_count, 1, "draw_order = {:?}", frame.draw_order);
1258        assert_eq!(restore_count, 1);
1259    }
1260
1261    #[test]
1262    fn opacity_prop_zero_skips_subtree_entirely() {
1263        // Sub-perceptual opacity (< 1/512) returns early — no
1264        // SetOpacity, no children draw commands. Saves a blend pass.
1265        let mut tree = WidgetTree::new().with_theme(crate::presets::intui::light());
1266        let parent = tree.add(StackWidget::new());
1267        tree.add_child(parent, FillWidget::new().background(Color::RED));
1268        tree.set_opacity(parent, 0.0_f32);
1269        tree.layout(SizeProposal::exact(100.0, 50.0));
1270        let frame = tree.render();
1271
1272        for cmd in &frame.draw_order {
1273            assert!(
1274                !matches!(cmd, teksilo_canvas::DrawCommand::SetOpacity(_)),
1275                "fully-transparent subtree should not emit SetOpacity"
1276            );
1277        }
1278        // The red FillWidget child must not appear either.
1279        assert!(
1280            !frame
1281                .shapes
1282                .iter()
1283                .any(|s| s.color == Color::RED.to_array()),
1284            "fully-transparent subtree should not paint its descendants"
1285        );
1286    }
1287
1288    #[test]
1289    fn transform_prop_emits_push_and_pop_around_subtree() {
1290        // A widget with transform_prop = Some(Static(scale(2))) wraps
1291        // both its own paint AND its children's paint inside a
1292        // PushTransform / PopTransform pair, mirroring the opacity
1293        // pattern.
1294        let mut tree = WidgetTree::new().with_theme(crate::presets::intui::light());
1295        let parent = tree.add(StackWidget::new());
1296        let _child = tree.add_child(parent, FillWidget::new().background(Color::RED));
1297        let scale_2x = teksilo_canvas::Transform2D::scale(2.0, 2.0);
1298        tree.set_transform(parent, scale_2x);
1299        tree.layout(SizeProposal::exact(100.0, 50.0));
1300        let frame = tree.render();
1301
1302        let mut push_count = 0;
1303        let mut pop_count = 0;
1304        let mut push_value = None;
1305        for cmd in &frame.draw_order {
1306            match cmd {
1307                teksilo_canvas::DrawCommand::PushTransform(t) => {
1308                    push_count += 1;
1309                    push_value = Some(*t);
1310                }
1311                teksilo_canvas::DrawCommand::PopTransform => pop_count += 1,
1312                _ => {}
1313            }
1314        }
1315        assert_eq!(push_count, 1, "draw_order = {:?}", frame.draw_order);
1316        assert_eq!(pop_count, 1);
1317        assert_eq!(push_value, Some(scale_2x));
1318    }
1319
1320    #[test]
1321    fn content_transform_clip_wraps_outside_the_transform() {
1322        // A *content* transform (the SceneView pattern: clips_children + a
1323        // content transform set via set_content_transform) must emit its clip
1324        // OUTSIDE the transform — SetClip before PushTransform, ClearClip after
1325        // PopTransform — so the renderer scissors to the fixed parent-space
1326        // viewport instead of the pan/zoom-shifted rect. (A *self* transform
1327        // like Scale keeps the clip inside the transform; see
1328        // transform_prop_emits_push_and_pop_around_subtree.)
1329        let mut tree = WidgetTree::new().with_theme(crate::presets::intui::light());
1330        let parent = tree.add(StackWidget::new());
1331        tree.add_child(parent, FillWidget::new().background(Color::RED));
1332        tree.layout(SizeProposal::exact(100.0, 50.0));
1333        // Set after layout so no rebuild can clear the flags before render.
1334        tree.set_clips_children(parent, true);
1335        tree.set_content_transform(parent, teksilo_canvas::Transform2D::translate(50.0, 30.0));
1336        let frame = tree.render();
1337
1338        let mut set_clip = None;
1339        let mut push = None;
1340        let mut pop = None;
1341        let mut clear = None;
1342        for (i, cmd) in frame.draw_order.iter().enumerate() {
1343            match cmd {
1344                teksilo_canvas::DrawCommand::SetClip(_) => set_clip = set_clip.or(Some(i)),
1345                teksilo_canvas::DrawCommand::PushTransform(_) => push = push.or(Some(i)),
1346                teksilo_canvas::DrawCommand::PopTransform => pop = Some(i),
1347                teksilo_canvas::DrawCommand::ClearClip => clear = Some(i),
1348                _ => {}
1349            }
1350        }
1351        let (sc, pt, pop, cc) = (
1352            set_clip.expect("SetClip emitted"),
1353            push.expect("PushTransform emitted"),
1354            pop.expect("PopTransform emitted"),
1355            clear.expect("ClearClip emitted"),
1356        );
1357        assert!(
1358            sc < pt,
1359            "clip must open before the transform: SetClip@{sc}, PushTransform@{pt}; order={:?}",
1360            frame.draw_order
1361        );
1362        assert!(
1363            pop < cc,
1364            "clip must close after the transform: PopTransform@{pop}, ClearClip@{cc}"
1365        );
1366    }
1367
1368    #[test]
1369    fn identity_transform_prop_skipped() {
1370        // transform_prop = Some(Static(IDENTITY)) is a no-op — the
1371        // walker should NOT emit a PushTransform / PopTransform pair
1372        // for the rest pose. Saves a flush per identity wrapper per
1373        // frame (Scale at full visibility, Rotate at angle=0).
1374        let mut tree = WidgetTree::new().with_theme(crate::presets::intui::light());
1375        let parent = tree.add(StackWidget::new());
1376        tree.add_child(parent, FillWidget::new().background(Color::RED));
1377        tree.set_transform(parent, teksilo_canvas::Transform2D::IDENTITY);
1378        tree.layout(SizeProposal::exact(100.0, 50.0));
1379        let frame = tree.render();
1380
1381        for cmd in &frame.draw_order {
1382            assert!(
1383                !matches!(
1384                    cmd,
1385                    teksilo_canvas::DrawCommand::PushTransform(_)
1386                        | teksilo_canvas::DrawCommand::PopTransform
1387                ),
1388                "identity transform must not emit a push/pop scope"
1389            );
1390        }
1391    }
1392
1393    #[test]
1394    fn transform_scope_paint_order_opacity_outer_transform_inner() {
1395        // When both opacity_prop AND transform_prop are set on the
1396        // same node, the framework's contract is opacity OUTER and
1397        // transform INNER. This pins down the order so future
1398        // refactors don't silently flip composability.
1399        let mut tree = WidgetTree::new().with_theme(crate::presets::intui::light());
1400        let parent = tree.add(StackWidget::new());
1401        tree.add_child(parent, FillWidget::new().background(Color::RED));
1402        tree.set_opacity(parent, 0.7_f32);
1403        tree.set_transform(parent, teksilo_canvas::Transform2D::scale(2.0, 2.0));
1404        tree.layout(SizeProposal::exact(100.0, 50.0));
1405        let frame = tree.render();
1406
1407        // Find the indices of each command kind.
1408        let mut set_opacity_idx = None;
1409        let mut push_transform_idx = None;
1410        let mut pop_transform_idx = None;
1411        let mut restore_opacity_idx = None;
1412        for (i, cmd) in frame.draw_order.iter().enumerate() {
1413            match cmd {
1414                teksilo_canvas::DrawCommand::SetOpacity(_) => set_opacity_idx = Some(i),
1415                teksilo_canvas::DrawCommand::PushTransform(_) => push_transform_idx = Some(i),
1416                teksilo_canvas::DrawCommand::PopTransform => pop_transform_idx = Some(i),
1417                teksilo_canvas::DrawCommand::RestoreOpacity => restore_opacity_idx = Some(i),
1418                _ => {}
1419            }
1420        }
1421        let so = set_opacity_idx.expect("SetOpacity emitted");
1422        let pt = push_transform_idx.expect("PushTransform emitted");
1423        let popt = pop_transform_idx.expect("PopTransform emitted");
1424        let ro = restore_opacity_idx.expect("RestoreOpacity emitted");
1425        assert!(so < pt, "opacity must open before transform: {so} < {pt}");
1426        assert!(pt < popt, "transform push must precede its pop");
1427        assert!(
1428            popt < ro,
1429            "transform must close before opacity: {popt} < {ro}"
1430        );
1431    }
1432
1433    /// A composing widget that paints a RED backdrop in `paint()`, hosts a
1434    /// GREEN child, and paints a BLUE foreground in `post_paint()`. Pins the
1435    /// P-C-AP draw order: backdrop (P) → child (C) → foreground (AP).
1436    #[derive(Debug)]
1437    struct Sandwich {
1438        child: Option<crate::WidgetId>,
1439    }
1440
1441    impl Widget for Sandwich {
1442        fn build(&mut self, ctx: &mut crate::build_context::BuildContext) -> Vec<crate::WidgetId> {
1443            let c = ctx.add(FillWidget::new().background(Color::GREEN));
1444            self.child = Some(c);
1445            vec![c]
1446        }
1447
1448        fn layout_response(
1449            &self,
1450            proposal: SizeProposal,
1451            _ctx: &LayoutContext,
1452        ) -> crate::widget::LayoutResponse {
1453            proposal.resolve(0.0, 0.0).into()
1454        }
1455
1456        fn place_children(
1457            &self,
1458            bounds: teksilo_canvas::Rect,
1459            _proposal: SizeProposal,
1460            children: &mut [crate::widget::WidgetPlacement],
1461            _ctx: &LayoutContext,
1462        ) {
1463            for child in children.iter_mut() {
1464                child.origin = bounds.origin();
1465                child.size = bounds.size();
1466            }
1467        }
1468
1469        fn children(&self) -> Vec<crate::WidgetId> {
1470            self.child.iter().copied().collect()
1471        }
1472
1473        fn paint(
1474            &self,
1475            bounds: teksilo_canvas::Rect,
1476            canvas: &mut teksilo_canvas::Canvas,
1477            _ctx: &PaintContext,
1478        ) {
1479            canvas.fill_rounded_rect(bounds, CornerRadius::uniform(0.0), Color::RED);
1480        }
1481
1482        fn wants_post_paint(&self) -> bool {
1483            true
1484        }
1485
1486        fn post_paint(
1487            &self,
1488            bounds: teksilo_canvas::Rect,
1489            canvas: &mut teksilo_canvas::Canvas,
1490            _ctx: &PaintContext,
1491        ) {
1492            canvas.fill_rounded_rect(bounds, CornerRadius::uniform(0.0), Color::BLUE);
1493        }
1494    }
1495
1496    #[test]
1497    fn post_paint_emits_after_children() {
1498        // P-C-AP ordering: a composing widget's own paint() is a backdrop
1499        // (before children) and post_paint() is a foreground (after the whole
1500        // child subtree). Backdrop=RED, child=GREEN, foreground=BLUE; assert
1501        // RED < GREEN < BLUE in draw_order.
1502        let mut tree = WidgetTree::new().with_theme(crate::presets::intui::light());
1503        tree.add(Sandwich { child: None });
1504        tree.layout(SizeProposal::exact(100.0, 50.0));
1505        let frame = tree.render();
1506
1507        let color_of = |cmd: &teksilo_canvas::DrawCommand| -> Option<[f32; 4]> {
1508            match cmd {
1509                teksilo_canvas::DrawCommand::Shape(i) => frame.shapes.get(*i).map(|s| s.color),
1510                teksilo_canvas::DrawCommand::Decoration(i) => {
1511                    frame.decorations.get(*i).map(|d| d.color)
1512                }
1513                _ => None,
1514            }
1515        };
1516        // Find the first draw whose color is dominated by `dominant` channel.
1517        let find = |dominant: usize| -> Option<usize> {
1518            frame.draw_order.iter().position(|cmd| {
1519                color_of(cmd).is_some_and(|c| {
1520                    c[dominant] > 0.5 && (0..3).all(|ch| ch == dominant || c[ch] < 0.5)
1521                })
1522            })
1523        };
1524        let red = find(0).expect("backdrop (RED) painted");
1525        let green = find(1).expect("child (GREEN) painted");
1526        let blue = find(2).expect("foreground (BLUE) painted");
1527        assert!(
1528            red < green && green < blue,
1529            "expected backdrop < child < foreground; RED@{red}, GREEN@{green}, BLUE@{blue}; order={:?}",
1530            frame.draw_order
1531        );
1532    }
1533
1534    #[test]
1535    fn blur_prop_emits_begin_end_pair_around_subtree() {
1536        // A widget with blur_prop = Some(Static(8.0)) wraps both its
1537        // own paint AND its children's paint inside a BeginBlurredSubtree
1538        // / EndBlurredSubtree pair, mirroring the opacity and transform
1539        // patterns. The Begin command carries the widget's bounds and
1540        // the requested radius.
1541        let mut tree = WidgetTree::new().with_theme(crate::presets::intui::light());
1542        let parent = tree.add(StackWidget::new());
1543        let _child = tree.add_child(parent, FillWidget::new().background(Color::RED));
1544        tree.set_blur(parent, 8.0_f32);
1545        tree.layout(SizeProposal::exact(100.0, 50.0));
1546        let frame = tree.render();
1547
1548        let mut begin_count = 0;
1549        let mut end_count = 0;
1550        let mut begin_radius = None;
1551        for cmd in &frame.draw_order {
1552            match cmd {
1553                teksilo_canvas::DrawCommand::BeginBlurredSubtree { radius, .. } => {
1554                    begin_count += 1;
1555                    begin_radius = Some(*radius);
1556                }
1557                teksilo_canvas::DrawCommand::EndBlurredSubtree => end_count += 1,
1558                _ => {}
1559            }
1560        }
1561        assert_eq!(begin_count, 1, "draw_order = {:?}", frame.draw_order);
1562        assert_eq!(end_count, 1);
1563        assert_eq!(begin_radius, Some(8.0));
1564    }
1565
1566    #[test]
1567    fn blur_prop_subperceptual_radius_skipped() {
1568        // blur_prop = Some(Static(0.2)) is below the 0.5 threshold —
1569        // the walker emits no Begin/End pair so animated 0→target
1570        // patterns have zero per-frame cost when fully off.
1571        let mut tree = WidgetTree::new().with_theme(crate::presets::intui::light());
1572        let parent = tree.add(StackWidget::new());
1573        tree.add_child(parent, FillWidget::new().background(Color::RED));
1574        tree.set_blur(parent, 0.2_f32);
1575        tree.layout(SizeProposal::exact(100.0, 50.0));
1576        let frame = tree.render();
1577
1578        for cmd in &frame.draw_order {
1579            assert!(
1580                !matches!(
1581                    cmd,
1582                    teksilo_canvas::DrawCommand::BeginBlurredSubtree { .. }
1583                        | teksilo_canvas::DrawCommand::EndBlurredSubtree
1584                ),
1585                "sub-perceptual blur must not emit Begin/End"
1586            );
1587        }
1588    }
1589
1590    #[test]
1591    fn blur_scope_is_outermost_when_combined_with_opacity_and_transform() {
1592        // Architectural pin: blur is the OUTERMOST scope so it captures
1593        // the already-faded, already-transformed subtree into the
1594        // intermediate texture.  Order on enter:
1595        //   Begin → SetOpacity → PushTransform → ...paint...
1596        // Order on exit (LIFO):
1597        //   PopTransform → RestoreOpacity → End
1598        let mut tree = WidgetTree::new().with_theme(crate::presets::intui::light());
1599        let parent = tree.add(StackWidget::new());
1600        tree.add_child(parent, FillWidget::new().background(Color::RED));
1601        tree.set_blur(parent, 8.0_f32);
1602        tree.set_opacity(parent, 0.7_f32);
1603        tree.set_transform(parent, teksilo_canvas::Transform2D::scale(2.0, 2.0));
1604        tree.layout(SizeProposal::exact(100.0, 50.0));
1605        let frame = tree.render();
1606
1607        let mut begin_idx = None;
1608        let mut set_opacity_idx = None;
1609        let mut push_transform_idx = None;
1610        let mut pop_transform_idx = None;
1611        let mut restore_opacity_idx = None;
1612        let mut end_idx = None;
1613        for (i, cmd) in frame.draw_order.iter().enumerate() {
1614            match cmd {
1615                teksilo_canvas::DrawCommand::BeginBlurredSubtree { .. } => begin_idx = Some(i),
1616                teksilo_canvas::DrawCommand::SetOpacity(_) => set_opacity_idx = Some(i),
1617                teksilo_canvas::DrawCommand::PushTransform(_) => push_transform_idx = Some(i),
1618                teksilo_canvas::DrawCommand::PopTransform => pop_transform_idx = Some(i),
1619                teksilo_canvas::DrawCommand::RestoreOpacity => restore_opacity_idx = Some(i),
1620                teksilo_canvas::DrawCommand::EndBlurredSubtree => end_idx = Some(i),
1621                _ => {}
1622            }
1623        }
1624        let bg = begin_idx.expect("Begin emitted");
1625        let so = set_opacity_idx.expect("SetOpacity emitted");
1626        let pt = push_transform_idx.expect("PushTransform emitted");
1627        let popt = pop_transform_idx.expect("PopTransform emitted");
1628        let ro = restore_opacity_idx.expect("RestoreOpacity emitted");
1629        let en = end_idx.expect("End emitted");
1630        assert!(bg < so, "blur opens before opacity");
1631        assert!(so < pt, "opacity opens before transform");
1632        assert!(pt < popt);
1633        assert!(popt < ro, "transform closes before opacity");
1634        assert!(ro < en, "opacity closes before blur");
1635    }
1636
1637    #[test]
1638    fn nested_theme_overrides_compose() {
1639        let mut tree = WidgetTree::new().with_theme(crate::presets::intui::light());
1640
1641        let grandparent = tree.add(FillWidget::new());
1642        let parent = tree.add_child(grandparent, FillWidget::new());
1643        let child = tree.add_child(parent, FillWidget::new());
1644
1645        tree.set_theme_override(grandparent, |theme| {
1646            theme.colors.accent = Color::RED;
1647        });
1648        tree.set_theme_override(parent, |theme| {
1649            theme.colors.text_secondary = Color::GREEN;
1650        });
1651
1652        tree.layout(SizeProposal::exact(100.0, 50.0));
1653
1654        let child_theme = tree.resolved_theme(child);
1655        assert_eq!(child_theme.colors.accent, Color::RED);
1656        assert_eq!(child_theme.colors.text_secondary, Color::GREEN);
1657    }
1658}