uzor-render-vello-cpu 1.5.1

CPU-only rendering backend using vello_cpu
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
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
//! `VelloCpuRenderContext` — CPU-only `RenderContext` implementation.
//!
//! Uses `vello_cpu::RenderContext` for all rasterization. Zero GPU dependency.
//!
//! ## Type-system note
//!
//! `vello_cpu` 0.0.6 re-exports `kurbo` (0.13), `peniko` (0.6), and `color`
//! (0.3) from `vello_common 0.0.6`.  These differ from the `vello 0.6` versions
//! used by the GPU backend (`uzor-render-vello-gpu`), so this crate does NOT
//! depend on `uzor-backend-vello-common` and implements all state management
//! inline to avoid cross-version type conflicts.

use std::collections::HashMap;
use std::sync::{Arc, OnceLock};

use vello_cpu::kurbo::{self, Affine, BezPath, Cap, Join, Rect, Shape, Stroke};
use vello_cpu::peniko::{
    Blob, ColorStop, ColorStops, Extend, Fill, FontData, Gradient, LinearGradientPosition, Mix,
    Compose,
};
use vello_cpu::{
    Glyph, Image, ImageSource, Pixmap as VelloCpuPixmap, RenderContext as VelloCpuCtx, RenderMode,
    RenderSettings, Resources,
};

use skrifa::{
    MetadataProvider,
    raw::{FileRef, FontRef},
};

use uzor::fonts;
use uzor::core::types::Rect as UzorRect;
use uzor::render::{
    BatchPainter, BlendMode as UzorBlendMode, CircleBatch,
    Effects, GradientPainter, LineSegment, Masking, Painter,
    OffscreenTarget, OffscreenTargetDesc, OffscreenTargetId,
    RenderContext as UzorRenderContext, RenderContextExt, ShapeHelpers,
    TextBounds, TextMetrics, TextRenderer, TextAlign, TextBaseline,
};

// ---------------------------------------------------------------------------
// Cached vello_cpu FontData (one per process)
// ---------------------------------------------------------------------------

static FONT_REGULAR:     OnceLock<FontData> = OnceLock::new();
static FONT_BOLD:        OnceLock<FontData> = OnceLock::new();
static FONT_ITALIC:      OnceLock<FontData> = OnceLock::new();
static FONT_BOLD_ITALIC: OnceLock<FontData> = OnceLock::new();

static FONT_PT_ROOT_UI:       OnceLock<FontData> = OnceLock::new();
static FONT_JB_MONO_REGULAR:  OnceLock<FontData> = OnceLock::new();
static FONT_JB_MONO_BOLD:     OnceLock<FontData> = OnceLock::new();

static FONT_FALLBACK_NERD_FONT:    OnceLock<FontData> = OnceLock::new();
static FONT_FALLBACK_SYMBOLS2:     OnceLock<FontData> = OnceLock::new();
static FONT_FALLBACK_COLOR_EMOJI:  OnceLock<FontData> = OnceLock::new();
static FONT_FALLBACK_EMOJI:        OnceLock<FontData> = OnceLock::new();
static FONT_FALLBACK_CJK_SC:       OnceLock<FontData> = OnceLock::new();
static FONT_FALLBACK_ARABIC:       OnceLock<FontData> = OnceLock::new();
static FONT_FALLBACK_DEVANAGARI:   OnceLock<FontData> = OnceLock::new();

use uzor::fonts::FontFamily;

fn get_font(family: FontFamily, bold: bool, italic: bool) -> &'static FontData {
    match family {
        FontFamily::PtRootUi => FONT_PT_ROOT_UI
            .get_or_init(|| make_font(fonts::font_bytes(family, bold, italic))),
        FontFamily::JetBrainsMono => {
            let _ = italic; // no italic variant bundled
            if bold {
                FONT_JB_MONO_BOLD
                    .get_or_init(|| make_font(fonts::font_bytes(family, true, false)))
            } else {
                FONT_JB_MONO_REGULAR
                    .get_or_init(|| make_font(fonts::font_bytes(family, false, false)))
            }
        }
        FontFamily::Roboto => match (bold, italic) {
            (true,  true ) => FONT_BOLD_ITALIC
                .get_or_init(|| make_font(fonts::font_bytes(family, true, true))),
            (true,  false) => FONT_BOLD
                .get_or_init(|| make_font(fonts::font_bytes(family, true, false))),
            (false, true ) => FONT_ITALIC
                .get_or_init(|| make_font(fonts::font_bytes(family, false, true))),
            (false, false) => FONT_REGULAR
                .get_or_init(|| make_font(fonts::font_bytes(family, false, false))),
        },
    }
}

fn get_fallback_fonts() -> &'static [FontData] {
    static FALLBACK_LIST: OnceLock<Vec<FontData>> = OnceLock::new();
    FALLBACK_LIST.get_or_init(|| {
        let nf   = FONT_FALLBACK_NERD_FONT.get_or_init(|| make_font(fonts::SYMBOLS_NERD_FONT_MONO));
        let s2   = FONT_FALLBACK_SYMBOLS2.get_or_init(|| make_font(fonts::NOTO_SANS_SYMBOLS2));
        let cjk  = FONT_FALLBACK_CJK_SC.get_or_init(|| make_font(fonts::NOTO_SANS_CJK_SC));
        let ar   = FONT_FALLBACK_ARABIC.get_or_init(|| make_font(fonts::NOTO_SANS_ARABIC));
        let deva = FONT_FALLBACK_DEVANAGARI.get_or_init(|| make_font(fonts::NOTO_SANS_DEVANAGARI));
        let cv   = FONT_FALLBACK_COLOR_EMOJI.get_or_init(|| make_font(fonts::NOTO_COLOR_EMOJI));
        let em   = FONT_FALLBACK_EMOJI.get_or_init(|| make_font(fonts::NOTO_EMOJI));
        // Order: [0]=NerdFont, [1]=Symbols2, [2]=CjkSc, [3]=Arabic, [4]=Devanagari,
        //        [5]=NotoColorEmoji, [6]=NotoEmoji
        // Text script fonts (CJK/Arabic/Devanagari) placed BEFORE emoji so ordinary
        // script codepoints resolve to text outlines rather than emoji glyphs.
        vec![
            nf.clone(), s2.clone(), cjk.clone(), ar.clone(), deva.clone(),
            cv.clone(), em.clone(),
        ]
    })
}

fn make_font(bytes: &'static [u8]) -> FontData {
    FontData::new(Blob::new(Arc::new(bytes) as Arc<dyn AsRef<[u8]> + Send + Sync>), 0)
}

fn to_font_ref(font: &FontData) -> Option<FontRef<'_>> {
    let file_ref = FileRef::new(font.data.as_ref()).ok()?;
    match file_ref {
        FileRef::Font(f)   => Some(f),
        FileRef::Collection(col) => col.get(font.index).ok(),
    }
}

// ---------------------------------------------------------------------------
// Resolved glyph with fallback font tracking
// ---------------------------------------------------------------------------

struct ResolvedGlyph {
    /// None = primary font; Some(i) = fallback index i.
    font_index: Option<usize>,
    glyph_id: u32,
    x: f32,
    advance: f32,
}

fn resolve_glyphs_with_fallback(
    text: &str,
    primary_ref: &FontRef<'_>,
    font_size: f32,
) -> Vec<ResolvedGlyph> {
    let size = skrifa::instance::Size::new(font_size);
    let var_loc = skrifa::instance::LocationRef::default();
    let primary_charmap = primary_ref.charmap();
    let primary_metrics = primary_ref.glyph_metrics(size, var_loc);
    let fallbacks = get_fallback_fonts();

    let mut pen_x = 0.0f32;
    let mut result = Vec::with_capacity(text.len());

    for ch in text.chars() {
        let primary_gid = primary_charmap.map(ch).unwrap_or_default();
        if primary_gid != skrifa::GlyphId::new(0) {
            let adv = primary_metrics.advance_width(primary_gid).unwrap_or_default();
            result.push(ResolvedGlyph {
                font_index: None,
                glyph_id: primary_gid.to_u32(),
                x: pen_x,
                advance: adv,
            });
            pen_x += adv;
        } else {
            let mut found_index = None;
            let mut found_gid = primary_gid;
            let mut found_adv = primary_metrics.advance_width(primary_gid).unwrap_or_default();

            for (idx, fb_font) in fallbacks.iter().enumerate() {
                if let Some(fb_ref) = to_font_ref(fb_font) {
                    let fb_gid = fb_ref.charmap().map(ch).unwrap_or_default();
                    if fb_gid != skrifa::GlyphId::new(0) {
                        let fb_metrics = fb_ref.glyph_metrics(size, var_loc);
                        found_adv = fb_metrics.advance_width(fb_gid).unwrap_or_default();
                        found_gid = fb_gid;
                        found_index = Some(idx);
                        break;
                    }
                }
            }

            result.push(ResolvedGlyph {
                font_index: found_index,
                glyph_id: found_gid.to_u32(),
                x: pen_x,
                advance: found_adv,
            });
            pen_x += found_adv;
        }
    }

    result
}

