guido 0.12.0

A reactive Rust GUI library using wgpu for Wayland layer shell widgets
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
//! Paint context for the hierarchical render tree.

use std::rc::Rc;

use super::commands::{Border, CornerRadii, DrawCommand};
use super::text_measurer::LineFit;
use super::tree::{ClipRegion, NodeId, RenderNode};
use super::types::{Gradient, Shadow};
use crate::image_decode::DecodedImage;
use crate::pivot::Pivot;
use crate::transform::Transform;
use crate::tree::{Tree, WidgetId};
use crate::widgets::font::{FontFamily, FontWeight, LineHeight};
use crate::widgets::image::{ContentFit, ImageSource};
use crate::widgets::text_style::{TextShadow, TextStroke};
use crate::widgets::{Color, Rect, TextAlign};

/// Painting context for the renderer.
///
/// Widgets use this to build their render node. There's no push/pop for
/// transforms - they're set once per node and inherited automatically by children.
///
/// All drawing is done in LOCAL coordinates (0,0 is the widget's top-left).
/// Positioning is handled via transforms:
/// - [`paint_child`](Self::paint_child) places the child, from its bounds in
///   the tree — a widget does not position what it paints
/// - Child applies its own user transform (rotation, scale) via `apply_transform`
///
/// # Example
///
/// ```ignore
/// // not compiled: a fragment of a `Widget` impl, shown without the impl it
/// // belongs to. `tests/external_widget.rs` is the compiled version of this,
/// // including a parent that paints its child through `paint_child`.
/// fn paint(&self, ctx: &mut PaintContext) {
///     // Local bounds (0,0 origin with widget's own width/height)
///     let bounds = ctx.tree().get_bounds(ctx.id()).unwrap_or_default();
///     let local_bounds = Rect::new(0.0, 0.0, bounds.width, bounds.height);
///     ctx.set_bounds(local_bounds);
///
///     // Apply user transform (rotation, scale) - composes with the position
///     // `paint_child` already gave this node
///     if !self.user_transform.is_identity() {
///         ctx.apply_transform_with_pivot(self.user_transform, self.pivot);
///     }
///
///     // Draw background in LOCAL coordinates
///     ctx.draw_rounded_rect(local_bounds, Color::BLUE, 8.0);
///
///     // Paint children. One call each: it culls, caches, places and scopes.
///     for &child_id in &self.children {
///         ctx.paint_child(child_id, &ChildPaintOptions::default());
///     }
///
///     // Draw overlay effects (after children) in LOCAL coords
///     ctx.draw_overlay_circle(cx, cy, radius, color);
/// }
/// ```
pub struct PaintContext<'a> {
    /// The node being built
    node: &'a mut RenderNode,
    /// Optional viewport rect for culling off-screen children.
    /// Set by scrollable containers and propagated to descendants.
    /// Coordinates are in this node's local space.
    cull_rect: Option<Rect>,
    /// The tree the widget being painted belongs to, for its bounds and its
    /// children's.
    tree: &'a Tree,
    /// Which widget this context is painting. What
    /// [`paint_child`](Self::paint_child) attributes a read to, and what a
    /// widget asks for its own bounds with.
    id: WidgetId,
    /// The scale of the frame being painted. See
    /// [`scale_factor`](Self::scale_factor).
    scale_factor: f32,
}

impl<'a> PaintContext<'a> {
    /// Create a context for painting `id` into a node.
    ///
    /// The framework's, through [`Tree::paint_widget`](crate::tree::Tree::paint_widget):
    /// a widget is painted through that call or through
    /// [`paint_child`](Self::paint_child), never by reaching for this.
    pub(crate) fn new(
        node: &'a mut RenderNode,
        tree: &'a Tree,
        id: WidgetId,
        scale_factor: f32,
    ) -> Self {
        Self {
            node,
            cull_rect: None,
            tree,
            id,
            scale_factor,
        }
    }

    /// The widget being painted.
    pub fn id(&self) -> WidgetId {
        self.id
    }

