agg-gui 0.1.0

A Rust GUI framework built on AGG — immediate-mode widgets, Y-up layout, halo-AA rendering via tess2
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
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
//! Graphics context — the primary drawing API for widget painting.
//!
//! `GfxCtx` is modeled after Cairo's `cairo_t`. All drawing goes through this
//! type. It owns a stateful transform + style stack and writes pixels into a
//! [`Framebuffer`] via AGG.
//!
//! # Coordinate system
//!
//! All coordinates are **first-quadrant (Y-up)**. Origin is the bottom-left
//! corner of the framebuffer. Positive X goes right, positive Y goes up.
//! Positive angles rotate counter-clockwise (mathematically standard).

use std::f64::consts::PI;
use std::sync::Arc;

use agg_rust::arc::Arc as AggArc;
use agg_rust::basics::PATH_FLAGS_NONE;
use agg_rust::comp_op::{CompOp, PixfmtRgba32CompOp};
use agg_rust::conv_curve::ConvCurve;
use agg_rust::conv_stroke::ConvStroke;
use agg_rust::conv_transform::ConvTransform;
use agg_rust::gsv_text::GsvText;
use agg_rust::math_stroke::{LineCap, LineJoin};
use agg_rust::path_storage::PathStorage;
use agg_rust::rasterizer_scanline_aa::RasterizerScanlineAa;
use agg_rust::renderer_base::RendererBase;
use agg_rust::renderer_scanline::render_scanlines_aa_solid;
use agg_rust::rendering_buffer::RowAccessor;
use agg_rust::rounded_rect::RoundedRect;
use agg_rust::scanline_u::ScanlineU8;
use agg_rust::trans_affine::TransAffine;

use crate::color::Color;
use crate::framebuffer::Framebuffer;
use crate::text::{shape_text, measure_advance, Font, TextMetrics};

// ---------------------------------------------------------------------------
// Layer stack entry
// ---------------------------------------------------------------------------

/// One entry on the `GfxCtx` layer stack, created by `push_layer`.
struct LayerEntry {
    /// The offscreen framebuffer for this layer.
    fb:             Framebuffer,
    /// GfxState snapshot at the moment `push_layer` was called.
    /// Restored verbatim on `pop_layer`.
    saved_state:    GfxState,
    /// State-stack snapshot at the moment `push_layer` was called.
    saved_stack:    Vec<GfxState>,
    /// Screen-space X origin of this layer (= CTM tx at push time, Y-up).
    origin_x:       f64,
    /// Screen-space Y origin of this layer (= CTM ty at push time, Y-up).
    origin_y:       f64,
}

// Re-export so callers don't need to import agg_rust directly.
pub use agg_rust::comp_op::CompOp as BlendMode;

/// Snapshot of drawing state, pushed/popped by `save()`/`restore()`.
#[derive(Clone)]
struct GfxState {
    transform: TransAffine,
    fill_color: Color,
    stroke_color: Color,
    line_width: f64,
    line_join: LineJoin,
    line_cap: LineCap,
    blend_mode: CompOp,
    /// Scissor clip in Y-up screen space: `(x, y, width, height)`.
    clip: Option<(f64, f64, f64, f64)>,
    /// Global alpha multiplier applied to fill and stroke at draw time.
    global_alpha: f64,
    /// Current font (shared).
    font: Option<Arc<Font>>,
    /// Font size in pixels (height from baseline to top of cap height).
    font_size: f64,
}

impl Default for GfxState {
    fn default() -> Self {
        Self {
            transform: TransAffine::new(),
            fill_color: Color::black(),
            stroke_color: Color::black(),
            line_width: 1.0,
            line_join: LineJoin::Round,
            line_cap: LineCap::Round,
            blend_mode: CompOp::SrcOver,
            clip: None,
            global_alpha: 1.0,
            font: None,
            font_size: 16.0,
        }
    }
}

/// Cairo-style stateful 2D graphics context.
///
/// All widget painting goes through `GfxCtx`. Create one per frame from a
/// [`Framebuffer`], draw into it, then let it drop — the framebuffer retains
/// the rendered pixels.
///
/// # Layer compositing
///
/// Call `push_layer(w, h)` to redirect all subsequent drawing into an offscreen
/// framebuffer.  Call `pop_layer()` to SrcOver-composite that buffer back into
/// the previous target (which may itself be a layer or the base framebuffer).
/// Layers nest; each `push` must be matched by exactly one `pop`.
pub struct GfxCtx<'a> {
    base_fb:     &'a mut Framebuffer,
    /// Offscreen layer stack.  Empty when rendering directly to `base_fb`.
    layer_stack: Vec<LayerEntry>,
    state:       GfxState,
    state_stack: Vec<GfxState>,
    /// Accumulated path, reset by `begin_path()`.
    path:        PathStorage,
    /// When true, `fill_text` routes through the 3× horizontal LCD
    /// subpixel pipeline (see `lcd_coverage.rs`) and composites per-channel
    /// onto the active framebuffer.  Controlled by the backbuffer mode —
    /// set to true when this ctx is writing into an `LcdCoverage` widget
    /// backbuffer, false for `Rgba`.  Main render loops set it at frame
    /// start from `font_settings::lcd_enabled()`.
    lcd_mode: bool,
}

impl<'a> GfxCtx<'a> {
    /// Create a new graphics context for the given framebuffer.
    pub fn new(fb: &'a mut Framebuffer) -> Self {
        Self {
            base_fb: fb,
            layer_stack: Vec::new(),
            state: GfxState::default(),
            state_stack: Vec::new(),
            path: PathStorage::new(),
            lcd_mode: false,
        }
    }