fn resolved_total_width(glyphs: &[ResolvedGlyph]) -> f32 {
    glyphs.last().map_or(0.0, |g| g.x + g.advance)
}

// ---------------------------------------------------------------------------
// Color parsing (CSS → vello_cpu / peniko color)
// ---------------------------------------------------------------------------

/// vello_cpu color type (premul-capable, sRGB)
type Color = vello_cpu::color::AlphaColor<vello_cpu::color::Srgb>;

fn parse_color(s: &str) -> Color {
    let (r, g, b, a) = uzor::render::parse_color(s);
    Color::from_rgba8(r, g, b, a)
}

// ---------------------------------------------------------------------------
// CSS font parsing
// ---------------------------------------------------------------------------

#[derive(Clone, Debug)]
struct FontInfo {
    size:   f64,
    bold:   bool,
    italic: bool,
    family: FontFamily,
}

impl Default for FontInfo {
    fn default() -> Self {
        Self { size: 12.0, bold: false, italic: false, family: FontFamily::Roboto }
    }
}

fn parse_css_font(font_str: &str) -> FontInfo {
    let parsed = fonts::parse_css_font(font_str);
    FontInfo {
        size:   parsed.size as f64,
        bold:   parsed.bold,
        italic: parsed.italic,
        family: parsed.family,
    }
}

/// Re-compose a CSS font shorthand string from an already-parsed
/// [`FontInfo`] — the inverse of [`parse_css_font`], needed because
/// [`uzor::shaper::measure_glyphs`] takes a CSS string, not a `FontInfo`.
/// Mirrors `uzor-render-tiny-skia`'s own identically-shaped
/// `font_css_string` helper (same 3 bundled families, same shorthand
/// grammar).
fn font_css_string(info: &FontInfo) -> String {
    let family = match info.family {
        FontFamily::Roboto        => "Roboto",
        FontFamily::PtRootUi      => "PT Root UI",
        FontFamily::JetBrainsMono => "JetBrains Mono",
    };
    let mut parts: Vec<String> = Vec::with_capacity(4);
    if info.italic { parts.push("italic".into()); }
    if info.bold   { parts.push("bold".into()); }
    parts.push(format!("{}px", info.size));
    parts.push(family.into());
    parts.join(" ")
}

// ---------------------------------------------------------------------------
// Text metrics via skrifa — rasterization-only escape hatch
// ---------------------------------------------------------------------------

/// Sum of skrifa's own raw glyph `advance_width` — the un-kerned advance
/// this backend's own [`fill_text`](TextRenderer::fill_text) pen walk
/// still uses to place each rasterized glyph. **No longer** the width
/// [`TextMetrics::measure_text`]/[`TextMetrics::text_bounds`] report —
/// both now delegate to [`uzor::shaper`] (real GPOS kerning via
/// cosmic-text), the SAME canonical source every other shaper-backed
/// backend in this workspace measures through, so a layout decision
/// never disagrees by backend. Kept as the internal rasterization pen-
/// advance implementation detail only.
fn measure_text_width(text: &str, font_info: &FontInfo) -> f64 {
    let font = get_font(font_info.family, font_info.bold, font_info.italic);
    let Some(font_ref) = to_font_ref(font) else {
        return text.len() as f64 * font_info.size * 0.6;
    };
    let glyphs = resolve_glyphs_with_fallback(text, &font_ref, font_info.size as f32);
    resolved_total_width(&glyphs) as f64
}

// ---------------------------------------------------------------------------
// Shadow state (M6-P1)
// ---------------------------------------------------------------------------

/// Active drop shadow for vello-cpu.  Approximated as an offset, alpha copy.
#[derive(Clone)]
struct ShadowState {
    dx:    f64,
    dy:    f64,
    color: Color,
}

// ---------------------------------------------------------------------------
// Save/restore state
// ---------------------------------------------------------------------------

#[derive(Clone)]
struct SavedState {
    transform:    Affine,
    stroke_color: Color,
    stroke_width: f64,
    fill_color:   Color,
    line_cap:     Cap,
    line_join:    Join,
    /// Current dash pattern (Canvas2D's `setLineDash`) — `None` is a
    /// plain solid stroke. Local/user-space lengths; `kurbo::Stroke`'s
    /// own `dash_pattern`/`dash_offset` are applied by
    /// `vello_common::flatten::expand_stroke` in the PATH's own
    /// coordinate space, before `vello_cpu`'s `set_transform` affine is
    /// applied to the resulting outline — so the active CTM scales the
    /// dash pattern the same way it scales stroke width and path
    /// geometry, matching `tiny-skia`'s own dashing order.
    line_dash:    Option<Vec<f64>>,
    global_alpha: f64,
    font_info:    FontInfo,
    text_align:   TextAlign,
    text_baseline: TextBaseline,
    /// Whether `clip()` was called at this save level (so we pop it on restore).
    has_clip:     bool,
    /// Blend mode at this save level.
    blend_mode:   UzorBlendMode,
}

// ---------------------------------------------------------------------------
// VelloCpuRenderContext
// ---------------------------------------------------------------------------

/// CPU-only rendering context backed by `vello_cpu`.
///
/// Uses the sparse-strips rasterization algorithm with optional SIMD
/// acceleration.  No GPU context, no wgpu dependency.
///
/// ## Frame lifecycle
///
/// ```rust,ignore
/// let mut ctx = VelloCpuRenderContext::new(1.0); // dpr
/// ctx.begin_frame(800, 600);
/// ctx.set_fill_color("#1e1e1e");
/// ctx.fill_rect(0.0, 0.0, 800.0, 600.0);
/// ctx.render_to_pixmap_rgba8(&mut rgba8_buffer, 800, 600);
/// ```
pub struct VelloCpuRenderContext {
    // vello_cpu renderer — re-created on size change, reset each frame
    render_ctx:   Option<VelloCpuCtx>,
    // vello_cpu 0.0.9 split per-render resources (image-registry + glyph caches)
    // out of the context so the rasteriser can own them across frames.
    resources:    vello_cpu::Resources,
    width:        u32,
    height:       u32,
    dpr:          f64,

    // Drawing state
    transform:    Affine,
    stroke_color: Color,
    stroke_width: f64,
    fill_color:   Color,
    line_cap:     Cap,
    line_join:    Join,
    /// See `SavedState::line_dash`'s own doc comment.
    line_dash:    Option<Vec<f64>>,
    global_alpha: f64,
    font_info:    FontInfo,
    text_align:   TextAlign,
    text_baseline: TextBaseline,

    // Current Canvas2D-style path
    path:         Option<BezPath>,

    // Whether a clip path is active at the current innermost save level
    clip_active:  bool,

    // Save/restore stack
    state_stack:  Vec<SavedState>,

    // M6-P1: Drop shadow (approximated as offset copy, blur not native)
    shadow:       Option<ShadowState>,
    // M6-P3: Blend mode
    blend_mode:   UzorBlendMode,

    // Offscreen render-target cache — rendered RGBA8 content, keyed by
    // handle. See `uzor::render::offscreen` for the trait contract.
    offscreen_targets: HashMap<OffscreenTargetId, CachedTarget>,
    // Monotonic counter for allocating new `OffscreenTargetId`s.
    next_offscreen_id: u64,
    // Stack of saved recording state, swapped out by
    // `push_offscreen_target`; `pop_offscreen_target` restores the top
    // entry and stores the rendered content under the target's id.
    offscreen_stack: Vec<SavedRecording>,
}