    /// The scale of the frame being painted: how many device pixels its
    /// surface has to one logical pixel.
    ///
    /// Fractional where the compositor says so, and 1 until it has said
    /// anything. What a widget that builds its own raster needs, to build it at
    /// one pixel per device pixel — everything it draws through this context is
    /// still in logical coordinates.
    ///
    /// Read at paint time, and nothing more is needed: a scale change repaints
    /// the whole surface, so a paint that read the old one is never reused at
    /// the new one.
    ///
    /// ```
    /// # use guido::prelude::*;
    /// # use guido::widget_prelude::*;
    /// # use std::sync::Arc;
    /// struct Noise;
    ///
    /// impl Widget for Noise {
    ///     fn layout(&mut self, _ctx: &mut LayoutCtx, constraints: Constraints) -> Size {
    ///         constraints.constrain(Size::new(100.0, 20.0))
    ///     }
    ///
    ///     fn paint(&self, ctx: &mut PaintContext) {
    ///         let scale = ctx.scale_factor();
    ///         let (width, height) = ((100.0 * scale).round() as u32, (20.0 * scale).round() as u32);
    ///         let pixels: Vec<u8> = (0..width * height * 4).map(|i| (i % 251) as u8).collect();
    ///         ctx.draw_image(
    ///             ImageSource::Rgba { width, height, pixels: Arc::from(pixels) },
    ///             Rect::new(0.0, 0.0, 100.0, 20.0),
    ///             ContentFit::Fill,
    ///             None,
    ///         );
    ///     }
    /// }
    /// ```
    pub fn scale_factor(&self) -> f32 {
        self.scale_factor
    }