    // -------------------------------------------------------------------------
    // Layer compositing
    // -------------------------------------------------------------------------

    /// Begin an offscreen compositing layer of `width × height` pixels.
    ///
    /// All draw calls until the matching `pop_layer` are redirected into a fresh
    /// transparent `Framebuffer`.  The current CTM's translation records the
    /// layer's screen-space origin; drawing inside uses a reset local transform.
    pub fn push_layer(&mut self, width: f64, height: f64) {
        let origin_x = self.state.transform.tx;
        let origin_y = self.state.transform.ty;
        let saved_state = self.state.clone();
        let saved_stack = std::mem::take(&mut self.state_stack);
        let layer_fb = Framebuffer::new(width.ceil() as u32, height.ceil() as u32);
        self.layer_stack.push(LayerEntry {
            fb: layer_fb,
            saved_state,
            saved_stack,
            origin_x,
            origin_y,
        });
        // Reset to local-space origin for the new layer.
        self.state.transform = TransAffine::new();
        self.state.clip = None;
    }

    /// SrcOver-composite the current layer into the previous render target, then
    /// restore the graphics state that was active at the matching `push_layer`.
    pub fn pop_layer(&mut self) {
        let Some(layer) = self.layer_stack.pop() else { return; };
        let ox = layer.origin_x as i32;
        let oy = layer.origin_y as i32;
        self.state       = layer.saved_state;
        self.state_stack = layer.saved_stack;
        // Composite: src = layer.fb, dst = now-active framebuffer.
        if let Some(top) = self.layer_stack.last_mut() {
            composite_framebuffers(&mut top.fb, &layer.fb, ox, oy);
        } else {
            composite_framebuffers(self.base_fb, &layer.fb, ox, oy);
        }
    }

    // -------------------------------------------------------------------------
    // State stack
    // -------------------------------------------------------------------------

    pub fn save(&mut self) {
        self.state_stack.push(self.state.clone());
    }

    pub fn restore(&mut self) {
        if let Some(state) = self.state_stack.pop() {
            self.state = state;
        }
    }

    // -------------------------------------------------------------------------
    // Transform (Y-up, CCW-positive rotations)
    // -------------------------------------------------------------------------

    /// Append a translation. Uses pre-multiply (Cairo semantics).
    pub fn translate(&mut self, tx: f64, ty: f64) {
        self.state.transform.premultiply(&TransAffine::new_translation(tx, ty));
    }

    /// Append a CCW rotation in radians. Uses pre-multiply semantics.
    pub fn rotate(&mut self, radians: f64) {
        self.state.transform.premultiply(&TransAffine::new_rotation(radians));
    }

    /// Append a scale. Uses pre-multiply semantics.
    pub fn scale(&mut self, sx: f64, sy: f64) {
        self.state.transform.premultiply(&TransAffine::new_scaling(sx, sy));
    }

    pub fn set_transform(&mut self, m: TransAffine) { self.state.transform = m; }
    pub fn reset_transform(&mut self) { self.state.transform = TransAffine::new(); }
    /// Return the current accumulated transform (cumulative translation + scale
    /// from all parent `save/translate/restore` calls). The `tx`/`ty` fields
    /// give the widget's bottom-left corner in framebuffer (Y-up) coordinates.
    pub fn transform(&self) -> TransAffine { self.state.transform }

    // -------------------------------------------------------------------------
    // Style
    // -------------------------------------------------------------------------

    pub fn set_fill_color(&mut self, color: Color) { self.state.fill_color = color; }
    pub fn set_stroke_color(&mut self, color: Color) { self.state.stroke_color = color; }
    pub fn set_line_width(&mut self, w: f64) { self.state.line_width = w; }
    pub fn set_line_join(&mut self, join: LineJoin) { self.state.line_join = join; }
    pub fn set_line_cap(&mut self, cap: LineCap) { self.state.line_cap = cap; }

    /// Set the Porter-Duff compositing mode. Default: `SrcOver`.
    pub fn set_blend_mode(&mut self, mode: CompOp) { self.state.blend_mode = mode; }

    /// Global alpha multiplier (0.0–1.0) applied on top of each color's alpha.
    pub fn set_global_alpha(&mut self, alpha: f64) {
        self.state.global_alpha = alpha.clamp(0.0, 1.0);
    }

    // -------------------------------------------------------------------------
    // Font
    // -------------------------------------------------------------------------

    /// Set the current font. Shared via `Arc` — cheap to clone across widgets.
    pub fn set_font(&mut self, font: Arc<Font>) {
        self.state.font = Some(font);
    }

    /// Set the font size in pixels (distance from baseline to cap height).
    pub fn set_font_size(&mut self, size: f64) {
        self.state.font_size = size.max(1.0);
    }

    /// Enable/disable LCD subpixel rendering on this ctx.  When true,
    /// `fill_text` uses the per-channel coverage pipeline; when false
    /// grayscale AA.  Set by `paint_subtree_backbuffered` for
    /// `LcdCoverage` widget buffers, and by the main render loop for
    /// direct-to-screen text.
    pub fn set_lcd_mode(&mut self, on: bool) { self.lcd_mode = on; }

    /// Read the ctx's current LCD mode.
    pub fn lcd_mode(&self) -> bool { self.lcd_mode }

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