/// Recording state swapped out while painting into an offscreen target.
struct SavedRecording {
    id:          OffscreenTargetId,
    render_ctx:  Option<VelloCpuCtx>,
    resources:   Resources,
    width:       u32,
    height:      u32,
    // Outer per-frame drawing state — the recording paints at its own
    // local origin with fresh state; the outer walk continues afterwards
    // with ITS state intact (without the restore, one mid-walk recording
    // clobbers the caller's translate/clip/save stack for the rest of
    // the frame).
    transform:   Affine,
    clip_active: bool,
    state_stack: Vec<SavedState>,
    path:        Option<BezPath>,
}

/// Rendered offscreen target content — premultiplied RGBA8 pixels.
struct CachedTarget {
    pixels: Vec<u8>,
    width:  u32,
    height: u32,
}

impl VelloCpuRenderContext {
    /// Create a new context.
    ///
    /// The underlying `vello_cpu::RenderContext` is lazily allocated on the
    /// first call to [`begin_frame`](Self::begin_frame).
    ///
    /// `dpr` — device pixel ratio.
    pub fn new(dpr: f64) -> Self {
        Self {
            render_ctx:   None,
            resources:    vello_cpu::Resources::new(),
            width:        0,
            height:       0,
            dpr,
            transform:    Affine::IDENTITY,
            stroke_color: Color::from_rgba8(255, 255, 255, 255),
            stroke_width: 1.0,
            fill_color:   Color::from_rgba8(0, 0, 0, 0),
            line_cap:     Cap::Butt,
            line_join:    Join::Miter,
            line_dash:    None,
            global_alpha: 1.0,
            font_info:    FontInfo::default(),
            text_align:   TextAlign::Left,
            text_baseline: TextBaseline::Middle,
            path:         None,
            clip_active:  false,
            state_stack:  Vec::new(),
            shadow:       None,
            blend_mode:   UzorBlendMode::Normal,
            offscreen_targets: HashMap::new(),
            next_offscreen_id: 0,
            offscreen_stack:   Vec::new(),
        }
    }

    /// Begin a new frame.
    ///
    /// Re-creates the `vello_cpu::RenderContext` only when `width` or `height`
    /// changes; otherwise calls `reset()` to clear draw commands without
    /// reallocating internal strip buffers.
    ///
    /// Also resets per-frame drawing state (transform, clip, save stack).
    pub fn begin_frame(&mut self, width: u32, height: u32) {
        let w16 = width.min(u16::MAX as u32) as u16;
        let h16 = height.min(u16::MAX as u32) as u16;

        let needs_new = self.render_ctx.is_none()
            || self.width  != width
            || self.height != height;

        if needs_new {
            let settings = RenderSettings {
                level:       vello_cpu::Level::new(),
                num_threads: 0,
                render_mode: RenderMode::OptimizeSpeed,
            };
            self.render_ctx = Some(VelloCpuCtx::new_with(w16, h16, settings));
            self.width  = width;
            self.height = height;
        } else if let Some(ref mut ctx) = self.render_ctx {
            ctx.reset();
        }

        // Reset per-frame state
        self.transform   = Affine::IDENTITY;
        self.clip_active = false;
        self.state_stack.clear();
        self.path        = None;
    }

    /// Render the completed frame into a premultiplied RGBA8 pixel buffer.
    ///
    /// `buffer` must have exactly `width * height * 4` bytes.
    /// The pixel format is `[R, G, B, A]` premultiplied — suitable for most
    /// image APIs and for manual conversion to softbuffer's `0x00RRGGBB` u32.
    ///
    /// Calls `flush()` internally (required when the `multithreading` feature
    /// is active), then rasterizes.
    pub fn render_to_pixmap_rgba8(&mut self, buffer: &mut [u8], width: u16, height: u16) {
        if let Some(ref mut ctx) = self.render_ctx {
            ctx.flush();
            // vello_cpu 0.0.9: render_to_buffer now takes &mut Resources first.
            ctx.render_to_buffer(&mut self.resources, buffer, width, height, RenderMode::OptimizeSpeed);
        }
    }

    /// Render directly into a softbuffer-compatible `u32` buffer.
    ///
    /// Renders to a temporary RGBA8 buffer and converts to `0x00RRGGBB`
    /// format expected by `softbuffer`.
    ///
    /// `out` must have at least `width * height` elements.
    pub fn render_to_softbuffer(&mut self, out: &mut [u32]) {
        let w = self.width as u16;
        let h = self.height as u16;
        let pixel_count = self.width as usize * self.height as usize;
        if out.len() < pixel_count {
            return;
        }
        let mut rgba8 = vec![0u8; pixel_count * 4];
        self.render_to_pixmap_rgba8(&mut rgba8, w, h);
        // Convert PremulRGBA8 [R,G,B,A] → softbuffer 0x00RRGGBB
        for (src, dst) in rgba8.chunks_exact(4).zip(out.iter_mut()) {
            *dst = ((src[0] as u32) << 16)
                 | ((src[1] as u32) <<  8)
                 |  (src[2] as u32);
        }
    }

    // ------------------------------------------------------------------
    // Internal helpers
    // ------------------------------------------------------------------

    /// Build a `kurbo::Stroke` from the current stroke state.
    fn current_stroke(&self) -> Stroke {
        let dash_pattern: kurbo::Dashes = match &self.line_dash {
            Some(pattern) => pattern.iter().copied().collect(),
            None => Default::default(),
        };
        Stroke {
            width:       self.stroke_width,
            join:        self.line_join,
            miter_limit: 4.0,
            start_cap:   self.line_cap,
            end_cap:     self.line_cap,
            dash_pattern,
            dash_offset:  0.0,
        }
    }

    /// Apply fill paint (fill color × global alpha) to the vello_cpu context.
    fn apply_fill_paint(&mut self) {
        let color = self.effective_fill_color();
        let blend = Self::blend_to_vello_cpu(self.blend_mode);
        if let Some(ref mut ctx) = self.render_ctx {
            ctx.set_blend_mode(blend);
            ctx.set_paint(color);
        }
    }

    /// Apply stroke paint (stroke color × global alpha) to the vello_cpu context.
    fn apply_stroke_paint(&mut self) {
        let color = self.effective_stroke_color();
        let blend = Self::blend_to_vello_cpu(self.blend_mode);
        if let Some(ref mut ctx) = self.render_ctx {
            ctx.set_blend_mode(blend);
            ctx.set_paint(color);
        }
    }

    fn effective_fill_color(&self) -> Color {
        if self.global_alpha < 1.0 {
            self.fill_color.with_alpha(self.global_alpha as f32)
        } else {
            self.fill_color
        }
    }

    fn effective_stroke_color(&self) -> Color {
        if self.global_alpha < 1.0 {
            self.stroke_color.with_alpha(self.global_alpha as f32)
        } else {
            self.stroke_color
        }
    }

    fn push_save_state(&mut self, has_clip: bool) {
        self.state_stack.push(SavedState {
            transform:    self.transform,
            stroke_color: self.stroke_color,
            stroke_width: self.stroke_width,
            fill_color:   self.fill_color,
            line_cap:     self.line_cap,
            line_join:    self.line_join,
            line_dash:    self.line_dash.clone(),
            global_alpha: self.global_alpha,
            font_info:    self.font_info.clone(),
            text_align:   self.text_align,
            text_baseline: self.text_baseline,
            has_clip,
            blend_mode:   self.blend_mode,
        });
    }

    fn pop_save_state(&mut self) -> Option<SavedState> {
        let s = self.state_stack.pop()?;
        self.transform    = s.transform;
        self.stroke_color = s.stroke_color;
        self.stroke_width = s.stroke_width;
        self.fill_color   = s.fill_color;
        self.line_cap     = s.line_cap;
        self.line_join    = s.line_join;
        self.line_dash    = s.line_dash.clone();
        self.global_alpha = s.global_alpha;
        self.font_info    = s.font_info.clone();
        self.text_align   = s.text_align;
        self.text_baseline = s.text_baseline;
        self.blend_mode   = s.blend_mode;
        Some(s)
    }

