agg-gui 0.2.0

Immediate-mode Rust GUI library with AGG rendering, Y-up layout, widgets, text, SVG, and native/WASM adapters
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
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
//! `DrawCtx` — the unified drawing interface shared by the software (`GfxCtx`)
//! and hardware (`GlGfxCtx`) rendering paths.
//!
//! Every `Widget::paint` implementation receives a `&mut dyn DrawCtx`.  The
//! concrete type is either:
//!
//! - **`GfxCtx`** — software AGG rasteriser (used when a widget opts into a
//!   back-buffer or when GL is unavailable).
//! - **`GlGfxCtx`** — hardware GL path: shapes are tessellated via `tess2`
//!   and submitted as GPU draw calls.
//!
//! The two implementations expose *identical* method signatures so that widget
//! `paint` bodies are unchanged regardless of the render target.

use std::sync::Arc;

use crate::color::Color;
use crate::geometry::Rect;
use crate::text::{Font, TextMetrics};
use crate::theme::Visuals;
use agg_rust::comp_op::CompOp;
use agg_rust::math_stroke::{LineCap, LineJoin};
use agg_rust::trans_affine::TransAffine;

/// Fill rule used when rasterizing closed paths.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum FillRule {
    /// Non-zero winding rule.
    NonZero,
    /// Even-odd parity rule.
    EvenOdd,
}

impl Default for FillRule {
    fn default() -> Self {
        Self::NonZero
    }
}

/// How a gradient behaves outside the normalized `0..=1` range.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum GradientSpread {
    /// Clamp to the nearest edge stop.
    Pad,
    /// Mirror each repeated interval.
    Reflect,
    /// Repeat the gradient ramp.
    Repeat,
}

impl Default for GradientSpread {
    fn default() -> Self {
        Self::Pad
    }
}

/// One color stop in a bridge-level gradient paint.
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct GradientStop {
    pub offset: f64,
    pub color: Color,
}

/// Linear gradient fill paint expressed in local drawing coordinates.
#[derive(Clone, Debug, PartialEq)]
pub struct LinearGradientPaint {
    pub x1: f64,
    pub y1: f64,
    pub x2: f64,
    pub y2: f64,
    pub transform: TransAffine,
    pub spread: GradientSpread,
    pub stops: Vec<GradientStop>,
}

impl LinearGradientPaint {
    pub fn sample(&self, mut x: f64, mut y: f64) -> Color {
        if self.stops.is_empty() {
            return Color::transparent();
        }

        self.transform.inverse_transform(&mut x, &mut y);

        let dx = self.x2 - self.x1;
        let dy = self.y2 - self.y1;
        let len2 = dx * dx + dy * dy;
        let t = if len2 > f64::EPSILON {
            ((x - self.x1) * dx + (y - self.y1) * dy) / len2
        } else {
            0.0
        };
        let t = apply_spread(t, self.spread);

        sample_stops(&self.stops, t)
    }
}

/// Radial/focal gradient fill paint expressed in local drawing coordinates.
#[derive(Clone, Debug, PartialEq)]
pub struct RadialGradientPaint {
    pub cx: f64,
    pub cy: f64,
    pub r: f64,
    pub fx: f64,
    pub fy: f64,
    pub transform: TransAffine,
    pub spread: GradientSpread,
    pub stops: Vec<GradientStop>,
}

impl RadialGradientPaint {
    /// Convenience constructor for the common case: focal point at the centre,
    /// identity transform, `Pad` spread. Stops are `(offset, color)` pairs.
    pub fn centered(cx: f64, cy: f64, r: f64, stops: &[(f64, Color)]) -> Self {
        Self {
            cx,
            cy,
            r,
            fx: cx,
            fy: cy,
            transform: TransAffine::default(),
            spread: GradientSpread::Pad,
            stops: stops
                .iter()
                .map(|(offset, color)| GradientStop {
                    offset: *offset,
                    color: *color,
                })
                .collect(),
        }
    }