    /// Intersect the current clip with a rectangle in the **current local
    /// coordinate space** (i.e. after all accumulated `translate` / `scale`
    /// calls).  The four corners are mapped through the current transform to
    /// produce an axis-aligned screen-space bounding box, which is then
    /// intersected with any existing clip.
    ///
    /// For the common case of pure translations this is equivalent to the old
    /// "screen-space rectangle" API, but it now works correctly when called
    /// from inside a `paint()` method that runs after the framework has already
    /// translated the context to the widget's origin.
    pub fn clip_rect(&mut self, x: f64, y: f64, w: f64, h: f64) {
        // Map all four corners through the CTM and take the AABB.
        let t = &self.state.transform;
        let corners = [(x, y), (x + w, y), (x + w, y + h), (x, y + h)];
        let mut sx_min = f64::INFINITY;
        let mut sy_min = f64::INFINITY;
        let mut sx_max = f64::NEG_INFINITY;
        let mut sy_max = f64::NEG_INFINITY;
        for (lx, ly) in corners {
            let mut sx = lx;
            let mut sy = ly;
            t.transform(&mut sx, &mut sy);
            if sx < sx_min { sx_min = sx; }
            if sx > sx_max { sx_max = sx; }
            if sy < sy_min { sy_min = sy; }
            if sy > sy_max { sy_max = sy; }
        }
        let sw = (sx_max - sx_min).max(0.0);
        let sh = (sy_max - sy_min).max(0.0);
        if let Some((cx, cy, cw, ch)) = self.state.clip {
            let x1 = sx_min.max(cx);
            let y1 = sy_min.max(cy);
            let x2 = sx_max.min(cx + cw);
            let y2 = sy_max.min(cy + ch);
            self.state.clip = Some((x1, y1, (x2 - x1).max(0.0), (y2 - y1).max(0.0)));
        } else {
            self.state.clip = Some((sx_min, sy_min, sw, sh));
        }
    }

    pub fn reset_clip(&mut self) { self.state.clip = None; }

    // -------------------------------------------------------------------------
    // Clear
    // -------------------------------------------------------------------------

    /// Fill the entire active framebuffer with `color`, ignoring transform and clip.
    pub fn clear(&mut self, color: Color) {
        let rgba = color.to_rgba8();
        for chunk in active_fb(&mut self.base_fb, &mut self.layer_stack).pixels_mut().chunks_exact_mut(4) {
            chunk[0] = rgba.r as u8;
            chunk[1] = rgba.g as u8;
            chunk[2] = rgba.b as u8;
            chunk[3] = rgba.a as u8;
        }
    }

    // -------------------------------------------------------------------------
    // Path construction
    // -------------------------------------------------------------------------

    pub fn begin_path(&mut self) { self.path = PathStorage::new(); }

    pub fn move_to(&mut self, x: f64, y: f64) { self.path.move_to(x, y); }
    pub fn line_to(&mut self, x: f64, y: f64) { self.path.line_to(x, y); }

    pub fn cubic_to(&mut self, cx1: f64, cy1: f64, cx2: f64, cy2: f64, x: f64, y: f64) {
        self.path.curve4(cx1, cy1, cx2, cy2, x, y);
    }

    pub fn quad_to(&mut self, cx: f64, cy: f64, x: f64, y: f64) {
        self.path.curve3(cx, cy, x, y);
    }

    pub fn arc_to(&mut self, cx: f64, cy: f64, r: f64, start_angle: f64, end_angle: f64, ccw: bool) {
        let mut arc = AggArc::new(cx, cy, r, r, start_angle, end_angle, ccw);
        self.path.concat_path(&mut arc, 0);
    }

    /// Full circle at `(cx, cy)` with radius `r`.
    pub fn circle(&mut self, cx: f64, cy: f64, r: f64) {
        self.arc_to(cx, cy, r, 0.0, 2.0 * PI, true);
        self.path.close_polygon(PATH_FLAGS_NONE);
    }

    /// Axis-aligned rectangle — bottom-left `(x, y)`, size `w × h`.
    pub fn rect(&mut self, x: f64, y: f64, w: f64, h: f64) {
        self.path.move_to(x, y);
        self.path.line_to(x + w, y);
        self.path.line_to(x + w, y + h);
        self.path.line_to(x, y + h);
        self.path.close_polygon(PATH_FLAGS_NONE);
    }

    /// Rounded rectangle — bottom-left `(x, y)`, size `w × h`, corner radius `r`.
    pub fn rounded_rect(&mut self, x: f64, y: f64, w: f64, h: f64, r: f64) {
        let r = r.min(w * 0.5).min(h * 0.5).max(0.0);
        let mut rr = RoundedRect::new(x, y, x + w, y + h, r);
        rr.normalize_radius();
        self.path.concat_path(&mut rr, 0);
    }

    pub fn close_path(&mut self) { self.path.close_polygon(PATH_FLAGS_NONE); }

    // -------------------------------------------------------------------------
    // Drawing
    // -------------------------------------------------------------------------

    /// Fill the accumulated path.
    pub fn fill(&mut self) {
        let mut color = self.state.fill_color;
        color.a *= self.state.global_alpha as f32;
        let rgba = color.to_rgba8();
        let mode = self.state.blend_mode;
        let clip = self.state.clip;
        let transform = self.state.transform.clone();
        let fb = active_fb(&mut self.base_fb, &mut self.layer_stack);
        rasterize_fill(fb, &mut self.path, &rgba, mode, clip, &transform);
    }