    /// Convert a `UzorBlendMode` to a `vello_cpu::peniko::BlendMode`.
    fn blend_to_vello_cpu(mode: UzorBlendMode) -> vello_cpu::peniko::BlendMode {
        match mode {
            UzorBlendMode::Normal     => Mix::Normal.into(),
            UzorBlendMode::Multiply   => Mix::Multiply.into(),
            UzorBlendMode::Screen     => Mix::Screen.into(),
            UzorBlendMode::Overlay    => Mix::Overlay.into(),
            UzorBlendMode::Darken     => Mix::Darken.into(),
            UzorBlendMode::Lighten    => Mix::Lighten.into(),
            UzorBlendMode::ColorDodge => Mix::ColorDodge.into(),
            UzorBlendMode::ColorBurn  => Mix::ColorBurn.into(),
            UzorBlendMode::HardLight  => Mix::HardLight.into(),
            UzorBlendMode::SoftLight  => Mix::SoftLight.into(),
            UzorBlendMode::Difference => Mix::Difference.into(),
            UzorBlendMode::Exclusion  => Mix::Exclusion.into(),
            UzorBlendMode::Plus       => Compose::Plus.into(),
        }
    }
}

// ---------------------------------------------------------------------------
// Painter
// ---------------------------------------------------------------------------

impl Painter for VelloCpuRenderContext {
    fn save(&mut self) {
        let has_clip = self.clip_active;
        self.push_save_state(has_clip);
        self.clip_active = false;
    }

    fn restore(&mut self) {
        if let Some(saved) = self.pop_save_state() {
            // Pop clip path if one was pushed during this save level
            if self.clip_active {
                if let Some(ref mut ctx) = self.render_ctx {
                    ctx.pop_clip_path();
                }
            }
            self.clip_active = saved.has_clip;
            let transform = self.transform;
            if let Some(ref mut ctx) = self.render_ctx {
                ctx.set_transform(transform);
            }
        }
    }

    // Canvas-style incremental CTM: a later `translate`/`rotate`/`scale`
    // call is expressed in the LOCAL frame the earlier calls already
    // established (`self * Op`, kurbo's `pre_*` family), NOT the outer/
    // world frame (`Op * self`, `then_*`) — see `uzor-render-tiny-skia`'s
    // identically-shaped `Painter::translate`/`rotate`/`scale` (the
    // reference-correct backend) and this crate's own new
    // `translate_then_rotate_matches_local_frame_composition` test below.
    fn translate(&mut self, x: f64, y: f64) {
        self.transform = self.transform.pre_translate((x, y).into());
    }

    fn rotate(&mut self, angle: f64) {
        self.transform = self.transform.pre_rotate(angle);
    }

    fn scale(&mut self, x: f64, y: f64) {
        self.transform = self.transform.pre_scale_non_uniform(x, y);
    }

    fn set_fill_color(&mut self, color: &str) {
        self.fill_color = parse_color(color);
    }

    fn set_global_alpha(&mut self, alpha: f64) {
        self.global_alpha = alpha.clamp(0.0, 1.0);
    }

    fn set_stroke_color(&mut self, color: &str) {
        self.stroke_color = parse_color(color);
    }

    fn set_stroke_width(&mut self, width: f64) {
        self.stroke_width = width;
        let stroke = self.current_stroke();
        if let Some(ref mut ctx) = self.render_ctx {
            ctx.set_stroke(stroke);
        }
    }

    fn set_line_dash(&mut self, pattern: &[f64]) {
        // The old comment here claimed constructing a dashed
        // `kurbo::Stroke` "requires the Stroke builder pattern" as if
        // that were a blocker — checked against the pinned `kurbo`
        // 0.13.1 source: `dash_pattern`/`dash_offset` are PLAIN PUBLIC
        // fields (`kurbo::stroke::Stroke`), already set via a struct
        // literal exactly like every other field `current_stroke`
        // builds below. No builder rework needed, no shared dasher
        // needed either — `vello_common::flatten::stroke` (what
        // `vello_cpu::RenderContext::stroke_path` calls internally)
        // already runs `kurbo::stroke_with`, which expands
        // `dash_pattern`/`dash_offset` into the stroked outline BEFORE
        // `set_transform`'s affine is applied — the same dash-before-
        // transform order `tiny-skia`'s `StrokeDash` uses (see
        // `SavedState::line_dash`'s own doc comment).
        self.line_dash = if pattern.is_empty() { None } else { Some(pattern.to_vec()) };
    }

    fn set_line_cap(&mut self, cap: &str) {
        self.line_cap = match cap {
            "round"  => Cap::Round,
            "square" => Cap::Square,
            _        => Cap::Butt,
        };
        let stroke = self.current_stroke();
        if let Some(ref mut ctx) = self.render_ctx {
            ctx.set_stroke(stroke);
        }
    }

    fn set_line_join(&mut self, join: &str) {
        self.line_join = match join {
            "round" => Join::Round,
            "bevel" => Join::Bevel,
            _       => Join::Miter,
        };
        let stroke = self.current_stroke();
        if let Some(ref mut ctx) = self.render_ctx {
            ctx.set_stroke(stroke);
        }
    }

    fn begin_path(&mut self) {
        self.path = Some(BezPath::new());
    }

    fn move_to(&mut self, x: f64, y: f64) {
        if let Some(ref mut p) = self.path {
            p.move_to(kurbo::Point::new(x, y));
        }
    }

    fn line_to(&mut self, x: f64, y: f64) {
        if let Some(ref mut p) = self.path {
            p.line_to(kurbo::Point::new(x, y));
        }
    }

    fn close_path(&mut self) {
        if let Some(ref mut p) = self.path {
            p.close_path();
        }
    }

    fn rect(&mut self, x: f64, y: f64, w: f64, h: f64) {
        if let Some(ref mut p) = self.path {
            p.move_to(kurbo::Point::new(x, y));
            p.line_to(kurbo::Point::new(x + w, y));
            p.line_to(kurbo::Point::new(x + w, y + h));
            p.line_to(kurbo::Point::new(x, y + h));
            p.close_path();
        }
    }

    fn arc(&mut self, cx: f64, cy: f64, radius: f64, start_angle: f64, end_angle: f64) {
        if let Some(ref mut p) = self.path {
            let arc = kurbo::Arc::new(
                kurbo::Point::new(cx, cy),
                kurbo::Vec2::new(radius, radius),
                start_angle,
                end_angle - start_angle,
                0.0,
            );
            let path_has_elements = !p.elements().is_empty();
            let mut is_first = true;
            arc.to_path(0.1).into_iter().for_each(|el| match el {
                kurbo::PathEl::MoveTo(pt) => {
                    if is_first && path_has_elements {
                        p.line_to(pt);
                    } else {
                        p.move_to(pt);
                    }
                    is_first = false;
                }
                kurbo::PathEl::LineTo(pt) => { p.line_to(pt); is_first = false; }
                kurbo::PathEl::QuadTo(c, pt) => { p.quad_to(c, pt); is_first = false; }
                kurbo::PathEl::CurveTo(c1, c2, pt) => {
                    p.curve_to(c1, c2, pt);
                    is_first = false;
                }
                kurbo::PathEl::ClosePath => p.close_path(),
            });
        }
    }

    fn ellipse(
        &mut self,
        cx: f64,
        cy: f64,
        rx: f64,
        ry: f64,
        _rotation: f64,
        start: f64,
        end: f64,
    ) {
        if let Some(ref mut p) = self.path {
            let arc = kurbo::Arc::new(
                kurbo::Point::new(cx, cy),
                kurbo::Vec2::new(rx, ry),
                start,
                end - start,
                0.0,
            );
            arc.to_path(0.1).into_iter().for_each(|el| match el {
                kurbo::PathEl::MoveTo(pt)          => p.move_to(pt),
                kurbo::PathEl::LineTo(pt)          => p.line_to(pt),
                kurbo::PathEl::QuadTo(c, pt)       => p.quad_to(c, pt),
                kurbo::PathEl::CurveTo(c1, c2, pt) => p.curve_to(c1, c2, pt),
                kurbo::PathEl::ClosePath           => p.close_path(),
            });
        }
    }