    pub fn sample(&self, mut x: f64, mut y: f64) -> Color {
        if self.stops.is_empty() {
            return Color::transparent();
        }

        self.transform.inverse_transform(&mut x, &mut y);

        let dx = x - self.fx;
        let dy = y - self.fy;
        let fx = self.fx - self.cx;
        let fy = self.fy - self.cy;
        let a = dx * dx + dy * dy;
        let t = if a <= f64::EPSILON || self.r <= f64::EPSILON {
            0.0
        } else {
            let b = 2.0 * (fx * dx + fy * dy);
            let c = fx * fx + fy * fy - self.r * self.r;
            let disc = (b * b - 4.0 * a * c).max(0.0);
            let k = (-b + disc.sqrt()) / (2.0 * a);
            if k > f64::EPSILON {
                1.0 / k
            } else {
                0.0
            }
        };
        sample_stops(&self.stops, apply_spread(t, self.spread))
    }
}

/// Repeating raster pattern paint expressed in SVG/user drawing coordinates.
#[derive(Clone, Debug, PartialEq)]
pub struct PatternPaint {
    pub x: f64,
    pub y: f64,
    pub width: f64,
    pub height: f64,
    pub transform: TransAffine,
    /// Straight-alpha RGBA tile pixels in bottom-up row order.
    pub pixels: Arc<Vec<u8>>,
    pub pixel_width: u32,
    pub pixel_height: u32,
}

impl PatternPaint {
    pub fn sample(&self, mut x: f64, mut y: f64) -> Color {
        if self.width <= f64::EPSILON
            || self.height <= f64::EPSILON
            || self.pixel_width == 0
            || self.pixel_height == 0
            || self.pixels.is_empty()
        {
            return Color::transparent();
        }

        self.transform.inverse_transform(&mut x, &mut y);
        let tx = (x - self.x).rem_euclid(self.width);
        let ty_down = (y - self.y).rem_euclid(self.height);
        let px = ((tx / self.width) * self.pixel_width as f64)
            .floor()
            .clamp(0.0, self.pixel_width.saturating_sub(1) as f64) as usize;
        let py = (((self.height - ty_down) / self.height) * self.pixel_height as f64)
            .floor()
            .clamp(0.0, self.pixel_height.saturating_sub(1) as f64) as usize;
        let i = (py * self.pixel_width as usize + px) * 4;
        if i + 3 >= self.pixels.len() {
            return Color::transparent();
        }

        Color::rgba(
            self.pixels[i] as f32 / 255.0,
            self.pixels[i + 1] as f32 / 255.0,
            self.pixels[i + 2] as f32 / 255.0,
            self.pixels[i + 3] as f32 / 255.0,
        )
    }
}

fn apply_spread(t: f64, spread: GradientSpread) -> f64 {
    match spread {
        GradientSpread::Pad => t.clamp(0.0, 1.0),
        GradientSpread::Repeat => t - t.floor(),
        GradientSpread::Reflect => {
            let period = t.rem_euclid(2.0);
            if period <= 1.0 {
                period
            } else {
                2.0 - period
            }
        }
    }
}

fn sample_stops(stops: &[GradientStop], t: f64) -> Color {
    if t <= stops[0].offset {
        return stops[0].color;
    }
    for pair in stops.windows(2) {
        let a = pair[0];
        let b = pair[1];
        if t <= b.offset {
            let span = (b.offset - a.offset).max(f64::EPSILON);
            let u = ((t - a.offset) / span).clamp(0.0, 1.0) as f32;
            return lerp_color(a.color, b.color, u);
        }
    }
    stops[stops.len() - 1].color
}

fn lerp_color(a: Color, b: Color, t: f32) -> Color {
    Color::rgba(
        a.r + (b.r - a.r) * t,
        a.g + (b.g - a.g) * t,
        a.b + (b.b - a.b) * t,
        a.a + (b.a - a.a) * t,
    )
}

// ---------------------------------------------------------------------------
// GL paint hook
// ---------------------------------------------------------------------------