    /// Stroke the accumulated path.
    pub fn stroke(&mut self) {
        let mut color = self.state.stroke_color;
        color.a *= self.state.global_alpha as f32;
        let rgba = color.to_rgba8();
        let width = self.state.line_width;
        let join = self.state.line_join;
        let cap = self.state.line_cap;
        let mode = self.state.blend_mode;
        let clip = self.state.clip;
        let transform = self.state.transform.clone();
        let fb = active_fb(&mut self.base_fb, &mut self.layer_stack);
        rasterize_stroke(fb, &mut self.path, &rgba, width, join, cap, mode, clip, &transform);
    }

    /// Fill then stroke the accumulated path in one call.
    pub fn fill_and_stroke(&mut self) {
        self.fill();
        self.stroke();
    }

    // -------------------------------------------------------------------------
    // Text
    // -------------------------------------------------------------------------

    /// Draw `text` at position `(x, y)` using the current font and fill color.
    ///
    /// `(x, y)` is the **baseline-left** position in Y-up screen coordinates.
    /// Glyphs extend upward (higher Y) for ascenders and downward (lower Y)
    /// for descenders — correct for Y-up rendering with no Y-flip.
    ///
    /// Requires a font to be set via [`set_font`](Self::set_font). Does nothing
    /// if no font has been set.
    pub fn fill_text(&mut self, text: &str, x: f64, y: f64) {
        let font = match self.state.font.clone() {
            Some(f) => f,
            None => return,
        };
        let font_size = self.state.font_size;

        let mut color = self.state.fill_color;
        color.a *= self.state.global_alpha as f32;

        // LCD subpixel path — gated on this ctx's `lcd_mode` flag,
        // which is set by `paint_subtree_backbuffered` when the widget
        // chose `BackbufferMode::LcdCoverage` and by the main render
        // loop for direct-to-screen text when the global font setting
        // says so.  Mask raster is cached keyed on `(text, font, size)`
        // and colour is applied at composite time.
        //
        // HiDPI: rasterise the mask at the **physical** font size (logical
        // × CTM scale) so the 1:1 texel-to-pixel composite fills the
        // expected number of physical pixels.  Without this the mask
        // renders at logical size and ends up half-size (or stretched by a
        // separate scale call) on 2×/3× displays.
        //
        // **Y-axis baseline alignment**: when the global hinting toggle
        // is ON, both renderers place the baseline on the same integer
        // physical pixel row — see the in-mask `by` snap inside
        // `rasterize_text_lcd_cached` paired with `shape_text`'s own
        // hint-driven `gy` snap.  When hinting is OFF, the RGBA path
        // produces baseline at the exact fractional `y`, while the LCD
        // path's intrinsic composite-rounding (`sy.round()` in
        // `draw_lcd_mask`, required for X-subpixel coherence) lands the
        // baseline at the nearest integer plus the fractional descender
        // — a subpixel residual that's impossible to remove without
        // breaking LCD chroma.  This is a deliberate trade-off matching
        // the user's "snap should be a checkbox, not always on".
        if self.lcd_mode {
            let t = &self.state.transform;
            let ctm_scale = (t.sx * t.sx + t.shy * t.shy).sqrt().max(1e-6);
            let phys_size = font_size * ctm_scale;
            let cached = crate::lcd_coverage::rasterize_text_lcd_cached(
                &font, text, phys_size,
            );
            // `baseline_*_in_mask` is in physical mask pixels; divide by
            // `ctm_scale` so the offset stays in logical units that the
            // CTM then multiplies back to physical at blit time.
            let dst_x = x - cached.baseline_x_in_mask / ctm_scale;
            let dst_y = y - cached.baseline_y_in_mask / ctm_scale;
            <Self as crate::DrawCtx>::draw_lcd_mask_arc(
                self,
                &cached.pixels, cached.width, cached.height,
                color, dst_x, dst_y,
            );
            return;
        }

        let rgba = color.to_rgba8();
        let mode = self.state.blend_mode;
        let clip = self.state.clip;
        let transform = self.state.transform.clone();

        // Shape text and collect per-glyph outline paths.
        let (glyph_paths, _) = shape_text(&font, text, font_size, x, y);
        let fb = active_fb(&mut self.base_fb, &mut self.layer_stack);
        for mut path in glyph_paths {
            rasterize_fill(fb, &mut path, &rgba, mode, clip, &transform);
        }
    }

    /// Measure the advance width and metrics of `text` in the current font.
    ///
    /// Returns `None` if no font has been set.
    pub fn measure_text(&self, text: &str) -> Option<TextMetrics> {
        let font = self.state.font.as_ref()?;
        let size = self.state.font_size;
        Some(TextMetrics {
            width: measure_advance(font, text, size),
            ascent: font.ascender_px(size),
            descent: font.descender_px(size),
            line_height: font.line_height_px(size),
        })
    }

    // -------------------------------------------------------------------------
    // Convenience: built-in stroked vector font (no font file required)
    // -------------------------------------------------------------------------

    /// Draw text using AGG's built-in vector font (no external font needed).
    ///
    /// Useful for labels before a full font is loaded.
    pub fn fill_text_gsv(&mut self, text: &str, x: f64, y: f64, size: f64) {
        let mut color = self.state.fill_color;
        color.a *= self.state.global_alpha as f32;
        let rgba = color.to_rgba8();
        let mode = self.state.blend_mode;
        let clip = self.state.clip;
        let transform = self.state.transform.clone();

        let fb = active_fb(&mut self.base_fb, &mut self.layer_stack);
        let w = fb.width();
        let h = fb.height();
        let stride = (w * 4) as i32;
        let mut ra = RowAccessor::new();
        unsafe { ra.attach(fb.pixels_mut().as_mut_ptr(), w, h, stride) };
        let pf = PixfmtRgba32CompOp::new_with_op(&mut ra, mode);
        let mut rb = RendererBase::new(pf);
        apply_clip(&mut rb, clip);

        let mut ras = RasterizerScanlineAa::new();
        let mut sl = ScanlineU8::new();

        let mut gsv = GsvText::new();
        gsv.size(size, 0.0);
        gsv.start_point(x, y);
        gsv.text(text);

        let mut stroke = ConvStroke::new(&mut gsv);
        stroke.set_width(size * 0.1);
        let mut transformed = ConvTransform::new(&mut stroke, transform);
        ras.add_path(&mut transformed, 0);
        render_scanlines_aa_solid(&mut ras, &mut sl, &mut rb, &rgba);
    }
}