    fn quadratic_curve_to(&mut self, cpx: f64, cpy: f64, x: f64, y: f64) {
        if let Some(ref mut p) = self.path {
            p.quad_to(kurbo::Point::new(cpx, cpy), kurbo::Point::new(x, y));
        }
    }

    fn bezier_curve_to(
        &mut self,
        cp1x: f64,
        cp1y: f64,
        cp2x: f64,
        cp2y: f64,
        x: f64,
        y: f64,
    ) {
        if let Some(ref mut p) = self.path {
            p.curve_to(
                kurbo::Point::new(cp1x, cp1y),
                kurbo::Point::new(cp2x, cp2y),
                kurbo::Point::new(x, y),
            );
        }
    }

    fn stroke(&mut self) {
        let Some(path) = self.path.clone() else { return };
        let transform = self.transform;
        let stroke = self.current_stroke();
        // M6-P1: shadow pass
        if let Some(ref sh) = self.shadow.clone() {
            let shadow_transform = transform.then_translate(kurbo::Vec2::new(sh.dx, sh.dy));
            if let Some(ref mut ctx) = self.render_ctx {
                ctx.set_transform(shadow_transform);
                ctx.set_blend_mode(vello_cpu::peniko::BlendMode::default());
                ctx.set_paint(sh.color);
                ctx.set_stroke(stroke.clone());
                ctx.stroke_path(&path);
            }
        }
        self.apply_stroke_paint();
        if let Some(ref mut ctx) = self.render_ctx {
            ctx.set_transform(transform);
            ctx.set_stroke(stroke);
            ctx.stroke_path(&path);
        }
    }

    fn fill(&mut self) {
        let Some(path) = self.path.clone() else { return };
        let transform = self.transform;
        // M6-P1: shadow pass
        if let Some(ref sh) = self.shadow.clone() {
            let shadow_transform = transform.then_translate(kurbo::Vec2::new(sh.dx, sh.dy));
            if let Some(ref mut ctx) = self.render_ctx {
                ctx.set_transform(shadow_transform);
                ctx.set_fill_rule(Fill::NonZero);
                ctx.set_blend_mode(vello_cpu::peniko::BlendMode::default());
                ctx.set_paint(sh.color);
                ctx.fill_path(&path);
            }
        }
        self.apply_fill_paint();
        if let Some(ref mut ctx) = self.render_ctx {
            ctx.set_transform(transform);
            ctx.set_fill_rule(Fill::NonZero);
            ctx.fill_path(&path);
        }
    }
}

// ---------------------------------------------------------------------------
// TextRenderer
// ---------------------------------------------------------------------------

impl TextRenderer for VelloCpuRenderContext {
    fn set_font(&mut self, font: &str) {
        self.font_info = parse_css_font(font);
    }

    fn set_text_align(&mut self, align: TextAlign) {
        self.text_align = align;
    }

    fn set_text_baseline(&mut self, baseline: TextBaseline) {
        self.text_baseline = baseline;
    }

    fn fill_text(&mut self, text: &str, x: f64, y: f64) {
        if text.is_empty() { return; }

        let font_info = self.font_info.clone();
        let primary_font = get_font(font_info.family, font_info.bold, font_info.italic);
        let font_size    = font_info.size as f32;

        let text_width = measure_text_width(text, &font_info);
        let x_off = match self.text_align {
            TextAlign::Center => -text_width / 2.0,
            TextAlign::Right  => -text_width,
            _                 => 0.0,
        };
        // Exhaustive match (no `_` wildcard) — `TextBaseline::Alphabetic`
        // used to silently fall into a wildcard arm that applied
        // `Middle`'s offset, i.e. an extra `size * 0.35` shift downward.
        // "Alphabetic" means the caller's own `y` coordinate ALREADY IS
        // the baseline (the standard Canvas2D/CSS definition) — the
        // correct offset is `0.0`, matching `Bottom`'s own value, not
        // `Middle`'s. Found + fixed 2026-07-24 while comparing this
        // leg's line positions against `uzor-render-urx`'s own
        // (identically-bugged, also fixed this same pass) glyph-run
        // rendering for the typography calibration fixture — this is
        // the crate whose OWN Alphabetic-baseline text (e.g.
        // `uzor-text::draw_paragraph`, which explicitly sets
        // `TextBaseline::Alphabetic` per line) was silently mispositioned.
        let y_off = match self.text_baseline {
            TextBaseline::Top       => font_info.size * 0.8,
            TextBaseline::Middle    => font_info.size * 0.35,
            TextBaseline::Bottom    => 0.0,
            TextBaseline::Alphabetic => 0.0,
        };

        let Some(primary_ref) = to_font_ref(primary_font) else { return };
        let resolved = resolve_glyphs_with_fallback(text, &primary_ref, font_size);
        let fallbacks = get_fallback_fonts();

        let text_transform = Affine::translate((x + x_off, y + y_off));
        let combined = self.transform * text_transform;

        // Fallback index 5 = NotoColorEmoji (COLR font) in chain:
        // [0]=NerdFont, [1]=Symbols2, [2]=CjkSc, [3]=Arabic, [4]=Devanagari,
        // [5]=NotoColorEmoji, [6]=NotoEmoji.
        // vello_cpu requires WHITE paint for COLR runs so the embedded palette is used directly.
        const COLOR_EMOJI_FALLBACK_IDX: usize = 5;
        let fill_color = self.effective_fill_color();
        let white = Color::from_rgba8(255, 255, 255, 255);

        // vello_cpu 0.0.9: glyph_run now takes &mut Resources first. Split-borrow
        // self.render_ctx + self.resources so both can be referenced inside the loop.
        let resources = &mut self.resources;
        if let Some(ref mut ctx) = self.render_ctx {
            ctx.set_transform(combined);

            let mut i = 0;
            while i < resolved.len() {
                let run_font_index = resolved[i].font_index;
                let run_start = i;
                while i < resolved.len() && resolved[i].font_index == run_font_index {
                    i += 1;
                }
                let run = &resolved[run_start..i];
                let is_color_emoji = run_font_index == Some(COLOR_EMOJI_FALLBACK_IDX);
                let font = match run_font_index {
                    None => primary_font,
                    Some(idx) if idx < fallbacks.len() => &fallbacks[idx],
                    _ => primary_font,
                };
                ctx.set_paint(if is_color_emoji { white } else { fill_color });
                let glyphs = run.iter().map(|g| Glyph { id: g.glyph_id, x: g.x, y: 0.0 });
                // Aligned to `uzor-render-vello-gpu`'s own convention
                // (`.hint(!is_color_emoji)`, `context.rs`/`text.rs`) —
                // both are vello-family rasterisers and should agree.
                // This crate hardcoded `.hint(false)` unconditionally
                // until the Wave 7 tail tech-debt sweep (2026-07-24)
                // found the disagreement while investigating why URX's
                // own swash-based CPU text (`.hint(true)`) read
                // differently from this leg's vello_cpu text.
                ctx.glyph_run(resources, font)
                    .font_size(font_size)
                    .hint(!is_color_emoji)
                    .normalized_coords(&[])
                    .fill_glyphs(glyphs);
            }

            ctx.set_transform(self.transform);
        }
    }

    fn stroke_text(&mut self, _text: &str, _x: f64, _y: f64) {
        // vello_cpu glyph_run() draws filled glyphs only; stroke_glyphs
        // requires a different code path.  Deliberate no-op.
    }
}

// ---------------------------------------------------------------------------
// TextMetrics
// ---------------------------------------------------------------------------

impl TextMetrics for VelloCpuRenderContext {
    /// Delegates to [`uzor::shaper`] (cosmic-text) — see this module's
    /// own `font_css_string`-adjacent divergence note for why: skrifa's
    /// raw `advance_width` sum never applies GPOS kerning, so it
    /// disagreed with every OTHER backend in this workspace (all of
    /// which already measure `measure_text_glyphs`/`measure_text_wrapped`/
    /// `text_to_path` through the SAME shaper) — a real cross-backend
    /// layout divergence, not just a cosmetic rendering difference
    /// (`uzor-figures`' `guide::labeler` collision pass feeds a
    /// backend's own `measure_text` result directly into a pass/fail
    /// occupancy check, so a few tenths of a pixel of kerning drift
    /// could flip which candidate slot a label claims).
    fn measure_text(&self, text: &str) -> f64 {
        let font_str = font_css_string(&self.font_info);
        let glyphs = uzor::shaper::measure_glyphs(text, &font_str);
        glyphs.last().map(|g| g.x_offset + g.advance).unwrap_or(0.0)
    }