/// Trait for widgets that want to render 3-D (or other GPU) content inline
/// during the widget paint pass.
///
/// `DrawCtx::gl_paint` calls this with an opaque `gl` handle — implementations
/// downcast it to `glow::Context` (or whatever GL type the platform provides).
/// The software `GfxCtx` never calls `paint`; see [`DrawCtx::gl_paint`].
pub trait GlPaint {
    /// Execute GPU draw calls for the widget's 3-D content.
    ///
    /// `gl` — opaque platform GL context; downcast via `std::any::Any`.
    /// `screen_rect` — Y-up screen-space rect for this widget (for viewport/scissor).
    /// `full_w`, `full_h` — full viewport dimensions (for restoring after).
    /// `parent_clip` — current framework scissor rect `[x, y, w, h]` in GL/Y-up
    ///   pixels, or `None` if no clip is active.  Implementations **must intersect**
    ///   any scissor they set with this rect so that parent widget clips (e.g. a
    ///   collapsed window) correctly hide GPU-rendered content.
    fn gl_paint(
        &mut self,
        gl: &dyn std::any::Any,
        screen_rect: Rect,
        full_w: i32,
        full_h: i32,
        parent_clip: Option<[i32; 4]>,
    );
}

/// Unified 2-D drawing context.
///
/// All coordinate parameters use the **Y-up, first-quadrant** convention:
/// origin at the bottom-left, positive-Y upward.  This matches `GfxCtx` and
/// the widget tree layout invariant.
pub trait DrawCtx {
    /// Optional escape hatch for widgets that need direct access to a
    /// backend-specific concrete context (e.g. to push a custom GPU draw
    /// command into the deferred command stream).
    ///
    /// The default returns `None`; backends that opt in override to return
    /// `Some(self)`.  Callers must handle the `None` case gracefully — if a
    /// widget falls back through `gl_paint` it works on every backend.
    fn as_any_mut(&mut self) -> Option<&mut dyn std::any::Any> {
        None
    }

    // ── State ─────────────────────────────────────────────────────────────────

    fn set_fill_color(&mut self, color: Color);
    fn set_stroke_color(&mut self, color: Color);
    fn set_fill_linear_gradient(&mut self, _gradient: LinearGradientPaint) {}
    fn set_fill_radial_gradient(&mut self, _gradient: RadialGradientPaint) {}
    fn set_fill_pattern(&mut self, _pattern: PatternPaint) {}
    fn set_stroke_linear_gradient(&mut self, _gradient: LinearGradientPaint) {}
    fn set_stroke_radial_gradient(&mut self, _gradient: RadialGradientPaint) {}
    fn set_stroke_pattern(&mut self, _pattern: PatternPaint) {}
    fn supports_fill_linear_gradient(&self) -> bool {
        false
    }
    fn supports_fill_radial_gradient(&self) -> bool {
        false
    }
    fn supports_fill_pattern(&self) -> bool {
        false
    }
    fn supports_stroke_linear_gradient(&self) -> bool {
        false
    }
    fn supports_stroke_radial_gradient(&self) -> bool {
        false
    }
    fn supports_stroke_pattern(&self) -> bool {
        false
    }
    fn set_line_width(&mut self, w: f64);
    fn set_line_join(&mut self, join: LineJoin);
    fn set_line_cap(&mut self, cap: LineCap);
    fn set_miter_limit(&mut self, limit: f64);
    fn set_line_dash(&mut self, dashes: &[f64], offset: f64);
    fn set_blend_mode(&mut self, mode: CompOp);
    fn set_global_alpha(&mut self, alpha: f64);
    fn set_fill_rule(&mut self, rule: FillRule);

    // ── Font ──────────────────────────────────────────────────────────────────

    fn set_font(&mut self, font: Arc<Font>);
    fn set_font_size(&mut self, size: f64);

    // ── Clipping ──────────────────────────────────────────────────────────────

    fn clip_rect(&mut self, x: f64, y: f64, w: f64, h: f64);
    fn reset_clip(&mut self);

    // ── Clear ─────────────────────────────────────────────────────────────────