// ---------------------------------------------------------------------------
// Active-framebuffer helper
// ---------------------------------------------------------------------------

/// Return a `&mut Framebuffer` for the currently active render target.
///
/// If any layers are on the stack, returns the top layer's framebuffer.
/// Otherwise returns the base framebuffer.  Accepts the two fields as
/// separate `&mut` references so callers can simultaneously borrow other
/// `GfxCtx` fields (e.g. `state`, `path`) without triggering borrow
/// conflicts on `self`.
#[inline]
fn active_fb<'a>(
    base_fb:     &'a mut Framebuffer,
    layer_stack: &'a mut Vec<LayerEntry>,
) -> &'a mut Framebuffer {
    if let Some(top) = layer_stack.last_mut() {
        &mut top.fb
    } else {
        base_fb
    }
}


// ---------------------------------------------------------------------------
// SrcOver layer compositing
// ---------------------------------------------------------------------------

/// Composite `src` onto `dst` using SrcOver alpha blending.
///
/// AGG writes **premultiplied** RGBA into framebuffers.  The premultiplied
/// SrcOver formula is:
///
/// ```text
/// out_channel = src_premul + dst_premul × (1 − src_alpha_norm)
/// ```
///
/// This applies identically to all four channels (R, G, B, A), which makes
/// the implementation straightforward and avoids the division step needed for
/// straight-alpha compositing.
///
/// `dest_x` / `dest_y` are the Y-up pixel coordinates in `dst` where the
/// bottom-left corner of `src` lands.  Out-of-bounds pixels are silently clipped.
fn composite_framebuffers(dst: &mut Framebuffer, src: &Framebuffer, dest_x: i32, dest_y: i32) {
    let src_w = src.width() as i32;
    let src_h = src.height() as i32;
    let dst_w = dst.width() as i32;
    let dst_h = dst.height() as i32;

    let src_px = src.pixels();
    let dst_px = dst.pixels_mut();

    for sy in 0..src_h {
        let dy = dest_y + sy;
        if dy < 0 || dy >= dst_h { continue; }
        for sx in 0..src_w {
            let dx = dest_x + sx;
            if dx < 0 || dx >= dst_w { continue; }
            let si = ((sy * src_w + sx) * 4) as usize;
            let di = ((dy * dst_w + dx) * 4) as usize;
            let sa = src_px[si + 3] as f32 / 255.0;
            if sa < 1e-4 { continue; } // fully transparent source — skip
            let inv_sa = 1.0 - sa;
            // Premultiplied SrcOver — same formula for all four channels.
            for k in 0..4 {
                let s = src_px[si + k] as f32;
                let d = dst_px[di + k] as f32;
                dst_px[di + k] = (s + d * inv_sa).round().clamp(0.0, 255.0) as u8;
            }
        }
    }
}

// ---------------------------------------------------------------------------
// Free rasterization helpers — take explicit path and fb references so they
// can be called for both self.path draws and per-glyph text draws without
// borrow-checker conflicts.
// ---------------------------------------------------------------------------

pub(crate) fn rasterize_fill(
    fb: &mut Framebuffer,
    path: &mut PathStorage,
    color: &agg_rust::color::Rgba8,
    mode: CompOp,
    clip: Option<(f64, f64, f64, f64)>,
    transform: &TransAffine,
) {
    let w = fb.width();
    let h = fb.height();
    let stride = (w * 4) as i32;
    let mut ra = RowAccessor::new();
    unsafe { ra.attach(fb.pixels_mut().as_mut_ptr(), w, h, stride) };
    let pf = PixfmtRgba32CompOp::new_with_op(&mut ra, mode);
    let mut rb = RendererBase::new(pf);
    apply_clip(&mut rb, clip);

    let mut ras = RasterizerScanlineAa::new();
    let mut sl = ScanlineU8::new();
    let mut curves = ConvCurve::new(path);
    let mut transformed = ConvTransform::new(&mut curves, transform.clone());
    ras.add_path(&mut transformed, 0);
    render_scanlines_aa_solid(&mut ras, &mut sl, &mut rb, color);
}

pub(crate) fn rasterize_stroke(
    fb: &mut Framebuffer,
    path: &mut PathStorage,
    color: &agg_rust::color::Rgba8,
    width: f64,
    join: LineJoin,
    cap: LineCap,
    mode: CompOp,
    clip: Option<(f64, f64, f64, f64)>,
    transform: &TransAffine,
) {
    let w = fb.width();
    let h = fb.height();
    let stride = (w * 4) as i32;
    let mut ra = RowAccessor::new();
    unsafe { ra.attach(fb.pixels_mut().as_mut_ptr(), w, h, stride) };
    let pf = PixfmtRgba32CompOp::new_with_op(&mut ra, mode);
    let mut rb = RendererBase::new(pf);
    apply_clip(&mut rb, clip);

    let mut ras = RasterizerScanlineAa::new();
    let mut sl = ScanlineU8::new();
    let mut curves = ConvCurve::new(path);
    let mut stroke = ConvStroke::new(&mut curves);
    stroke.set_width(width);
    stroke.set_line_join(join);
    stroke.set_line_cap(cap);
    let mut transformed = ConvTransform::new(&mut stroke, transform.clone());
    ras.add_path(&mut transformed, 0);
    render_scanlines_aa_solid(&mut ras, &mut sl, &mut rb, color);
}