    fn text_bounds(&self, text: &str, font: &str) -> TextBounds {
        let info = parse_css_font(font);
        let font_size = info.size as f32;
        let glyphs = uzor::shaper::measure_glyphs(text, font);
        let w = glyphs.last().map(|g| g.x_offset + g.advance).unwrap_or(0.0);
        let primary_font = get_font(info.family, info.bold, info.italic);
        let Some(font_ref) = to_font_ref(primary_font) else {
            let ascent  = info.size * 0.9;
            let descent = info.size * 0.3;
            return TextBounds { x: 0.0, y: -ascent, w, h: ascent + descent, ascent, descent };
        };
        let size = skrifa::instance::Size::new(font_size);
        let var_loc = skrifa::instance::LocationRef::default();
        let metrics = font_ref.metrics(size, var_loc);
        let ascent  = metrics.ascent  as f64;
        let descent = (-metrics.descent) as f64;
        TextBounds {
            x: 0.0,
            y: -ascent,
            w,
            h: ascent + descent,
            ascent,
            descent,
        }
    }

    /// Real cluster shaping via cosmic-text.
    ///
    /// Correctly handles Unicode grapheme clusters (`é` as one cluster),
    /// emoji ZWJ sequences, and returns visual left-to-right order for LTR text.
    /// Results are cached per `(font, text)` pair (unbounded cache for Phase 4).
    fn measure_text_glyphs(&self, text: &str, font: &str) -> Vec<uzor::render::GlyphMetric> {
        uzor::shaper::measure_glyphs(text, font)
    }

    /// Real word-wrap via cosmic-text `Wrap::Word`.
    ///
    /// Delegates to [`uzor::shaper::measure_glyphs_wrapped`], which owns its
    /// own `(font, text, max_width)`-keyed cache separate from the unwrapped
    /// `measure_glyphs`/`text_to_path` cache.
    fn measure_text_wrapped(&self, text: &str, font: &str, max_width: f64) -> Vec<uzor::render::WrappedLine> {
        uzor::shaper::measure_glyphs_wrapped(text, font, max_width)
    }

    fn text_to_path(&self, text: &str, font: &str) -> String {
        uzor::shaper::text_to_path(text, font)
    }
}

// ---------------------------------------------------------------------------
// Masking — clip() overridden; clip_rect/push_mask/pop_mask use defaults
// ---------------------------------------------------------------------------

impl Masking for VelloCpuRenderContext {
    fn clip(&mut self) {
        let Some(path) = self.path.clone() else { return };
        let transform = self.transform;
        self.clip_active = true;
        if let Some(ref mut ctx) = self.render_ctx {
            ctx.set_transform(transform);
            ctx.push_clip_path(&path);
        }
    }

    /// Even-odd fill rule override: clips using `Fill::EvenOdd` so two-subpath
    /// paths (outer rect CW + inner shape CCW) produce a ring-shaped clip.
    fn push_clip_svg_path_even_odd(&mut self, d: &str) {
        uzor::render::emit_svg_path(self, d);
        let Some(path) = self.path.clone() else { return };
        let transform = self.transform;
        self.clip_active = true;
        if let Some(ref mut ctx) = self.render_ctx {
            ctx.set_transform(transform);
            ctx.set_fill_rule(Fill::EvenOdd);
            ctx.push_clip_path(&path);
            ctx.set_fill_rule(Fill::NonZero);
        }
        self.save();
    }
}

// ---------------------------------------------------------------------------
// Effects
// ---------------------------------------------------------------------------

impl Effects for VelloCpuRenderContext {
    fn set_shadow(&mut self, dx: f64, dy: f64, _blur: f64, color: &str) {
        // Vello CPU has a DropShadow filter (pub(crate) only).
        // Approximated as an offset, pre-alpha copy — matches vello-gpu.
        let shadow_color = parse_color(color);
        self.shadow = Some(ShadowState { dx, dy, color: shadow_color });
    }

    fn clear_shadow(&mut self) {
        self.shadow = None;
    }

    fn set_blend_mode(&mut self, mode: UzorBlendMode) {
        self.blend_mode = mode;
        let blend = Self::blend_to_vello_cpu(mode);
        if let Some(ref mut ctx) = self.render_ctx {
            ctx.set_blend_mode(blend);
        }
    }
}

// ---------------------------------------------------------------------------
// ShapeHelpers — fill_rect and stroke_rect overridden; rounded uses defaults
// ---------------------------------------------------------------------------

impl ShapeHelpers for VelloCpuRenderContext {
    fn fill_rect(&mut self, x: f64, y: f64, w: f64, h: f64) {
        let r = Rect::new(x, y, x + w, y + h);
        let transform = self.transform;
        // M6-P1: shadow pass
        if let Some(ref sh) = self.shadow.clone() {
            let shadow_transform = transform.then_translate(kurbo::Vec2::new(sh.dx, sh.dy));
            if let Some(ref mut ctx) = self.render_ctx {
                ctx.set_transform(shadow_transform);
                ctx.set_blend_mode(vello_cpu::peniko::BlendMode::default());
                ctx.set_paint(sh.color);
                ctx.fill_rect(&r);
            }
        }
        self.apply_fill_paint();
        if let Some(ref mut ctx) = self.render_ctx {
            ctx.set_transform(transform);
            ctx.fill_rect(&r);
        }
    }

    fn stroke_rect(&mut self, x: f64, y: f64, w: f64, h: f64) {
        let r = Rect::new(x, y, x + w, y + h);
        let transform = self.transform;
        let stroke = self.current_stroke();
        self.apply_stroke_paint();
        if let Some(ref mut ctx) = self.render_ctx {
            ctx.set_transform(transform);
            ctx.set_stroke(stroke);
            ctx.stroke_rect(&r);
        }
    }

    fn rounded_rect_corners(
        &mut self,
        x: f64,
        y: f64,
        w: f64,
        h: f64,
        tl: f64,
        tr: f64,
        br: f64,
        bl: f64,
    ) {
        let max_r = (w / 2.0).min(h / 2.0).max(0.0);
        let tl = tl.clamp(0.0, max_r);
        let tr = tr.clamp(0.0, max_r);
        let br = br.clamp(0.0, max_r);
        let bl = bl.clamp(0.0, max_r);

        self.begin_path();
        self.move_to(x + tl, y);
        self.line_to(x + w - tr, y);
        self.arc(x + w - tr, y + tr, tr, -std::f64::consts::FRAC_PI_2, 0.0);
        self.line_to(x + w, y + h - br);
        self.arc(x + w - br, y + h - br, br, 0.0, std::f64::consts::FRAC_PI_2);
        self.line_to(x + bl, y + h);
        self.arc(x + bl, y + h - bl, bl, std::f64::consts::FRAC_PI_2, std::f64::consts::PI);
        self.line_to(x, y + tl);
        self.arc(x + tl, y + tl, tl, std::f64::consts::PI, std::f64::consts::PI * 1.5);
        self.close_path();
    }
}

// ---------------------------------------------------------------------------
// BatchPainter — optimized: single merged BezPath per call
// ---------------------------------------------------------------------------

impl BatchPainter for VelloCpuRenderContext {
    fn draw_line_batch(&mut self, lines: &[LineSegment], color: &str, width: f64) {
        if lines.is_empty() {
            return;
        }
        self.set_stroke_color(color);
        self.set_stroke_width(width);
        let mut path = BezPath::new();
        for l in lines {
            path.move_to(kurbo::Point::new(l.x1, l.y1));
            path.line_to(kurbo::Point::new(l.x2, l.y2));
        }
        let transform = self.transform;
        let stroke = self.current_stroke();
        self.apply_stroke_paint();
        if let Some(ref mut ctx) = self.render_ctx {
            ctx.set_transform(transform);
            ctx.set_stroke(stroke);
            ctx.stroke_path(&path);
        }
    }