    /// Fill the entire render target with `color`, ignoring the current clip.
    fn clear(&mut self, color: Color);

    // ── Path building ─────────────────────────────────────────────────────────

    fn begin_path(&mut self);
    fn move_to(&mut self, x: f64, y: f64);
    fn line_to(&mut self, x: f64, y: f64);
    fn cubic_to(&mut self, cx1: f64, cy1: f64, cx2: f64, cy2: f64, x: f64, y: f64);
    fn quad_to(&mut self, cx: f64, cy: f64, x: f64, y: f64);
    fn arc_to(&mut self, cx: f64, cy: f64, r: f64, start_angle: f64, end_angle: f64, ccw: bool);

    /// Add a full circle contour to the current path.
    fn circle(&mut self, cx: f64, cy: f64, r: f64);

    /// Add an axis-aligned rectangle contour to the current path.
    fn rect(&mut self, x: f64, y: f64, w: f64, h: f64);

    /// Add a rounded-rectangle contour to the current path.
    fn rounded_rect(&mut self, x: f64, y: f64, w: f64, h: f64, r: f64);

    fn close_path(&mut self);

    // ── Path drawing ──────────────────────────────────────────────────────────

    fn fill(&mut self);
    fn stroke(&mut self);
    fn fill_and_stroke(&mut self);

    /// Submit **pre-tessellated** AA triangles with per-vertex coverage
    /// (`x`, `y`, `alpha`) and triangle indices.
    ///
    /// This is the fast path for callers that tessellate their geometry
    /// ONCE at load time (e.g. the Lion demo, SVG icons): they do the
    /// `tessellate_path_aa` pass themselves, cache the vertex+index
    /// buffers, then submit them every frame with only a cheap CPU
    /// transform applied to the x/y components.  Compared to issuing
    /// `move_to` / `line_to` / `fill` every frame, this keeps the polygon
    /// set deterministic (no tess2 re-running on subtly-different
    /// coordinates), avoids thousands of re-tessellations per frame, and
    /// produces identical output regardless of the widget's transform.
    ///
    /// Vertices are `(x_logical_pixels, y_logical_pixels, alpha_0_to_1)`.
    /// `alpha` is multiplied into the supplied `color.a` in the AA shader
    /// so halo-strip edge AA survives this fast path.
    ///
    /// The software `GfxCtx` ignores the alpha attribute and rasterises
    /// each triangle as a solid fill — correct but without edge AA, which
    /// matches the software path's existing stroke/fill behaviour.
    fn draw_triangles_aa(
        &mut self,
        vertices: &[[f32; 3]],
        indices: &[u32],
        color: crate::color::Color,
    );

    // ── Text ──────────────────────────────────────────────────────────────────

    /// Draw `text` with the bottom of the baseline at `(x, y)`.
    fn fill_text(&mut self, text: &str, x: f64, y: f64);

    /// Draw `text` using the built-in AGG Glyph-Stroke-Vector font at `size`
    /// pixels.  Useful before a proper font is loaded.
    fn fill_text_gsv(&mut self, text: &str, x: f64, y: f64, size: f64);

    /// Measure `text` with the current font and font-size settings.
    fn measure_text(&self, text: &str) -> Option<TextMetrics>;

    // ── Transform ─────────────────────────────────────────────────────────────

    /// Current accumulated transform (CTM).
    fn transform(&self) -> TransAffine;

    /// Current transform expressed in the root render target's coordinate
    /// space, even when drawing inside an offscreen layer whose local CTM was
    /// reset to identity. Global overlays use this to submit app-level bounds.
    fn root_transform(&self) -> TransAffine {
        self.transform()
    }

    fn save(&mut self);
    fn restore(&mut self);
    fn translate(&mut self, tx: f64, ty: f64);
    fn rotate(&mut self, radians: f64);
    fn scale(&mut self, sx: f64, sy: f64);
    fn set_transform(&mut self, m: TransAffine);
    fn reset_transform(&mut self);