    /// The tree, for a widget that needs to ask about itself or its children.
    pub fn tree(&self) -> &'a Tree {
        self.tree
    }

    /// Get the cull rect (viewport in this node's local space), if set by a scrollable ancestor.
    pub fn cull_rect(&self) -> Option<Rect> {
        self.cull_rect
    }

    /// Set the cull rect (viewport in this node's local space) for culling off-screen children.
    pub fn set_cull_rect(&mut self, rect: Rect) {
        self.cull_rect = Some(rect);
    }

    /// Mark this node's paint as partial (some children were culled by cull_rect).
    /// Partial nodes are not cached to prevent reusing incomplete paint results.
    pub fn mark_partial(&mut self) {
        self.node.partial = true;
    }

    // -------------------------------------------------------------------------
    // Node Properties
    // -------------------------------------------------------------------------

    /// Set this node's bounds (for transform origin resolution).
    pub fn set_bounds(&mut self, bounds: Rect) {
        self.node.bounds = bounds;
    }

    /// Set this node's local transform (replaces any existing transform).
    ///
    /// This also records the transform as `parent_position` so that cached
    /// paint nodes can later decompose position vs. user-transform.
    pub(crate) fn set_transform(&mut self, transform: Transform) {
        self.node.local_transform = transform;
        self.node.parent_position = transform;
    }

    /// Apply a transform by composing it with the existing transform.
    ///
    /// The new transform is applied AFTER the existing transform:
    /// `result = existing.then(transform)`
    ///
    /// Use this when a child widget needs to add its own transform (rotation, scale)
    /// on top of the position transform set by its parent.
    pub fn apply_transform(&mut self, transform: Transform) {
        if !transform.is_identity() {
            self.node.local_transform = self.node.local_transform.then(&transform);
            self.cull_rect_follows(transform);
        }
    }

    /// Apply a transform with origin by composing it with the existing transform.
    pub fn apply_transform_with_pivot(&mut self, transform: Transform, origin: Pivot) {
        if !transform.is_identity() {
            self.node.pivot = origin;
            self.apply_transform(transform);
        }
    }

    /// Move the cull rect with the transform just applied.
    ///
    /// The rect names the visible region in *this node's* coordinates, and a
    /// widget that transforms itself has just changed what those coordinates
    /// mean. Without this the rect goes on describing where the content would
    /// have been drawn, and everything downstream that narrows children to it
    /// — the binary-search window and the per-child cull — answers about the
    /// wrong ones.
    ///
    /// The inverse, because the rect travels the other way from the content: a
    /// subtree lifted 300px upward shows what lies 300px further down. Resolved
    /// about the node's own pivot with `Transform::about`, the same composition
    /// `flatten` performs, so a rotation about a corner and one about a centre
    /// do not agree here and disagree on screen.
    ///
    /// A transform with no inverse — a scale of zero — collapses the content to
    /// a point, so none of it is visible and the rect that says so is the empty
    /// one. Dropping the rect instead would mean *nothing* is narrowed, and a
    /// collapsed subtree is a shipped idiom here: `scale(0.0)` is how a menu
    /// closes, and two hundred rows nobody can see would be painted on every
    /// frame that dirtied them.
    fn cull_rect_follows(&mut self, transform: Transform) {
        let Some(cull) = self.cull_rect else {
            return;
        };
        self.cull_rect = Some(
            transform
                .about(self.node.pivot, self.node.bounds)
                .inverse()
                .map_or(Rect::default(), |back| back.map_rect(cull)),
        );
    }

    /// Draw this node and everything under it at `opacity`, from 0 to 1.
    ///
    /// Multiplied into every colour the subtree draws, and into its
    /// descendants' own opacities, when the tree is flattened — so a child
    /// that sets one of its own is drawn at the product. Each draw is faded on
    /// its own: where two children overlap, the overlap shows through.
    ///
    /// Clamped here, because a spring overshoots: an opacity past 1 would
    /// brighten nothing and one below 0 would be a negative alpha.
    pub fn set_opacity(&mut self, opacity: f32) {
        self.node.opacity = opacity.clamp(0.0, 1.0);
    }

    /// Set this node's transform origin.
    pub fn set_pivot(&mut self, origin: Pivot) {
        self.node.pivot = origin;
    }

    /// Set this node's local transform with origin.
    pub fn set_transform_with_pivot(&mut self, transform: Transform, origin: Pivot) {
        self.node.local_transform = transform;
        self.node.pivot = origin;
    }

    // -------------------------------------------------------------------------
    // Clipping
    // -------------------------------------------------------------------------

    /// Set a clip region for this node and its children.
    ///
    /// The clip rect is in local coordinates (0,0 = node origin).
    /// All children of this node will be clipped to this region.
    ///
    /// # Arguments
    /// * `rect` - The clip rectangle in local coordinates
    /// * `corner_radius` - Corner radius for rounded clipping
    /// * `curvature` - Superellipse curvature (K-value: 1.0=circle, 2.0=squircle)
    pub fn set_clip(
        &mut self,
        rect: Rect,
        corner_radius: crate::renderer::CornerRadii,
        curvature: f32,
    ) {
        self.node.clip = Some(ClipRegion {
            rect,
            corner_radius,
            curvature,
        });
    }

    /// Set a rectangular clip (no rounded corners).
    ///
    /// This is a convenience method for `set_clip(rect, 0.0, 1.0)`.
    pub fn set_clip_rect(&mut self, rect: Rect) {
        self.set_clip(rect, crate::renderer::CornerRadii::uniform(0.0), 1.0);
    }

    /// Set a clip region only for overlay commands (doesn't clip children).
    ///
    /// Use this for effects like ripples that need to be clipped to the
    /// container's rounded corners without affecting child content.
    ///
    /// # Arguments
    /// * `rect` - The clip rectangle in local coordinates
    /// * `corner_radius` - Corner radius for rounded clipping
    /// * `curvature` - Superellipse curvature (K-value: 1.0=circle, 2.0=squircle)
    pub fn set_overlay_clip(
        &mut self,
        rect: Rect,
        corner_radius: crate::renderer::CornerRadii,
        curvature: f32,
    ) {
        self.node.overlay_clip = Some(ClipRegion {
            rect,
            corner_radius,
            curvature,
        });
    }

    // -------------------------------------------------------------------------
    // Draw Commands (Main Layer)
    // -------------------------------------------------------------------------

    /// Draw a rounded rectangle in local coordinates.
    pub fn draw_rounded_rect(&mut self, rect: Rect, color: Color, radius: impl Into<CornerRadii>) {
        self.node.commands.push(Rc::new(DrawCommand::RoundedRect {
            rect,
            color,
            radius: radius.into(),
            curvature: 1.0,
            border: None,
            shadow: None,
            gradient: None,
        }));
    }

    /// Draw a rounded rectangle with curvature in local coordinates.
    pub fn draw_rounded_rect_with_curvature(
        &mut self,
        rect: Rect,
        color: Color,
        radius: impl Into<CornerRadii>,
        curvature: f32,
    ) {
        self.node.commands.push(Rc::new(DrawCommand::RoundedRect {
            rect,
            color,
            radius: radius.into(),
            curvature,
            border: None,
            shadow: None,
            gradient: None,
        }));
    }

    /// Draw a border frame with curvature.
    pub fn draw_border_frame_with_curvature(
        &mut self,
        rect: Rect,
        border_color: Color,
        radius: impl Into<CornerRadii>,
        border_width: f32,
        curvature: f32,
    ) {
        self.node.commands.push(Rc::new(DrawCommand::RoundedRect {
            rect,
            color: Color::TRANSPARENT,
            radius: radius.into(),
            curvature,
            border: Some(Border::new(border_width, border_color)),
            shadow: None,
            gradient: None,
        }));
    }

    /// Draw a rounded rectangle with shadow.
    pub fn draw_rounded_rect_with_shadow(
        &mut self,
        rect: Rect,
        color: Color,
        radius: impl Into<CornerRadii>,
        curvature: f32,
        shadow: Shadow,
    ) {
        self.node.commands.push(Rc::new(DrawCommand::RoundedRect {
            rect,
            color,
            radius: radius.into(),
            curvature,
            border: None,
            shadow: Some(shadow),
            gradient: None,
        }));
    }

    /// Draw a fully configured rounded rectangle.
    #[allow(clippy::too_many_arguments)]
    pub fn draw_rounded_rect_full(
        &mut self,
        rect: Rect,
        color: Color,
        radius: impl Into<CornerRadii>,
        curvature: f32,
        border: Option<Border>,
        shadow: Option<Shadow>,
        gradient: Option<Gradient>,
    ) {
        self.node.commands.push(Rc::new(DrawCommand::RoundedRect {
            rect,
            color,
            radius: radius.into(),
            curvature,
            border,
            shadow,
            gradient,
        }));
    }

    /// Declare where input reaches this surface, or stops reaching it, over
    /// `rect`. Draws nothing; the region is read off the flattened frame.
    pub fn declare_input_region(
        &mut self,
        rect: Rect,
        corner_radii: impl Into<CornerRadii>,
        curvature: f32,
        takes: bool,
    ) {
        self.node.commands.push(Rc::new(DrawCommand::InputRegion {
            rect,
            corner_radii: corner_radii.into(),
            curvature,
            takes,
        }));
    }

    /// Draw a circle in local coordinates.
    /// Blur whatever is already drawn beneath `rect`, masked to its rounded
    /// shape. Emitted before the container's own background so it paints over
    /// its blurred backdrop.
    pub fn draw_backdrop_blur(
        &mut self,
        rect: Rect,
        sources: crate::backdrop::BackdropSources,
        radius: f32,
        corner_radii: impl Into<CornerRadii>,
        curvature: f32,
    ) {
        self.node.commands.push(Rc::new(DrawCommand::BackdropBlur {
            rect,
            sources,
            radius,
            corner_radii: corner_radii.into(),
            curvature,
        }));
    }

    /// Blur whatever is already drawn beneath the glyphs of `text`, so the
    /// text can be painted over its own blurred backdrop.
    ///
    /// Emitted before the text and its decorations. The arguments have to be
    /// the ones the text is drawn with: the mask is shaped from them, and a
    /// mask shaped differently is a halo.
    #[allow(clippy::too_many_arguments)]
    pub fn draw_text_backdrop_blur(
        &mut self,
        text: &str,
        rect: Rect,
        radius: f32,
        stroke: Option<TextStroke>,
        font_size: f32,
        font_family: FontFamily,
        font_weight: FontWeight,
        line_height: LineHeight,
        letter_spacing: f32,
        align: TextAlign,
        fit: Option<LineFit>,
    ) {
        if text.is_empty() || radius <= 0.0 {
            return;
        }
        self.node
            .commands
            .push(Rc::new(DrawCommand::TextBackdropBlur {
                text: text.to_owned(),
                stroke: stroke.filter(|s| s.width > 0.0),
                rect,
                radius,
                font_size,
                font_family,
                font_weight,
                line_height,
                letter_spacing,
                align,
                fit,
            }));
    }

    pub fn draw_circle(&mut self, cx: f32, cy: f32, radius: f32, color: Color) {
        self.node.commands.push(Rc::new(DrawCommand::Circle {
            center: (cx, cy),
            radius,
            color,
        }));
    }

    // -------------------------------------------------------------------------
    // Text Commands
    // -------------------------------------------------------------------------

    /// Draw text with default font settings, wrapped at `rect`'s width.
    pub fn draw_text(&mut self, text: &str, rect: Rect, color: Color, font_size: f32) {
        self.draw_text_styled(
            text,
            rect,
            color,
            font_size,
            FontFamily::default(),
            FontWeight::NORMAL,
            LineHeight::Normal,
            0.0,
            None,
        );
    }

    /// Draw text with custom font family, weight, line height and letter
    /// spacing, laid out as `fit` says.
    ///
    /// `fit` is the width the text was measured in and the cut, if any: every
    /// path shapes the text in that width, so it is drawn on the lines it was
    /// measured on. Measure and draw with the same one —
    /// [`LineFit::wrapping`](super::LineFit::wrapping) for a text that wraps
    /// at a width. Without a fit the text wraps at `rect`'s width.
    #[allow(clippy::too_many_arguments)]
    pub fn draw_text_styled(
        &mut self,
        text: &str,
        rect: Rect,
        color: Color,
        font_size: f32,
        font_family: FontFamily,
        font_weight: FontWeight,
        line_height: LineHeight,
        letter_spacing: f32,
        fit: Option<LineFit>,
    ) {
        if text.is_empty() {
            return;
        }
        self.push_text(
            &Rc::from(text),
            rect,
            color,
            font_size,
            font_family,
            font_weight,
            line_height,
            letter_spacing,
            TextAlign::Start,
            fit,
        );
    }

    #[allow(clippy::too_many_arguments)]
    fn push_text(
        &mut self,
        text: &Rc<str>,
        rect: Rect,
        color: Color,
        font_size: f32,
        font_family: FontFamily,
        font_weight: FontWeight,
        line_height: LineHeight,
        letter_spacing: f32,
        align: TextAlign,
        fit: Option<LineFit>,
    ) {
        self.node.commands.push(Rc::new(DrawCommand::Text {
            text: Rc::clone(text),
            rect,
            color,
            font_size,
            font_family,
            font_weight,
            line_height,
            letter_spacing,
            align,
            fit,
        }));
    }

    /// Draw text with its decorations, back to front: shadow, stroke, fill.
    ///
    /// The order is the whole point of having this in one place. A stroke
    /// painted *over* the fill eats half the weight of every stem, so the text
    /// reads as thinner rather than outlined — the same reason SVG spells it
    /// `paint-order: stroke fill`.
    #[allow(clippy::too_many_arguments)]
    pub fn draw_text_decorated(
        &mut self,
        text: &str,
        rect: Rect,
        color: Color,
        font_size: f32,
        font_family: FontFamily,
        font_weight: FontWeight,
        line_height: LineHeight,
        letter_spacing: f32,
        align: TextAlign,
        stroke: Option<TextStroke>,
        shadow: Option<TextShadow>,
        fit: Option<LineFit>,
    ) {
        if text.is_empty() {
            return;
        }
        // One string for every copy: the shadow's samples, the stroke's, and
        // the fill each draw the same text.
        let text = &Rc::from(text);

        // Filtered like the stroke below it, and for the same reason the
        // container's shadow is: a fully transparent one still expands into a
        // ring of text copies, every frame, drawing nothing. Spellable
        // deliberately (`TextShadow::new(.., Color::TRANSPARENT)`) and in
        // passing, while an animated shadow colour leaves transparent.
        if let Some(shadow) = shadow.filter(|s| s.color.a > 0.0) {
            for (dx, dy, sample_color) in shadow.samples() {
                self.push_text(
                    text,
                    rect.offset(dx, dy),
                    sample_color,
                    font_size,
                    font_family,
                    font_weight,
                    line_height,
                    letter_spacing,
                    align,
                    fit,
                );
            }
        }

        if let Some(stroke) = stroke.filter(|s| s.width > 0.0) {
            for (dx, dy) in stroke.samples() {
                self.push_text(
                    text,
                    rect.offset(dx, dy),
                    stroke.color,
                    font_size,
                    font_family,
                    font_weight,
                    line_height,
                    letter_spacing,
                    align,
                    fit,
                );
            }
        }

        self.push_text(
            text,
            rect,
            color,
            font_size,
            font_family,
            font_weight,
            line_height,
            letter_spacing,
            align,
            fit,
        );
    }

    // -------------------------------------------------------------------------
    // Image Commands
    // -------------------------------------------------------------------------

    /// Draw an image in local coordinates.
    ///
    /// A raster `Path` or `Bytes` source is decoded off the frame, and an SVG
    /// rasterized there: until that lands this draws nothing, and the widget
    /// painting it is repainted when it does.
    pub fn draw_image(
        &mut self,
        source: ImageSource,
        rect: Rect,
        content_fit: ContentFit,
        tint: Option<Color>,
    ) {
        // Read while painting, so the widget drawing it is repainted when the
        // decode lands — and until then draws nothing.
        let decoded = match crate::image_decode::state(&source) {
            None => None,
            Some((state, decoded)) if crate::image_decode::paints(state, &decoded) => Some(decoded),
            Some(_) => return,
        };
        self.push_image(source, decoded, rect, content_fit, tint);
    }

    /// Push an image whose decode the caller has already resolved — the
    /// `Image` widget, which holds its entry and so needs no lookup.
    pub(crate) fn push_image(
        &mut self,
        source: ImageSource,
        decoded: Option<DecodedImage>,
        rect: Rect,
        content_fit: ContentFit,
        tint: Option<Color>,
    ) {
        self.node.commands.push(Rc::new(DrawCommand::Image {
            source,
            decoded,
            rect,
            content_fit,
            tint,
        }));
    }

    // -------------------------------------------------------------------------
    // Children
    // -------------------------------------------------------------------------

    /// Add a child node and get a context to paint into it.
    ///
    /// The child will inherit transforms from this node automatically
    /// during tree flattening.
    pub(crate) fn add_child(&mut self, widget: WidgetId, bounds: Rect) -> PaintContext<'_> {
        let id: NodeId = widget.as_u64();
        self.node
            .children
            .push(Rc::new(RenderNode::with_bounds(id, bounds)));
        let child = Rc::get_mut(
            self.node
                .children
                .last_mut()
                .expect("child was just pushed"),
        )
        .expect("freshly created child Rc is unique");
        PaintContext::new(child, self.tree, widget, self.scale_factor)
    }

    /// Add a pre-built child node.
    ///
    /// Used by the paint cache: reusing a clean child is `Rc::clone` of its
    /// cached node (or a shallow header clone when its position changed).
    pub(crate) fn add_child_rc(&mut self, node: Rc<RenderNode>) {
        self.node.children.push(node);
    }

    // -------------------------------------------------------------------------
    // Overlay Commands (After Children)
    // -------------------------------------------------------------------------

    /// Draw a circle as overlay (rendered after children).
    /// Used for ripple effects that should appear on top of child content.
    pub fn draw_overlay_circle(&mut self, cx: f32, cy: f32, radius: f32, color: Color) {
        self.node
            .overlay_commands
            .push(Rc::new(DrawCommand::Circle {
                center: (cx, cy),
                radius,
                color,
            }));
    }

    /// Draw a rounded rectangle as overlay (rendered after children).
    pub fn draw_overlay_rounded_rect(
        &mut self,
        rect: Rect,
        color: Color,
        radius: impl Into<CornerRadii>,
    ) {
        self.node
            .overlay_commands
            .push(Rc::new(DrawCommand::RoundedRect {
                rect,
                color,
                radius: radius.into(),
                curvature: 1.0,
                border: None,
                shadow: None,
                gradient: None,
            }));
    }
}