    fn draw_circle_batch(&mut self, circles: &[CircleBatch], color: &str) {
        if circles.is_empty() {
            return;
        }
        self.set_fill_color(color);
        let mut path = BezPath::new();
        for c in circles {
            let circle = kurbo::Circle::new(kurbo::Point::new(c.cx, c.cy), c.r);
            path.extend(circle.path_elements(0.1));
        }
        let transform = self.transform;
        self.apply_fill_paint();
        if let Some(ref mut ctx) = self.render_ctx {
            ctx.set_transform(transform);
            ctx.set_fill_rule(Fill::NonZero);
            ctx.fill_path(&path);
        }
    }

    fn stroke_polyline(&mut self, pts: &[(f64, f64)], color: &str, width: f64) {
        if pts.is_empty() {
            return;
        }
        self.set_stroke_color(color);
        self.set_stroke_width(width);
        let mut path = BezPath::new();
        path.move_to(kurbo::Point::new(pts[0].0, pts[0].1));
        for &(x, y) in &pts[1..] {
            path.line_to(kurbo::Point::new(x, y));
        }
        let transform = self.transform;
        let stroke = self.current_stroke();
        self.apply_stroke_paint();
        if let Some(ref mut ctx) = self.render_ctx {
            ctx.set_transform(transform);
            ctx.set_stroke(stroke);
            ctx.stroke_path(&path);
        }
    }
}

// ---------------------------------------------------------------------------
// GradientPainter
// ---------------------------------------------------------------------------

impl GradientPainter for VelloCpuRenderContext {
    fn fill_linear_gradient(
        &mut self,
        stops: &[(f32, &str)],
        x1: f64,
        y1: f64,
        x2: f64,
        y2: f64,
    ) {
        let Some(path) = self.path.clone() else { return };
        let transform = self.transform;

        let color_stops: ColorStops = ColorStops::from(
            stops
                .iter()
                .map(|(offset, hex)| ColorStop::from((*offset, parse_color(hex))))
                .collect::<Vec<ColorStop>>()
                .as_slice(),
        );

        let gradient = Gradient {
            kind: LinearGradientPosition {
                start: kurbo::Point::new(x1, y1),
                end: kurbo::Point::new(x2, y2),
            }
            .into(),
            stops: color_stops,
            extend: Extend::Pad,
            ..Default::default()
        };

        if let Some(ref mut ctx) = self.render_ctx {
            ctx.set_transform(transform);
            ctx.set_fill_rule(Fill::NonZero);
            ctx.set_paint(gradient);
            ctx.fill_path(&path);
        }
    }

    fn fill_radial_gradient(
        &mut self,
        cx: f64,
        cy: f64,
        r: f64,
        stops: &[(f32, &str)],
        x: f64,
        y: f64,
        w: f64,
        h: f64,
    ) {
        let _ = (x, y, w, h);
        let Some(path) = self.path.clone() else { return };
        let transform = self.transform;

        let color_stops: ColorStops = ColorStops::from(
            stops
                .iter()
                .map(|(offset, hex)| ColorStop::from((*offset, parse_color(hex))))
                .collect::<Vec<ColorStop>>()
                .as_slice(),
        );

        let gradient = Gradient::new_radial(kurbo::Point::new(cx, cy), r as f32)
            .with_stops(color_stops.as_slice())
            .with_extend(Extend::Pad);

        if let Some(ref mut ctx) = self.render_ctx {
            ctx.set_transform(transform);
            ctx.set_fill_rule(Fill::NonZero);
            ctx.set_paint(gradient);
            ctx.fill_path(&path);
        }
    }
}

// ---------------------------------------------------------------------------
// UiEffectHelpers — all defaults (no blur support on vello-cpu)
// ---------------------------------------------------------------------------

impl uzor::render::UiEffectHelpers for VelloCpuRenderContext {}

// ---------------------------------------------------------------------------
// RenderContext (dpr only)
// ---------------------------------------------------------------------------

impl UzorRenderContext for VelloCpuRenderContext {
    fn dpr(&self) -> f64 {
        self.dpr
    }

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

    fn push_offscreen_target(&mut self, desc: OffscreenTargetDesc) -> OffscreenTarget {
        let w = desc.width_px.max(1);
        let h = desc.height_px.max(1);
        let w16 = w.min(u16::MAX as u32) as u16;
        let h16 = h.min(u16::MAX as u32) as u16;

        let id = OffscreenTargetId(self.next_offscreen_id);
        self.next_offscreen_id += 1;

        let settings = RenderSettings {
            level:       vello_cpu::Level::new(),
            num_threads: 0,
            render_mode: RenderMode::OptimizeSpeed,
        };
        let fresh_ctx = VelloCpuCtx::new_with(w16, h16, settings);
        let fresh_resources = Resources::new();

        let saved_ctx = std::mem::replace(&mut self.render_ctx, Some(fresh_ctx));
        let saved_resources = std::mem::replace(&mut self.resources, fresh_resources);
        let saved_width = std::mem::replace(&mut self.width, w);
        let saved_height = std::mem::replace(&mut self.height, h);

        self.offscreen_stack.push(SavedRecording {
            id,
            render_ctx:  saved_ctx,
            resources:   saved_resources,
            width:       saved_width,
            height:      saved_height,
            transform:   self.transform,
            clip_active: std::mem::take(&mut self.clip_active),
            state_stack: std::mem::take(&mut self.state_stack),
            path:        self.path.take(),
        });

        // The offscreen subtree paints at its own local origin — fresh
        // state, exactly like `begin_frame`.
        self.transform = Affine::IDENTITY;

        Some(id)
    }

    fn pop_offscreen_target(&mut self) {
        let Some(saved) = self.offscreen_stack.pop() else {
            return;
        };

        let w = self.width.min(u16::MAX as u32) as u16;
        let h = self.height.min(u16::MAX as u32) as u16;
        let pixel_count = self.width as usize * self.height as usize;
        let mut pixels = vec![0u8; pixel_count * 4];
        if let Some(ref mut ctx) = self.render_ctx {
            ctx.flush();
            ctx.render_to_buffer(&mut self.resources, &mut pixels, w, h, RenderMode::OptimizeSpeed);
        }

        self.offscreen_targets.insert(
            saved.id,
            CachedTarget { pixels, width: self.width, height: self.height },
        );

        self.render_ctx  = saved.render_ctx;
        self.resources   = saved.resources;
        self.width       = saved.width;
        self.height      = saved.height;
        self.transform   = saved.transform;
        self.clip_active = saved.clip_active;
        self.state_stack = saved.state_stack;
        self.path        = saved.path;
    }

    fn draw_cached_target(&mut self, id: OffscreenTargetId, dst_rect: UzorRect) -> bool {
        let Some(target) = self.offscreen_targets.get(&id) else {
            return false;
        };
        if dst_rect.width <= 0.0 || dst_rect.height <= 0.0 {
            return false;
        }
        let img_w = target.width.max(1);
        let img_h = target.height.max(1);

        // Convert the cached straight RGBA8 buffer into vello_common's
        // premultiplied-alpha pixmap representation.
        let premul: Vec<vello_cpu::color::PremulRgba8> = target
            .pixels
            .chunks_exact(4)
            .map(|px| {
                let a = u16::from(px[3]);
                let mul = |c: u8| ((a * u16::from(c)) / 255) as u8;
                vello_cpu::color::PremulRgba8 { r: mul(px[0]), g: mul(px[1]), b: mul(px[2]), a: px[3] }
            })
            .collect();
        let pixmap = VelloCpuPixmap::from_parts(
            premul,
            img_w.min(u16::MAX as u32) as u16,
            img_h.min(u16::MAX as u32) as u16,
        );
        let source = ImageSource::Pixmap(Arc::new(pixmap));
        let image = Image { image: source, sampler: Default::default() };

        // Place the image (native pixel space `[0,img_w) x [0,img_h)`)
        // into `dst_rect` via the paint transform: scale from native
        // size to the destination size, then translate into position.
        let scale_x = dst_rect.width / f64::from(img_w);
        let scale_y = dst_rect.height / f64::from(img_h);
        let paint_transform = Affine::translate((dst_rect.x, dst_rect.y))
            * Affine::scale_non_uniform(scale_x, scale_y);

        let rect = Rect::new(dst_rect.x, dst_rect.y, dst_rect.x + dst_rect.width, dst_rect.y + dst_rect.height);
        let path = rect.to_path(0.1);
        let transform = self.transform;
        let blend = Self::blend_to_vello_cpu(self.blend_mode);

        if let Some(ref mut ctx) = self.render_ctx {
            ctx.set_transform(transform);
            ctx.set_blend_mode(blend);
            ctx.set_paint_transform(paint_transform);
            ctx.set_fill_rule(Fill::NonZero);
            ctx.set_paint(image);
            ctx.fill_path(&path);
            ctx.reset_paint_transform();
        }
        true
    }