    /// **Opt-in** pixel snapping.  Strips the fractional part of the current
    /// CTM translation so subsequent integer-coordinate `rect` / `fill` /
    /// `stroke` / `draw_image_rgba*` calls land exactly on the physical pixel
    /// grid — no AA fringe on edges, no LINEAR-filter blur on 1:1 texture
    /// blits.
    ///
    /// Call this ONLY when the widget genuinely wants pixel-aligned drawing
    /// (text backbuffers, pixel-alignment diagnostics, crisp UI strokes).
    /// Sub-pixel positioning remains the default — e.g. a smooth-scrolling
    /// panel or an animated marker may legitimately want a fractional offset.
    /// Typical usage:
    /// ```ignore
    /// ctx.save();
    /// ctx.snap_to_pixel();
    /// ctx.rect(0.0, 0.0, 10.0, 10.0);
    /// ctx.fill();
    /// ctx.restore();
    /// ```
    ///
    /// Only the translation component is affected; rotations and non-uniform
    /// scales pass through untouched (pixel alignment under those transforms
    /// isn't well defined, and forcing a snap would visibly jitter rotated
    /// content).
    fn snap_to_pixel(&mut self) {
        let t = self.transform();
        let fx = t.tx - t.tx.floor();
        let fy = t.ty - t.ty.floor();
        if fx != 0.0 || fy != 0.0 {
            self.translate(-fx, -fy);
        }
    }

    // ── Compositing layers ────────────────────────────────────────────────────

    /// Begin a new transparent compositing layer of the given pixel dimensions.
    ///
    /// All subsequent drawing (by this widget and its descendants) is redirected
    /// into the new layer until [`pop_layer`] is called.  Layers nest: each
    /// `push_layer` must be matched by exactly one `pop_layer`.
    ///
    /// The current accumulated transform records the layer's screen-space origin;
    /// drawing inside the layer uses a fresh local-space transform (origin 0,0).
    ///
    /// Implementations that do not support layers (e.g. the GL path) may leave
    /// this as a no-op — the widget renders pass-through into the parent target.
    fn push_layer(&mut self, _width: f64, _height: f64) {}

    /// Whether this backend implements real offscreen compositing layers.
    ///
    /// The default is `false` so widgets can opt into layer-based rendering
    /// without forcing every backend to pay for, or emulate, that feature.
    fn supports_compositing_layers(&self) -> bool {
        false
    }

    /// Whether this backend can retain named offscreen layers across frames.
    ///
    /// Generic compositing support is enough for isolated opacity groups, but
    /// retained widget backbuffers need a backend-owned surface keyed by ID.
    fn supports_retained_layers(&self) -> bool {
        false
    }

    /// Begin a new transparent compositing layer that will be multiplied by
    /// `alpha` when composited back into the parent target.
    ///
    /// Backends that do not support layer alpha can fall back to `push_layer`;
    /// callers gate this through [`supports_compositing_layers`].
    fn push_layer_with_alpha(&mut self, width: f64, height: f64, _alpha: f64) {
        self.push_layer(width, height);
    }

    /// Constrain subsequent drawing in the current layer to a rounded-rect
    /// mask. Used by window layers after shadows are drawn so chrome/content
    /// cannot write into rounded transparent corners.
    ///
    /// This is a containment clip, not the visual antialiasing edge. Backends
    /// should leave enough room for partially-transparent edge pixels so the
    /// caller's normal alpha coverage can feather corners and edges.
    fn set_layer_rounded_clip(&mut self, _x: f64, _y: f64, _w: f64, _h: f64, _r: f64) {}

    /// Composite a previously retained backend layer. Returns `true` when
    /// the backend had a retained surface for `key` and drew it.
    fn composite_retained_layer(
        &mut self,
        _key: u64,
        _width: f64,
        _height: f64,
        _alpha: f64,
    ) -> bool {
        false
    }

    /// Begin rendering into a retained backend layer identified by `key`.
    /// Backends that do not retain layers may fall back to a transient layer.
    fn push_retained_layer_with_alpha(&mut self, _key: u64, width: f64, height: f64, alpha: f64) {
        self.push_layer_with_alpha(width, height, alpha);
    }