// ---------------------------------------------------------------------------
// DrawCtx blanket impl for GfxCtx
// ---------------------------------------------------------------------------

impl crate::draw_ctx::DrawCtx for GfxCtx<'_> {
    fn set_fill_color(&mut self, c: crate::color::Color)     { self.set_fill_color(c) }
    fn set_stroke_color(&mut self, c: crate::color::Color)   { self.set_stroke_color(c) }
    fn set_line_width(&mut self, w: f64)                      { self.set_line_width(w) }
    fn set_line_join(&mut self, j: agg_rust::math_stroke::LineJoin) { self.set_line_join(j) }
    fn set_line_cap(&mut self, c: agg_rust::math_stroke::LineCap)   { self.set_line_cap(c) }
    fn set_blend_mode(&mut self, m: agg_rust::comp_op::CompOp)      { self.set_blend_mode(m) }
    fn set_global_alpha(&mut self, a: f64)                   { self.set_global_alpha(a) }
    fn set_font(&mut self, f: Arc<crate::text::Font>)        { self.set_font(f) }
    fn set_font_size(&mut self, s: f64)                      { self.set_font_size(s) }
    fn clip_rect(&mut self, x: f64, y: f64, w: f64, h: f64) { self.clip_rect(x, y, w, h) }
    fn reset_clip(&mut self)                                  { self.reset_clip() }
    fn clear(&mut self, c: crate::color::Color)              { self.clear(c) }
    fn begin_path(&mut self)                                  { self.begin_path() }
    fn move_to(&mut self, x: f64, y: f64)                    { self.move_to(x, y) }
    fn line_to(&mut self, x: f64, y: f64)                    { self.line_to(x, y) }
    fn cubic_to(&mut self, cx1: f64, cy1: f64, cx2: f64, cy2: f64, x: f64, y: f64) {
        self.cubic_to(cx1, cy1, cx2, cy2, x, y)
    }
    fn quad_to(&mut self, cx: f64, cy: f64, x: f64, y: f64) { self.quad_to(cx, cy, x, y) }
    fn arc_to(&mut self, cx: f64, cy: f64, r: f64, a1: f64, a2: f64, ccw: bool) {
        self.arc_to(cx, cy, r, a1, a2, ccw)
    }
    fn circle(&mut self, cx: f64, cy: f64, r: f64)          { self.circle(cx, cy, r) }
    fn rect(&mut self, x: f64, y: f64, w: f64, h: f64)      { self.rect(x, y, w, h) }
    fn rounded_rect(&mut self, x: f64, y: f64, w: f64, h: f64, r: f64) {
        self.rounded_rect(x, y, w, h, r)
    }
    fn close_path(&mut self)                                  { self.close_path() }
    fn fill(&mut self)                                        { self.fill() }
    fn stroke(&mut self)                                      { self.stroke() }
    fn fill_and_stroke(&mut self)                             { self.fill_and_stroke() }

    fn draw_triangles_aa(
        &mut self,
        vertices: &[[f32; 3]],
        indices:  &[u32],
        color:    crate::color::Color,
    ) {
        // Software fallback: rasterise each triangle as a solid filled
        // polygon.  The per-vertex `alpha` is ignored (software already has
        // analytic AA via the scanline rasteriser), so halo quads from the
        // GPU pipeline end up as redundant thin slivers — visually harmless
        // but inefficient.  Callers that care should check `has_image_blit`
        // / a similar capability flag; for now this keeps parity with the
        // trait so the Lion demo renders correctly on the CPU path too.
        let saved_fill = self.state.fill_color;
        self.set_fill_color(color);
        let n_tris = indices.len() / 3;
        for t in 0..n_tris {
            let i0 = indices[t * 3    ] as usize;
            let i1 = indices[t * 3 + 1] as usize;
            let i2 = indices[t * 3 + 2] as usize;
            if i0 >= vertices.len() || i1 >= vertices.len() || i2 >= vertices.len() { continue; }
            let v0 = vertices[i0];
            let v1 = vertices[i1];
            let v2 = vertices[i2];
            self.begin_path();
            self.move_to(v0[0] as f64, v0[1] as f64);
            self.line_to(v1[0] as f64, v1[1] as f64);
            self.line_to(v2[0] as f64, v2[1] as f64);
            self.close_path();
            self.fill();
        }
        self.set_fill_color(saved_fill);
    }
    fn fill_text(&mut self, t: &str, x: f64, y: f64)        { self.fill_text(t, x, y) }
    fn fill_text_gsv(&mut self, t: &str, x: f64, y: f64, s: f64) { self.fill_text_gsv(t, x, y, s) }
    fn measure_text(&self, t: &str) -> Option<crate::text::TextMetrics> { self.measure_text(t) }
    fn transform(&self) -> agg_rust::trans_affine::TransAffine { self.transform() }
    fn save(&mut self)                                        { self.save() }
    fn restore(&mut self)                                     { self.restore() }
    fn translate(&mut self, tx: f64, ty: f64)                { self.translate(tx, ty) }
    fn rotate(&mut self, r: f64)                             { self.rotate(r) }
    fn scale(&mut self, sx: f64, sy: f64)                    { self.scale(sx, sy) }
    fn set_transform(&mut self, m: agg_rust::trans_affine::TransAffine) { self.set_transform(m) }
    fn reset_transform(&mut self)                             { self.reset_transform() }
    fn push_layer(&mut self, w: f64, h: f64)                 { self.push_layer(w, h) }
    fn pop_layer(&mut self)                                   { self.pop_layer() }

    fn has_image_blit(&self) -> bool { true }

    fn draw_image_rgba_arc(
        &mut self,
        data:  &Arc<Vec<u8>>,
        img_w: u32,
        img_h: u32,
        dst_x: f64,
        dst_y: f64,
        dst_w: f64,
        dst_h: f64,
    ) {
        // Software backend has no GPU texture cache; the CPU composite path
        // is the same as the slice entry point.
        self.draw_image_rgba(data.as_slice(), img_w, img_h, dst_x, dst_y, dst_w, dst_h);
    }

    fn draw_lcd_backbuffer_arc(
        &mut self,
        color: &Arc<Vec<u8>>,
        alpha: &Arc<Vec<u8>>,
        w: u32,
        h: u32,
        dst_x: f64,
        dst_y: f64,
        _dst_w: f64,
        _dst_h: f64,
    ) {
        // Per-channel premultiplied src-over directly onto the active
        // framebuffer.  Preserves LCD chroma: each subpixel's alpha
        // drives the src-over of that subpixel's colour into the
        // destination independently of the other two.
        //
        // Inputs are **top-row-first** (matches the cache layout); the
        // destination `Framebuffer` is Y-up with row 0 at the bottom, so
        // src row `sy` maps to dst row `origin_y + (h-1-sy)`.
        if w == 0 || h == 0 { return; }
        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 t = &self.state.transform;
        let sx = (dst_x * t.sx + dst_y * t.shx + t.tx).round() as i32;
        let sy = (dst_x * t.shy + dst_y * t.sy + t.ty).round() as i32;
        let fb = active_fb(&mut self.base_fb, &mut self.layer_stack);
        let fw = fb.width()  as i32;
        let fh = fb.height() as i32;
        let fw_u = fw as usize;
        let pixels = fb.pixels_mut();

        for src_y in 0..h_u {
            // Top-row-first src → Y-up dst: src row 0 (visually top)
            // lands at dst_y + h - 1 (the visually-top dst row).
            let dy = sy + (h_u - 1 - src_y) as i32;
            if dy < 0 || dy >= fh { continue; }
            let dy_u = dy as usize;
            for src_x in 0..w_u {
                let dx = sx + src_x as i32;
                if dx < 0 || dx >= fw { continue; }
                let ci = (src_y * w_u + src_x) * 3;

                let sa_r = alpha[ci]     as f32 / 255.0;
                let sa_g = alpha[ci + 1] as f32 / 255.0;
                let sa_b = alpha[ci + 2] as f32 / 255.0;
                if sa_r == 0.0 && sa_g == 0.0 && sa_b == 0.0 { continue; }

                let sc_r = color[ci]     as f32 / 255.0;
                let sc_g = color[ci + 1] as f32 / 255.0;
                let sc_b = color[ci + 2] as f32 / 255.0;

                let di = (dy_u * fw_u + dx as usize) * 4;
                // Framebuffer holds premultiplied RGBA.  Per-channel
                // src-over is `dst = src + dst * (1 - src_a)` since src
                // is already premultiplied.  Alpha composites via
                // max-channel-alpha so the destination picks up full
                // opacity wherever any subpixel was painted — matches
                // "this pixel was drawn on" for subsequent SrcOver blits.
                let dc_r = pixels[di]     as f32 / 255.0;
                let dc_g = pixels[di + 1] as f32 / 255.0;
                let dc_b = pixels[di + 2] as f32 / 255.0;
                let da   = pixels[di + 3] as f32 / 255.0;

                let rc_r = sc_r + dc_r * (1.0 - sa_r);
                let rc_g = sc_g + dc_g * (1.0 - sa_g);
                let rc_b = sc_b + dc_b * (1.0 - sa_b);
                let src_a_max = sa_r.max(sa_g).max(sa_b);
                let ra = src_a_max + da * (1.0 - src_a_max);

                pixels[di]     = (rc_r * 255.0 + 0.5).clamp(0.0, 255.0) as u8;
                pixels[di + 1] = (rc_g * 255.0 + 0.5).clamp(0.0, 255.0) as u8;
                pixels[di + 2] = (rc_b * 255.0 + 0.5).clamp(0.0, 255.0) as u8;
                pixels[di + 3] = (ra   * 255.0 + 0.5).clamp(0.0, 255.0) as u8;
            }
        }
    }

    fn has_lcd_mask_composite(&self) -> bool { true }

    fn draw_lcd_mask(
        &mut self,
        mask:      &[u8],
        mask_w:    u32,
        mask_h:    u32,
        src_color: Color,
        dst_x:     f64,
        dst_y:     f64,
    ) {
        // Resolve to the active target (base fb or topmost layer) with
        // the current CTM applied to the placement origin.  Both the
        // mask and the Framebuffer are Y-up (row 0 = bottom), so mask
        // row `my` maps directly to dst row `sy + my`.
        if mask.len() < (mask_w as usize) * (mask_h as usize) * 3 { return; }
        let t = &self.state.transform;
        let sx = dst_x * t.sx + dst_y * t.shx + t.tx;
        let sy = dst_x * t.shy + dst_y * t.sy + t.ty;
        let fb = active_fb(&mut self.base_fb, &mut self.layer_stack);
        let fw = fb.width();
        let fh = fb.height();
        let origin_x = sx.round() as i32;
        let origin_y = sy.round() as i32;

        let sa = src_color.a.clamp(0.0, 1.0);
        let sr = src_color.r.clamp(0.0, 1.0);
        let sg = src_color.g.clamp(0.0, 1.0);
        let sb = src_color.b.clamp(0.0, 1.0);
        let fw_i = fw as i32;
        let fh_i = fh as i32;
        let mw_i = mask_w as i32;
        let mh_i = mask_h as i32;
        let pixels = fb.pixels_mut();

        for my in 0..mh_i {
            // Mask row `my` (Y-up: 0 = bottom) → dst row `origin_y + my`
            // in the Y-up framebuffer.  No flip.
            let dy = origin_y + my;
            if dy < 0 || dy >= fh_i { continue; }
            for mx in 0..mw_i {
                let dx = origin_x + mx;
                if dx < 0 || dx >= fw_i { continue; }
                let mi = ((my * mw_i + mx) * 3) as usize;
                // Per-channel coverage × src alpha — partial-alpha src
                // (e.g. `text_dim` placeholder colour) fades proportionally.
                let cr = (mask[mi]     as f32 / 255.0) * sa;
                let cg = (mask[mi + 1] as f32 / 255.0) * sa;
                let cb = (mask[mi + 2] as f32 / 255.0) * sa;
                if cr == 0.0 && cg == 0.0 && cb == 0.0 { continue; }
                let di = ((dy * fw_i + dx) * 4) as usize;
                let dr = pixels[di]     as f32 / 255.0;
                let dg = pixels[di + 1] as f32 / 255.0;
                let db = pixels[di + 2] as f32 / 255.0;
                let rr  = sr * cr + dr * (1.0 - cr);
                let rg  = sg * cg + dg * (1.0 - cg);
                let rbb = sb * cb + db * (1.0 - cb);
                pixels[di]     = (rr  * 255.0 + 0.5).clamp(0.0, 255.0) as u8;
                pixels[di + 1] = (rg  * 255.0 + 0.5).clamp(0.0, 255.0) as u8;
                pixels[di + 2] = (rbb * 255.0 + 0.5).clamp(0.0, 255.0) as u8;
                // Alpha unchanged — we're writing onto an existing opaque
                // (or semi-transparent) surface without introducing new
                // transparency.
            }
        }
    }

    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,
    ) {
        // Scale the source image into a temporary Framebuffer at dst size,
        // then composite it onto the current render target using the CTM origin.
        if img_w == 0 || img_h == 0 || dst_w < 1.0 || dst_h < 1.0 { return; }

        let out_w = dst_w.round() as u32;
        let out_h = dst_h.round() as u32;
        let mut scaled = crate::framebuffer::Framebuffer::new(out_w, out_h);

        // Nearest-neighbour scale — sufficient for README screenshots / badges.
        // `data` is straight-alpha by the `draw_image_rgba` convention; AGG
        // framebuffers store **premultiplied** RGBA, so we premultiply each
        // sampled pixel on the way in so `composite_framebuffers` (which uses
        // premultiplied SrcOver) blends with correct intensity.
        let px = scaled.pixels_mut();
        for dy in 0..out_h {
            for dx in 0..out_w {
                let sx = (dx as f64 / out_w as f64 * img_w as f64) as u32;
                // Image is top-row-first; Y-up dst means we flip sy.
                let sy_img = ((1.0 - (dy as f64 + 0.5) / out_h as f64) * img_h as f64)
                    .floor()
                    .clamp(0.0, (img_h - 1) as f64) as u32;
                let si = ((sy_img * img_w + sx) * 4) as usize;
                let di = ((dy * out_w + dx) * 4) as usize;
                if si + 3 < data.len() && di + 3 < px.len() {
                    let a = data[si + 3] as u32;
                    if a == 255 {
                        px[di]     = data[si];
                        px[di + 1] = data[si + 1];
                        px[di + 2] = data[si + 2];
                        px[di + 3] = 255;
                    } else {
                        // Premultiply: (c * a + 127) / 255 (round-half-up).
                        px[di]     = (((data[si]     as u32) * a + 127) / 255) as u8;
                        px[di + 1] = (((data[si + 1] as u32) * a + 127) / 255) as u8;
                        px[di + 2] = (((data[si + 2] as u32) * a + 127) / 255) as u8;
                        px[di + 3] = a as u8;
                    }
                }
            }
        }

        // Apply CTM translation to get screen-space origin.
        let (tx, ty) = { let t = self.transform(); (t.tx, t.ty) };
        let screen_x = (tx + dst_x).round() as i32;
        let screen_y = (ty + dst_y).round() as i32;
        let fb = active_fb(&mut self.base_fb, &mut self.layer_stack);
        composite_framebuffers(fb, &scaled, screen_x, screen_y);
    }
}

/// Apply a Y-up scissor clip to a `RendererBase` (pixel-inclusive coordinates).
pub(crate) fn apply_clip<PF: agg_rust::pixfmt_rgba::PixelFormat>(
    rb: &mut RendererBase<PF>,
    clip: Option<(f64, f64, f64, f64)>,
) {
    if let Some((x, y, w, h)) = clip {
        let x1 = x.floor() as i32;
        let y1 = y.floor() as i32;
        let x2 = (x + w).ceil() as i32 - 1;
        let y2 = (y + h).ceil() as i32 - 1;
        rb.clip_box_i(x1, y1, x2, y2);
    }
}