    fn resize_offscreen_target(&mut self, id: OffscreenTargetId, desc: OffscreenTargetDesc) -> bool {
        if !self.offscreen_targets.contains_key(&id) {
            return false;
        }
        // Cached content no longer matches the requested size — drop it;
        // the caller's next `push_offscreen_target` (same id semantics
        // don't apply here since ids aren't reused) will repaint fresh.
        // Per the trait contract callers should `free` + `push` a new
        // target when this returns `false`; report success only when
        // the stored buffer already matches the new size (no-op resize).
        let desc_matches = self
            .offscreen_targets
            .get(&id)
            .is_some_and(|t| t.width == desc.width_px && t.height == desc.height_px);
        desc_matches
    }

    fn free_offscreen_target(&mut self, id: OffscreenTargetId) {
        self.offscreen_targets.remove(&id);
    }
}

// ---------------------------------------------------------------------------
// RenderContextExt — blur/glass effects (no-op for CPU backend)
// ---------------------------------------------------------------------------

impl RenderContextExt for VelloCpuRenderContext {
    /// CPU backend carries no blur image state.
    type BlurImage = ();

    fn set_blur_image(&mut self, _image: Option<()>, _width: u32, _height: u32) {
        // CPU backend does not support blur backgrounds.
    }

    fn set_use_convex_glass_buttons(&mut self, _use_convex: bool) {
        // CPU backend does not support convex glass buttons.
    }
}

// ---------------------------------------------------------------------------
// Tests — transform-composition regression (canvas-style incremental CTM)
// ---------------------------------------------------------------------------
//
// Root-caused defect: `translate`/`rotate`/`scale` used to compose via
// kurbo's `then_*` family (`Op * self` — the operation applied in the
// OUTER/world frame, after everything already accumulated). A `translate`
// followed by a `rotate`/`scale` on a non-identity transform must instead
// compose LOCAL-frame (`self * Op`, kurbo's `pre_*` family) — exactly the
// semantics `uzor-render-tiny-skia`'s reference-correct `Painter::
// translate`/`rotate`/`scale` already use. These tests pin the exact
// expected device-space mapping of a known local point so a regression to
// `then_*` fails immediately, with no rendering required.
#[cfg(test)]
mod tests {
    use super::*;
    use uzor::render::Painter;

    #[test]
    fn translate_then_rotate_matches_local_frame_composition() {
        let mut ctx = VelloCpuRenderContext::new(1.0);

        // translate(10, 0) then rotate(90deg) — a point drawn locally at
        // (5, 0) after these two calls must land at device (10, 5):
        // rotate(90deg) first turns local (5,0) into (0,5) in the frame
        // `translate` already established, THEN that frame's own (10, 0)
        // offset is added.
        ctx.translate(10.0, 0.0);
        ctx.rotate(std::f64::consts::FRAC_PI_2);

        let p = ctx.transform * kurbo::Point::new(5.0, 0.0);
        assert!((p.x - 10.0).abs() < 1e-9, "x mismatch: got {p:?}");
        assert!((p.y - 5.0).abs() < 1e-9, "y mismatch: got {p:?}");

        // A `then_*`-composed (world-frame) regression would instead
        // rotate the ALREADY-translated point about the origin, landing
        // at device (0, 10) — pinning the wrong-answer shape too so a
        // silent revert is unambiguous, not just "some other number."
        assert!(
            (p.x - 0.0).abs() > 1.0 || (p.y - 10.0).abs() > 1.0,
            "result matches the WRONG (then_*, world-frame) composition"
        );
    }

    #[test]
    fn translate_then_scale_matches_local_frame_composition() {
        let mut ctx = VelloCpuRenderContext::new(1.0);

        // Matches Canvas2D semantics: local (0,0) -> device (10,20);
        // local (5,5) -> device (10 + 2*5, 20 + 3*5) = (20, 35).
        ctx.translate(10.0, 20.0);
        ctx.scale(2.0, 3.0);

        let origin = ctx.transform * kurbo::Point::new(0.0, 0.0);
        assert!((origin.x - 10.0).abs() < 1e-9 && (origin.y - 20.0).abs() < 1e-9);

        let p = ctx.transform * kurbo::Point::new(5.0, 5.0);
        assert!((p.x - 20.0).abs() < 1e-9 && (p.y - 35.0).abs() < 1e-9, "got {p:?}");
    }

    // ── Dash pattern wiring (defect fix: `set_line_dash` used to be a
    // silent no-op — every dashed stroke rendered solid) ──────────────

    #[test]
    fn set_line_dash_populates_current_strokes_dash_pattern() {
        let mut ctx = VelloCpuRenderContext::new(1.0);
        ctx.set_line_dash(&[5.0, 3.0]);
        let stroke = ctx.current_stroke();
        assert_eq!(stroke.dash_pattern.as_slice(), &[5.0, 3.0]);
        assert_eq!(stroke.dash_offset, 0.0);
    }

    #[test]
    fn set_line_dash_empty_pattern_clears_a_previously_set_dash() {
        let mut ctx = VelloCpuRenderContext::new(1.0);
        ctx.set_line_dash(&[5.0, 3.0]);
        ctx.set_line_dash(&[]);
        let stroke = ctx.current_stroke();
        assert!(stroke.dash_pattern.is_empty());
    }

    #[test]
    fn save_restore_preserves_the_dash_pattern() {
        let mut ctx = VelloCpuRenderContext::new(1.0);
        ctx.save();
        ctx.set_line_dash(&[5.0, 3.0]);
        ctx.restore();
        // `set_line_dash` happened AFTER `save()`, so `restore()` must
        // pop it back to "no dash" — same save/restore contract every
        // other stroke-state field on this context already honours.
        assert!(ctx.current_stroke().dash_pattern.is_empty());
    }

    /// A dashed stroke must rasterize to MULTIPLE disjoint ink runs
    /// along the line, not one continuous solid run — the exact defect
    /// this fix closes (`set_line_dash` was previously a no-op, so
    /// every dashed reference-line/crosshair guide rendered solid on
    /// this backend).
    #[test]
    fn dashed_stroke_rasterizes_to_multiple_disjoint_ink_runs() {
        const W: u16 = 100;
        const H: u16 = 10;
        let mut ctx = VelloCpuRenderContext::new(1.0);
        ctx.begin_frame(W as u32, H as u32);
        ctx.set_fill_color("#000000");
        ShapeHelpers::fill_rect(&mut ctx, 0.0, 0.0, W as f64, H as f64);
        ctx.set_stroke_color("#ffffff");
        ctx.set_stroke_width(4.0);
        ctx.set_line_dash(&[10.0, 10.0]);
        ctx.begin_path();
        ctx.move_to(0.0, 5.0);
        ctx.line_to(W as f64, 5.0);
        Painter::stroke(&mut ctx);

        let mut buf = vec![0u8; W as usize * H as usize * 4];
        ctx.render_to_pixmap_rgba8(&mut buf, W, H);

        // Walk the stroke's own row and count transitions into a
        // "covered" (bright, premultiplied-white) run.
        let y = 5usize;
        let mut runs = 0usize;
        let mut was_covered = false;
        for x in 0..W as usize {
            let idx = (y * W as usize + x) * 4;
            let covered = buf[idx] > 128;
            if covered && !was_covered {
                runs += 1;
            }
            was_covered = covered;
        }
        assert!(runs >= 3, "expected multiple disjoint dash runs along the stroke, got {runs} run(s)");
    }
}