    /// Composite the current layer back into the previous render target using
    /// SrcOver alpha blending, then discard the layer.
    ///
    /// Must be called after a matching `push_layer`.  Unmatched calls are ignored.
    fn pop_layer(&mut self) {}

    // ── GL / GPU content ──────────────────────────────────────────────────────

    /// Render GPU content (3-D scene, video frame, etc.) inline at the correct
    /// painter-order position.
    ///
    /// `screen_rect` is the widget's screen-space rect in Y-up coordinates
    /// (i.e. `ctx.transform()` origin + `widget.bounds().size`).
    ///
    /// The GL implementation executes `painter.gl_paint()` immediately so that
    /// any 2-D widgets painted after this call naturally overdraw the GPU
    /// content — correct back-to-front ordering with no post-frame fixup.
    ///
    /// The **software (`GfxCtx`) path is a no-op**: widgets should draw a 2-D
    /// placeholder before calling this method so the software render has
    /// something visible.
    fn gl_paint(&mut self, _screen_rect: Rect, _painter: &mut dyn GlPaint) {}

    // ── LCD mask compositing ──────────────────────────────────────────────────

    /// Composite a pre-rasterized LCD subpixel mask onto the current
    /// render target, mixing `src_color` into the destination through
    /// per-channel coverage.
    ///
    /// `mask` is three bytes per pixel (`cov_r`, `cov_g`, `cov_b`) as
    /// produced by [`crate::text_lcd::rasterize_lcd_mask`].  The caller
    /// specifies `(dst_x, dst_y)` in local coordinates (Y-up in our
    /// convention) and `mask_w × mask_h` to tell the backend the mask's
    /// dimensions.
    ///
    /// Per-channel source-over blend:
    /// ```text
    /// dst.r = src.r * mask.r + dst.r * (1 - mask.r)
    /// dst.g = src.g * mask.g + dst.g * (1 - mask.g)
    /// dst.b = src.b * mask.b + dst.b * (1 - mask.b)
    /// ```
    ///
    /// **This is the universal "composite LCD text onto arbitrary bg"
    /// primitive** — it replaces the prior walk / sample / pre-fill
    /// approach.  Software ctx implements it as an inner-loop blend; the
    /// GL ctx implements it via a dual-source-blend fragment shader.
    /// Backends that haven't wired it yet use the default no-op, which
    /// makes callers fall back to grayscale AA.
    fn draw_lcd_mask(
        &mut self,
        _mask: &[u8],
        _mask_w: u32,
        _mask_h: u32,
        _src_color: Color,
        _dst_x: f64,
        _dst_y: f64,
    ) {
    }

    /// Arc-keyed variant so GL backends can cache the uploaded texture
    /// on the `Arc`'s pointer identity — one `glTexImage2D` per unique
    /// raster, lifetime tied to the mask's strong-ref count.  Software
    /// backends fall through to the slice path.
    fn draw_lcd_mask_arc(
        &mut self,
        mask: &std::sync::Arc<Vec<u8>>,
        mask_w: u32,
        mask_h: u32,
        src_color: Color,
        dst_x: f64,
        dst_y: f64,
    ) {
        self.draw_lcd_mask(mask.as_slice(), mask_w, mask_h, src_color, dst_x, dst_y);
    }

    /// Returns `true` if this backend supports [`draw_lcd_mask`] — i.e.
    /// it can composite per-channel LCD coverage onto the active target.
    /// Label queries this to decide between the LCD and grayscale AA
    /// paths; a backend that returns `false` will never see LCD text.
    fn has_lcd_mask_composite(&self) -> bool {
        false
    }

    // ── Image blitting ────────────────────────────────────────────────────────

    /// Returns `true` if this context implements `draw_image_rgba` with actual
    /// pixel blitting.  `Label` (and any other widget that uses a software
    /// backbuffer) gates its cache path on this method so it can fall back to
    /// direct `fill_text()` on render targets that don't support blitting
    /// (e.g. the GL path).
    ///
    /// Default: `false`.  Override to `true` in `GfxCtx`.
    fn has_image_blit(&self) -> bool {
        false
    }

    /// Draw raw RGBA pixel data into `dst_rect` (Y-up local coordinates).
    ///
    /// `data` must be `img_w * img_h * 4` bytes of tightly-packed RGBA8 data
    /// in row-major order, **top-row first** (Y-down image storage convention).
    /// The image is scaled to fit `(dst_x, dst_y, dst_w, dst_h)`.
    ///
    /// Default implementation: no-op (GL path or software paths that do not
    /// implement blitting can leave this as a placeholder).
    fn draw_image_rgba(
        &mut self,
        data: &[u8],
        img_w: u32,
        img_h: u32,
        dst_x: f64,
        dst_y: f64,
        dst_w: f64,
        dst_h: f64,
    ) {
        let _ = (data, img_w, img_h, dst_x, dst_y, dst_w, dst_h);
    }

    /// Same as [`draw_image_rgba`] but accepts an `Arc<Vec<u8>>` so the GL
    /// backend can key its texture cache on the `Arc`'s pointer identity and
    /// hold a `Weak` ref for automatic cleanup when the underlying buffer is
    /// dropped — the pattern MatterCAD implements with C# `ConditionalWeakTable`.
    ///
    /// Used by `Label` (and future glyph-atlas consumers) in tandem with the
    /// crate-level [`image_cache`](crate::image_cache) so that rebuilt widget
    /// trees with unchanged content never re-rasterize OR re-upload.
    ///
    /// Default implementation: forward to [`draw_image_rgba`] via slice
    /// borrow.  Software backends don't benefit from GPU texture caching so
    /// the default is usually fine; the GL backend overrides.
    fn draw_image_rgba_arc(
        &mut self,
        data: &std::sync::Arc<Vec<u8>>,
        img_w: u32,
        img_h: u32,
        dst_x: f64,
        dst_y: f64,
        dst_w: f64,
        dst_h: f64,
    ) {
        self.draw_image_rgba(data.as_slice(), img_w, img_h, dst_x, dst_y, dst_w, dst_h);
    }

    // ── LCD backbuffer blit ───────────────────────────────────────────────────

    /// Composite a two-plane `LcdCoverage`-mode backbuffer onto the active
    /// render target at `(dst_x, dst_y)` with size `(dst_w, dst_h)` (in
    /// local coords).  Inputs are two `Arc<Vec<u8>>`, each 3 bytes per
    /// pixel, **top-row-first**:
    ///
    /// - `color`: premultiplied per-channel RGB.
    /// - `alpha`: per-channel alpha (coverage).
    ///
    /// The compositor applies per-channel premultiplied src-over:
    ///
    /// ```text
    /// dst.ch := src.color_ch + dst.ch * (1 - src.alpha_ch)
    /// ```
    ///
    /// which preserves LCD subpixel chroma through the cache round-trip.
    /// Used by [`crate::widget::paint_subtree_backbuffered`] when a widget's
    /// [`crate::widget::BackbufferMode::LcdCoverage`] cache is ready to
    /// composite onto its parent.
    ///
    /// **Default:** collapses the two planes into a single straight-alpha
    /// RGBA8 image (max of channel alphas, divided back to straight colour)
    /// and forwards to [`draw_image_rgba`].  Correct for any content where
    /// the three channel alphas agree; lossy of LCD chroma where they
    /// diverge.  Backends that want full subpixel quality through the
    /// cache override this with a two-texture shader path.
    fn draw_lcd_backbuffer_arc(
        &mut self,
        color: &std::sync::Arc<Vec<u8>>,
        alpha: &std::sync::Arc<Vec<u8>>,
        w: u32,
        h: u32,
        dst_x: f64,
        dst_y: f64,
        dst_w: f64,
        dst_h: f64,
    ) {
        // Collapse to straight-alpha RGBA8 on the fly.  Matches the same
        // math `LcdBuffer::to_rgba8_top_down_collapsed` uses internally,
        // except applied to a top-down pair rather than a Y-up pair.
        let w_u = w as usize;
        let h_u = h as usize;
        if color.len() < w_u * h_u * 3 || alpha.len() < w_u * h_u * 3 {
            return;
        }
        let mut rgba = vec![0u8; w_u * h_u * 4];
        for i in 0..(w_u * h_u) {
            let ci = i * 3;
            let ra = alpha[ci];
            let ga = alpha[ci + 1];
            let ba = alpha[ci + 2];
            let a = ra.max(ga).max(ba);
            if a == 0 {
                continue;
            }
            let af = a as f32 / 255.0;
            let rc = color[ci] as f32 / 255.0;
            let gc = color[ci + 1] as f32 / 255.0;
            let bc = color[ci + 2] as f32 / 255.0;
            let di = i * 4;
            rgba[di] = ((rc / af) * 255.0 + 0.5).clamp(0.0, 255.0) as u8;
            rgba[di + 1] = ((gc / af) * 255.0 + 0.5).clamp(0.0, 255.0) as u8;
            rgba[di + 2] = ((bc / af) * 255.0 + 0.5).clamp(0.0, 255.0) as u8;
            rgba[di + 3] = a;
        }
        self.draw_image_rgba(&rgba, w, h, dst_x, dst_y, dst_w, dst_h);
    }

    // ── Screenshot capture (GPU-direct path) ──────────────────────────────────
    //
    // Hardware-accelerated screenshot pipeline.  The capture lives on the GPU
    // as a backend-internal texture, so the live preview pane samples it
    // directly with proper downsample filtering — no CPU readback per frame,
    // no re-upload, no mipmap generation in the hot path.  Pixels are pulled
    // back to system memory only when the user actually clicks Save / Copy.
    //
    // Default impls are no-ops returning `false` / empty so the software
    // backend stays unchanged: the screenshot widget falls back to the
    // existing `draw_image_rgba_arc` + Vec<u8> path automatically.

    /// Snapshot the current frame's surface into the backend's internal
    /// screenshot texture (allocating / resizing as needed).  Must be
    /// called inside the active frame, after `end_frame` has flushed the
    /// 2-D render but before the platform shell calls present.
    ///
    /// Returns `true` if the backend supports the capture path.
    fn capture_screenshot(&mut self) -> bool {
        false
    }

    /// True if a previously-captured screenshot is held by the backend
    /// and available for [`Self::draw_captured_screenshot`].
    fn has_captured_screenshot(&self) -> bool {
        false
    }

    /// Dimensions of the held capture, or `None` when no capture exists.
    fn captured_screenshot_size(&self) -> Option<(u32, u32)> {
        None
    }

    /// Draw the held capture into `(dst_x, dst_y, dst_w, dst_h)` using the
    /// backend's preferred filtered sampling.  Returns `true` if the
    /// capture exists and was drawn.
    fn draw_captured_screenshot(
        &mut self,
        _dst_x: f64,
        _dst_y: f64,
        _dst_w: f64,
        _dst_h: f64,
    ) -> bool {
        false
    }

    /// Read the held capture's pixels back to CPU memory as Y-down RGBA8 —
    /// for Save / Copy.  This is intentionally a single-shot synchronous
    /// readback; widgets should NOT call this every frame.  Returns
    /// `(empty, 0, 0)` on backends without a capture or without GPU
    /// readback support.
    fn read_captured_screenshot(&mut self) -> (Vec<u8>, u32, u32) {
        (Vec::new(), 0, 0)
    }

    // ── Theme / Visuals ───────────────────────────────────────────────────────

    /// Return the currently-active [`Visuals`] palette.
    ///
    /// Delegates to [`crate::theme::current_visuals`], which reads the
    /// thread-local set by [`crate::theme::set_visuals`].  Widget `paint()`
    /// implementations call this to get colours instead of hardcoding them.
    fn visuals(&self) -> Visuals {
        crate::theme::current_visuals()
    }
}