uzor-render-urx 1.5.1

URX render adapter — implements uzor::RenderContext, emits urx_core::Scene. Lets uzor/tessera consumers select any of the 4 URX 2D backends (cpu/wgpu/hybrid/wgpu-full) through the standard backend-selection path. Phase A bridge — Phase B will let consumers emit Scene directly.
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
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
//! `UrxRenderContext` — implements the full `uzor::RenderContext` supertrait
//! composition, emits `urx_core::Scene::DrawCommand` events.
//!
//! State management mirrors the Canvas2D semantics used by every other
//! uzor backend (vello-cpu / vello-hybrid / tiny-skia): `save()/restore()`
//! push/pop a frame of {transform, fill_color, stroke_color, stroke_width,
//! line cap/join, global_alpha, font, text align/baseline, blend, clip
//! depth}. `begin_path()` resets the current path; `fill()/stroke()` emit
//! a `FillPath`/`StrokePath` command carrying the buffered path + current
//! style + current transform. Backend reads the `Scene` once and
//! rasterises in painter's order — no statefulness leaks across `Scene`.

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

use kurbo::{
    Affine as KAffine, BezPath, Cap, Join, Point as KPoint, Rect as KRect, Vec2,
};
use peniko::{
    Brush as PenikoBrush, Color, ColorStop, ColorStops, Extend, Gradient,
    LinearGradientPosition, RadialGradientPosition,
};

use uzor_urx_core::scene::{
    Dash as UrxDash, DrawCommand, FillRule, FontId, Glyph, LineCap as UrxLineCap,
    LineBatchSegment, LineJoin as UrxLineJoin, Scene, Stroke as UrxStroke,
};

use uzor::fonts::{self, FontFamily};
use uzor::render::{
    BatchPainter, BlendMode as UzorBlendMode, CircleBatch, Effects, GlyphMetric, GradientPainter,
    LineSegment, Masking, Painter, RenderContext as UzorRenderContext, RenderContextExt,
    ShapeHelpers, TextAlign, TextBaseline, TextBounds, TextMetrics, TextRenderer,
    UiEffectHelpers,
};

// ── Font info (Canvas2D-style font shorthand) ───────────────────────────────

#[derive(Clone, Debug)]
struct FontInfo {
    size:   f32,
    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(s: &str) -> FontInfo {
    let p = fonts::parse_css_font(s);
    FontInfo { size: p.size, bold: p.bold, italic: p.italic, family: p.family }
}

// ── Color parsing ───────────────────────────────────────────────────────────

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

fn apply_alpha(c: Color, alpha: f64) -> Color {
    if alpha >= 1.0 { c } else { c.multiply_alpha(alpha as f32) }
}

// ── Saved state frame ──────────────────────────────────────────────────────

#[derive(Clone)]
struct SavedState {
    transform:     KAffine,
    fill_color:    Color,
    stroke_color:  Color,
    stroke_width:  f64,
    line_cap:      Cap,
    line_join:     Join,
    /// Current dash pattern (Canvas2D's `setLineDash`) — `None` is a
    /// plain solid stroke. Local/user-space lengths, same coordinate
    /// space `stroke_width` and every path coordinate already use — see
    /// `uzor_urx_core::scene::Dash`'s own doc comment for why that
    /// space is the correct one (the emitted `DrawCommand`'s own
    /// `transform` field scales the pattern the same way it scales the
    /// rest of the geometry).
    line_dash:     Option<Vec<f64>>,
    global_alpha:  f64,
    font_info:     FontInfo,
    text_align:    TextAlign,
    text_baseline: TextBaseline,
    blend_mode:    UzorBlendMode,
    /// How many `PushClipRect`/`PushClipRoundedRect` ops were emitted at
    /// this save level. `restore()` emits matching `PopClip`s.
    clip_pushes:   u32,
}

#[derive(Clone)]
struct ShadowState {
    dx:    f64,
    dy:    f64,
    color: Color,
}

#[derive(Clone, Copy, Debug)]
enum PathHint {
    Empty,
    FullCircle { cx: f64, cy: f64, radius: f64 },
    Generic,
}

// ── UrxRenderContext ────────────────────────────────────────────────────────

/// `uzor::RenderContext` impl that buffers draw events into an
/// `urx_core::Scene`. Backend-agnostic — choose the backend at submit time.
///
/// ## Frame lifecycle
///
/// ```rust,ignore
/// let mut ctx = UrxRenderContext::new(dpr);
/// ctx.begin_frame(width, height);
/// // consumer paints via the standard RenderContext trait surface
/// let scene = ctx.take_scene();
/// // hand to any URX backend
/// ```
pub struct UrxRenderContext {
    scene: Scene,
    /// Monotonic identity of the currently buffered scene.
    ///
    /// A new revision starts only when the producer begins rebuilding the
    /// frame. Submitting or re-submitting the retained scene does not change
    /// it, so a backend can safely use this value as a coarse cache key.
    revision: u64,
    width:  u32,
    height: u32,
    dpr:    f64,

    // Drawing state
    transform:     KAffine,
    fill_color:    Color,
    stroke_color:  Color,
    stroke_width:  f64,
    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,
    blend_mode:    UzorBlendMode,

    /// Current Canvas2D-style path buffer.
    path: BezPath,
    /// Exact primitive identity for the subset that can bypass generic path
    /// tessellation without changing the public path API.
    path_hint: PathHint,

    /// Drop shadow (optional). Emitted as a translated pre-pass before the
    /// main draw on `fill_rect` / `fill` / `fill_text` ops.
    shadow: Option<ShadowState>,

    /// Clip stack depth at each save level — `clip()` increments the top,
    /// `restore()` pops matching `PopClip` ops to balance.
    clip_pushes: u32,

    state_stack: Vec<SavedState>,
}

impl UrxRenderContext {
    pub fn new(dpr: f64) -> Self {
        Self {
            scene:         Scene::new(),
            revision:      0,
            width:         0,
            height:        0,
            dpr,
            transform:     KAffine::IDENTITY,
            fill_color:    Color::from_rgba8(0, 0, 0, 255),
            stroke_color:  Color::from_rgba8(0, 0, 0, 255),
            stroke_width:  1.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,
            blend_mode:    UzorBlendMode::Normal,
            path:          BezPath::new(),
            path_hint:     PathHint::Empty,
            shadow:        None,
            clip_pushes:   0,
            state_stack:   Vec::new(),
        }
    }

    /// Defensive guard for any path-op that kurbo requires be preceded
    /// by a `MoveTo` (line_to, quad_to, curve_to, close_path, arc
    /// segment append). Canvas2D semantics tolerate calling these on
    /// an empty / just-closed path — they implicitly start a fresh
    /// subpath at the given fallback point (or at the op's own
    /// target). kurbo panics with "BezPath must begin with MoveTo",
    /// so we open the subpath ourselves.
    ///
    /// Cheap when the subpath is already open (one `last()` peek +
    /// pattern match) — only walks the elements when the path is
    /// non-empty AND the last element is a `ClosePath`.
    fn ensure_subpath_open(&mut self, fallback: KPoint) {
        let needs_move = match self.path.elements().last() {
            None => true,
            Some(kurbo::PathEl::ClosePath) => true,
            _ => false,
        };
        if needs_move {
            self.path.move_to(fallback);
        }
    }

    /// Reset for a new frame. Discards any buffered draws + state.
    pub fn begin_frame(&mut self, width: u32, height: u32) {
        self.revision = self.revision.saturating_add(1);
        self.scene.reset();
        self.width  = width;
        self.height = height;
        self.transform = KAffine::IDENTITY;
        self.path.truncate(0);
        self.path_hint = PathHint::Empty;
        self.shadow = None;
        self.clip_pushes = 0;
        self.state_stack.clear();
    }

    /// Take ownership of the buffered `Scene` and reset the inner one. The
    /// returned scene is what the URX backend rasterises this frame.
    pub fn take_scene(&mut self) -> Scene {
        std::mem::replace(&mut self.scene, Scene::new())
    }

    /// Clear submitted commands while retaining the scene's allocation.
    ///
    /// Submitters that only need to borrow [`Self::scene`] should call this
    /// after rendering instead of taking and dropping the whole scene.
    pub fn recycle_scene(&mut self) {
        self.scene.reset();
    }

    /// Read-only access (for tests / inspection).
    pub fn scene(&self) -> &Scene { &self.scene }

    /// Monotonic revision of the buffered scene.
    pub fn revision(&self) -> u64 { self.revision }

    pub fn size(&self) -> (u32, u32) { (self.width, self.height) }

    // ── Internal helpers ───────────────────────────────────────────────────

    fn effective_fill_brush(&self) -> PenikoBrush {
        PenikoBrush::Solid(apply_alpha(self.fill_color, self.global_alpha))
    }

    fn effective_stroke_brush(&self) -> PenikoBrush {
        PenikoBrush::Solid(apply_alpha(self.stroke_color, self.global_alpha))
    }

    /// Alpha-scale a freshly-built [`Gradient`] by `global_alpha` (a
    /// gradient's stops carry their own per-stop alpha already;
    /// `global_alpha` composes on top, same as `effective_fill_brush`'s
    /// solid-color path applies it via [`apply_alpha`]). Used ONLY by
    /// `GradientPainter`'s two entry points below — unlike the old
    /// `fill_gradient`-stash design, no state survives past the single
    /// call that builds this brush (see `fill_linear_gradient`'s own doc
    /// comment for why the stash was removed entirely).
    fn gradient_brush(&self, g: Gradient) -> PenikoBrush {
        if self.global_alpha < 1.0 {
            let stops_vec: Vec<ColorStop> = g
                .stops
                .iter()
                .map(|s| ColorStop {
                    offset: s.offset,
                    color:  s.color.multiply_alpha(self.global_alpha as f32),
                })
                .collect();
            let mut g2 = g.clone();
            g2.stops = ColorStops::from(stops_vec.as_slice());
            PenikoBrush::Gradient(g2)
        } else {
            PenikoBrush::Gradient(g)
        }
    }

    /// Shared draw core for `fill()` and the two `GradientPainter` entry
    /// points below — emits the shadow pre-pass (if any) then the main
    /// `FillPath` for the CURRENT path buffer, using `brush`. No-op on
    /// an empty path (Canvas2D semantics: filling nothing draws
    /// nothing). Does NOT clear `self.path` — matches `fill()`'s
    /// pre-existing behaviour (only `begin_path()` clears it, so a
    /// caller CAN fill the same path twice, e.g. once solid then once
    /// with a gradient, same as Canvas2D's own `fill()` contract).
    fn emit_fill_path(&mut self, brush: PenikoBrush) {
        if self.path.elements().is_empty() { return; }
        if let Some(sh) = self.shadow.clone() {
            self.scene.push(DrawCommand::FillPath {
                path:      self.path.clone(),
                rule:      FillRule::NonZero,
                brush:     PenikoBrush::Solid(apply_alpha(sh.color, self.global_alpha)),
                transform: self.transform.then_translate(Vec2::new(sh.dx, sh.dy)),
            });
        }
        self.scene.push(DrawCommand::FillPath {
            path: self.path.clone(),
            rule: FillRule::NonZero,
            brush,
            transform: self.transform,
        });
    }

    fn current_stroke(&self) -> UrxStroke {
        UrxStroke {
            width:       self.stroke_width as f32,
            miter_limit: 4.0,
            cap:         to_urx_cap(self.line_cap),
            join:        to_urx_join(self.line_join),
            dash:        self.line_dash.as_ref().map(|pattern| UrxDash {
                pattern: pattern.iter().map(|&v| v as f32).collect(),
                // Canvas2D's `lineDashOffset` has no `Painter`-trait
                // setter (only `set_line_dash(pattern)` exists) — every
                // dash always starts at phase 0 until the trait grows
                // one.
                phase: 0.0,
            }),
        }
    }

    /// Emit a fill rect (with optional rounded radii). Honours the
    /// active shadow + current solid `fill_color` — a gradient fill
    /// goes through `GradientPainter::fill_linear_gradient`/
    /// `fill_radial_gradient` instead, which paint the CURRENT PATH
    /// directly (Canvas2D's `rect()` + `fill_linear_gradient()` idiom,
    /// see that method's own doc comment), not this rect-shorthand path.
    fn emit_fill_rect(&mut self, x: f64, y: f64, w: f64, h: f64, radii: Option<[f32; 4]>) {
        let rect = KRect::new(x, y, x + w, y + h);
        if let Some(sh) = self.shadow.clone() {
            self.scene.push(DrawCommand::FillRect {
                rect,
                radii,
                brush: PenikoBrush::Solid(apply_alpha(sh.color, self.global_alpha)),
                transform: self.transform.then_translate(Vec2::new(sh.dx, sh.dy)),
            });
        }
        let brush = self.effective_fill_brush();
        self.scene.push(DrawCommand::FillRect {
            rect,
            radii,
            brush,
            transform: self.transform,
        });
    }

    fn emit_stroke_rect(&mut self, x: f64, y: f64, w: f64, h: f64) {
        let rect = KRect::new(x, y, x + w, y + h);
        let stroke = self.current_stroke();
        let brush = self.effective_stroke_brush();
        self.scene.push(DrawCommand::StrokeRect {
            rect,
            radii: None,
            stroke,
            brush,
            transform: self.transform,
        });
    }
}

// ── Cap/Join translation ────────────────────────────────────────────────────

fn to_urx_cap(c: Cap) -> UrxLineCap {
    match c {
        Cap::Butt   => UrxLineCap::Butt,
        Cap::Round  => UrxLineCap::Round,
        Cap::Square => UrxLineCap::Square,
    }
}

fn to_urx_join(j: Join) -> UrxLineJoin {
    match j {
        Join::Miter => UrxLineJoin::Miter,
        Join::Round => UrxLineJoin::Round,
        Join::Bevel => UrxLineJoin::Bevel,
    }
}

// ── Painter ─────────────────────────────────────────────────────────────────

impl Painter for UrxRenderContext {
    fn save(&mut self) {
        self.state_stack.push(SavedState {
            transform:     self.transform,
            fill_color:    self.fill_color,
            stroke_color:  self.stroke_color,
            stroke_width:  self.stroke_width,
            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,
            blend_mode:    self.blend_mode,
            clip_pushes:   self.clip_pushes,
        });
        // Track new pushes at the new level — popped on restore.
        self.clip_pushes = 0;
    }

    fn restore(&mut self) {
        // Pop any clips pushed since the last save.
        for _ in 0..self.clip_pushes {
            self.scene.push(DrawCommand::PopClip);
        }
        if let Some(s) = self.state_stack.pop() {
            self.transform     = s.transform;
            self.fill_color    = s.fill_color;
            self.stroke_color  = s.stroke_color;
            self.stroke_width  = s.stroke_width;
            self.line_cap      = s.line_cap;
            self.line_join     = s.line_join;
            self.line_dash     = s.line_dash;
            self.global_alpha  = s.global_alpha;
            self.font_info     = s.font_info;
            self.text_align    = s.text_align;
            self.text_baseline = s.text_baseline;
            self.blend_mode    = s.blend_mode;
            self.clip_pushes   = s.clip_pushes;
        }
    }

    // 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(Vec2::new(x, y));
    }
    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_stroke_color(&mut self, color: &str) { self.stroke_color = parse_color(color); }
    fn set_stroke_width(&mut self, width: f64) { self.stroke_width = width; }
    fn set_global_alpha(&mut self, alpha: f64) { self.global_alpha = alpha.clamp(0.0, 1.0); }
    fn set_line_dash(&mut self, pattern: &[f64]) {
        // Canvas2D semantics: an empty pattern clears dashing back to a
        // solid stroke (mirrors `uzor-render-tiny-skia::set_line_dash`'s
        // identical `is_empty()` check — the reference-correct backend
        // this crate's own `current_stroke` doc comments already point
        // to elsewhere in this file).
        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,
        };
    }
    fn set_line_join(&mut self, join: &str) {
        self.line_join = match join {
            "round" => Join::Round,
            "bevel" => Join::Bevel,
            _       => Join::Miter,
        };
    }

    fn begin_path(&mut self) {
        self.path.truncate(0);
        self.path_hint = PathHint::Empty;
    }
    fn move_to(&mut self, x: f64, y: f64) {
        self.path_hint = PathHint::Generic;
        self.path.move_to(KPoint::new(x, y));
    }
    fn line_to(&mut self, x: f64, y: f64) {
        // Canvas2D tolerates `lineTo` on an empty path (starts a
        // subpath at that point). kurbo panics — open the subpath.
        self.ensure_subpath_open(KPoint::new(x, y));
        self.path.line_to(KPoint::new(x, y));
        self.path_hint = PathHint::Generic;
    }
    fn close_path(&mut self) {
        // No-op if no subpath is open — Canvas2D semantics.
        if !self.path.elements().is_empty()
            && !matches!(self.path.elements().last(), Some(kurbo::PathEl::ClosePath))
        {
            self.path.close_path();
            self.path_hint = PathHint::Generic;
        }
    }
    fn rect(&mut self, x: f64, y: f64, w: f64, h: f64) {
        self.path_hint = PathHint::Generic;
        self.path.move_to(KPoint::new(x, y));
        self.path.line_to(KPoint::new(x + w, y));
        self.path.line_to(KPoint::new(x + w, y + h));
        self.path.line_to(KPoint::new(x, y + h));
        self.path.close_path();
    }
    fn arc(&mut self, cx: f64, cy: f64, radius: f64, start: f64, end: f64) {
        // kurbo::Arc → BezPath path-elements appended to the current path.
        // `append_iter` yields LineTo/CurveTo without a leading MoveTo —
        // valid for "continue current subpath", panics on an empty/just-
        // closed path. Emit MoveTo to the arc's starting point when
        // needed (Canvas2D semantics: arc on a fresh path starts a new
        // subpath at the first arc point).
        let path_was_empty = self.path.elements().is_empty();
        let sweep = end - start;
        let arc = kurbo::Arc::new(
            KPoint::new(cx, cy),
            Vec2::new(radius, radius),
            start,
            sweep,
            0.0,
        );
        self.ensure_subpath_open(KPoint::new(
            cx + radius * start.cos(),
            cy + radius * start.sin(),
        ));
        for el in arc.append_iter(0.1) {
            self.path.push(el);
        }
        self.path_hint = if path_was_empty
            && cx.is_finite()
            && cy.is_finite()
            && radius.is_finite()
            && radius >= 0.0
            && (sweep.abs() - std::f64::consts::TAU).abs() <= 1e-9
        {
            PathHint::FullCircle { cx, cy, radius }
        } else {
            PathHint::Generic
        };
    }
    fn ellipse(&mut self, cx: f64, cy: f64, rx: f64, ry: f64, _rot: f64, start: f64, end: f64) {
        self.path_hint = PathHint::Generic;
        let arc = kurbo::Arc::new(
            KPoint::new(cx, cy),
            Vec2::new(rx, ry),
            start,
            end - start,
            0.0,
        );
        self.ensure_subpath_open(KPoint::new(
            cx + rx * start.cos(),
            cy + ry * start.sin(),
        ));
        for el in arc.append_iter(0.1) {
            self.path.push(el);
        }
    }
    fn quadratic_curve_to(&mut self, cpx: f64, cpy: f64, x: f64, y: f64) {
        self.path_hint = PathHint::Generic;
        // kurbo `quad_to` requires an open subpath. Canvas2D starts
        // one implicitly at the control point's previous position;
        // we fall back to the curve start (close enough — only fires
        // when the consumer skipped `move_to`).
        self.ensure_subpath_open(KPoint::new(cpx, cpy));
        self.path.quad_to(KPoint::new(cpx, cpy), KPoint::new(x, y));
    }
    fn bezier_curve_to(&mut self, cp1x: f64, cp1y: f64, cp2x: f64, cp2y: f64, x: f64, y: f64) {
        self.path_hint = PathHint::Generic;
        self.ensure_subpath_open(KPoint::new(cp1x, cp1y));
        self.path.curve_to(
            KPoint::new(cp1x, cp1y),
            KPoint::new(cp2x, cp2y),
            KPoint::new(x, y),
        );
    }

    fn stroke(&mut self) {
        if self.path.elements().is_empty() { return; }
        let stroke = self.current_stroke();
        let brush = self.effective_stroke_brush();
        if stroke.dash.is_none() {
            if let PathHint::FullCircle { cx, cy, radius } = self.path_hint {
                self.scene.push(DrawCommand::StrokeRect {
                    rect: KRect::new(cx - radius, cy - radius, cx + radius, cy + radius),
                    radii: Some([radius as f32; 4]),
                    stroke,
                    brush,
                    transform: self.transform,
                });
                return;
            }
        }
        self.scene.push(DrawCommand::StrokePath {
            path:      self.path.clone(),
            stroke,
            brush,
            transform: self.transform,
        });
    }

    fn fill(&mut self) {
        let brush = self.effective_fill_brush();
        self.emit_fill_path(brush);
    }
}

// ── ShapeHelpers (only fill_rect + stroke_rect overridden) ─────────────────

impl ShapeHelpers for UrxRenderContext {
    fn fill_rect(&mut self, x: f64, y: f64, w: f64, h: f64) {
        self.emit_fill_rect(x, y, w, h, None);
    }
    fn stroke_rect(&mut self, x: f64, y: f64, w: f64, h: f64) {
        self.emit_stroke_rect(x, y, w, h);
    }
    // fill_rounded_rect / stroke_rounded_rect override — use FillRect/StrokeRect
    // with radii so the backend can do rounded-rect-AA directly instead of
    // tessellating to a generic path.
    fn fill_rounded_rect(&mut self, x: f64, y: f64, w: f64, h: f64, radius: f64) {
        let r = radius.clamp(0.0, (w / 2.0).min(h / 2.0)) as f32;
        self.emit_fill_rect(x, y, w, h, Some([r, r, r, r]));
    }
    fn stroke_rounded_rect(&mut self, x: f64, y: f64, w: f64, h: f64, radius: f64) {
        let r = radius.clamp(0.0, (w / 2.0).min(h / 2.0)) as f32;
        let rect = KRect::new(x, y, x + w, y + h);
        let stroke = self.current_stroke();
        let brush = self.effective_stroke_brush();
        self.scene.push(DrawCommand::StrokeRect {
            rect,
            radii: Some([r, r, r, r]),
            stroke,
            brush,
            transform: self.transform,
        });
    }
}

// ── Masking ────────────────────────────────────────────────────────────────

impl Masking for UrxRenderContext {
    fn clip(&mut self) {
        // urx_core's clip vocabulary is rect-only today; convert the current
        // path's AABB to a rect clip. Generic-path clipping is a future
        // DrawCommand extension — when added, swap the AABB approximation
        // for a true `PushClipPath` op.
        if self.path.elements().is_empty() { return; }
        use kurbo::Shape;
        let bbox = self.path.bounding_box();
        self.scene.push(DrawCommand::PushClipRect {
            rect:      bbox,
            transform: self.transform,
        });
        self.clip_pushes = self.clip_pushes.saturating_add(1);
    }

    fn clip_rect(&mut self, x: f64, y: f64, width: f64, height: f64) {
        self.scene.push(DrawCommand::PushClipRect {
            rect:      KRect::new(x, y, x + width, y + height),
            transform: self.transform,
        });
        self.clip_pushes = self.clip_pushes.saturating_add(1);
    }
}

// ── Effects ────────────────────────────────────────────────────────────────

impl Effects for UrxRenderContext {
    fn set_shadow(&mut self, dx: f64, dy: f64, _blur: f64, color: &str) {
        // Blur is approximated as a translated copy (matches the
        // vello-cpu/gpu approach until urx_core gains a blur op).
        self.shadow = Some(ShadowState { dx, dy, color: parse_color(color) });
    }
    fn clear_shadow(&mut self) { self.shadow = None; }
    fn set_blend_mode(&mut self, mode: UzorBlendMode) { self.blend_mode = mode; }
}

// ── Gradient ───────────────────────────────────────────────────────────────

fn build_gradient_stops(stops: &[(f32, &str)]) -> ColorStops {
    let v: Vec<ColorStop> = stops
        .iter()
        .map(|(o, hex)| ColorStop { offset: *o, color: parse_color(hex).into() })
        .collect();
    ColorStops::from(v.as_slice())
}

impl GradientPainter for UrxRenderContext {
    /// Paints the CURRENT path (built via `begin_path()`/`rect()`/etc.,
    /// same as `fill()`) with a linear gradient — immediately, not
    /// stashed for a later `fill()` call. This matches EVERY other uzor
    /// backend's own `GradientPainter` impl (`uzor-render-tiny-skia`,
    /// `uzor-render-vello-{cpu,gpu,hybrid}` all take the path, tessellate/
    /// rasterise it, and consume it right here — see their own
    /// `fill_linear_gradient` bodies) and the documented contract
    /// `uzor::core::render::svg::draw_svg_multicolor` relies on ("vello's
    /// fill()/stroke()/fill_linear_gradient() consume the path").
    ///
    /// A prior version of this method stashed the gradient into a
    /// `self.fill_gradient: Option<Gradient>` field for the NEXT `fill()`
    /// call to consume — which meant a caller that (correctly, per every
    /// other backend's contract) never called a separate `fill()`
    /// afterward painted NOTHING here, and the stashed gradient then
    /// leaked into whatever fill-brush-consuming call came next (a
    /// `fill_rect`/`fill()`/glyph draw with its own, unrelated solid
    /// color got silently painted with this gradient instead). That
    /// field is gone entirely now — there is no pending state left to
    /// leak, structurally, not just by convention.
    fn fill_linear_gradient(
        &mut self,
        stops: &[(f32, &str)],
        x1: f64, y1: f64, x2: f64, y2: f64,
    ) {
        if stops.is_empty() { return; }
        let kind = LinearGradientPosition {
            start: KPoint::new(x1, y1),
            end:   KPoint::new(x2, y2),
        };
        let g = Gradient {
            kind:   kind.into(),
            stops:  build_gradient_stops(stops),
            extend: Extend::Pad,
            ..Gradient::default()
        };
        let brush = self.gradient_brush(g);
        self.emit_fill_path(brush);
    }

    /// Same immediate-consume contract as `fill_linear_gradient` above —
    /// see that method's own doc comment for the full reasoning.
    fn fill_radial_gradient(
        &mut self,
        cx: f64, cy: f64, r: f64,
        stops: &[(f32, &str)],
        _x: f64, _y: f64, _w: f64, _h: f64,
    ) {
        if stops.is_empty() { return; }
        let kind = RadialGradientPosition {
            start_center: KPoint::new(cx, cy),
            start_radius: 0.0,
            end_center:   KPoint::new(cx, cy),
            end_radius:   r as f32,
        };
        let g = Gradient {
            kind:   kind.into(),
            stops:  build_gradient_stops(stops),
            extend: Extend::Pad,
            ..Gradient::default()
        };
        let brush = self.gradient_brush(g);
        self.emit_fill_path(brush);
    }
}

// ── BatchPainter ────────────────────────────────────────────────────────────

impl BatchPainter for UrxRenderContext {
    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 stroke = self.current_stroke();
        let brush = self.effective_stroke_brush();
        let segments = lines.iter().map(|line| LineBatchSegment {
            from: Vec2::new(line.x1, line.y1),
            to:   Vec2::new(line.x2, line.y2),
        }).collect();
        self.scene.push(DrawCommand::LineBatch {
            segments,
            stroke,
            brush,
            transform: self.transform,
        });
    }
    fn draw_circle_batch(&mut self, circles: &[CircleBatch], color: &str) {
        if circles.is_empty() { return; }
        self.set_fill_color(color);
        let brush = self.effective_fill_brush();
        for c in circles {
            self.scene.push(DrawCommand::FillRect {
                rect: KRect::new(c.cx - c.r, c.cy - c.r, c.cx + c.r, c.cy + c.r),
                radii: Some([c.r as f32; 4]),
                brush: brush.clone(),
                transform: self.transform,
            });
        }
    }
}

// ── GlyphRun bridging (URX text-gamma follow-up, 2026-07-24) ───────────────
//
// `fill_text` used to ALWAYS render text as a vector-outline path
// (`DrawCommand::FillPath`) — see the historical note kept on
// `fill_path_segment`'s own doc comment for why that was the original
// choice and why it's no longer a structural blocker. It now emits
// `DrawCommand::GlyphRun` (the SAME hinted-swash atlas path the crate-
// level parity suite already proves byte-tight CPU-vs-native, glyph
// fixture 0.000%) whenever it safely can, falling back to the outline
// path only for the two cases that genuinely cannot map onto a
// glyph-id run — both counted, never silent (see `emit_text_segments`
// and `fill_text`'s own transform check).

/// Process-wide cache: `uzor::shaper::ShaperFontId` (cosmic-text's own
/// per-face identity) -> `uzor_urx_glyph::FontId` (URX's own glyph-atlas
/// registry identity). `uzor_urx_glyph::register_font` mints a NEW,
/// distinct `FontId` on every call (not idempotent by content — see its
/// own doc comment) — without this cache, drawing the same font twice
/// would register it twice, breaking `GlyphKey`-based atlas/LRU cache
/// reuse across draws (every `GlyphKey` embeds the `FontId`, so two
/// registrations of the byte-identical font would never hit each
/// other's cached rasterisations).
fn font_id_cache() -> &'static Mutex<HashMap<uzor::shaper::ShaperFontId, FontId>> {
    static CACHE: OnceLock<Mutex<HashMap<uzor::shaper::ShaperFontId, FontId>>> = OnceLock::new();
    CACHE.get_or_init(|| Mutex::new(HashMap::new()))
}

/// Resolve (registering into `uzor_urx_glyph`'s registry on first use)
/// the `FontId` for a shaped segment's font. `None` only if the
/// process-wide font database somehow no longer has the face, or
/// `register_font` rejects bytes that JUST successfully shaped text via
/// cosmic-text moments earlier (should not happen either way — a
/// defensive `None`, not an expected outcome).
///
/// Holds the cache's lock across the ENTIRE check-then-register-then-
/// insert sequence (never releases it between the miss check and the
/// insert) — a `check, unlock, register, re-lock, insert` version of
/// this function would race two concurrent callers seeing the SAME
/// miss and each registering (and caching) their OWN distinct `FontId`
/// for the byte-identical font, silently defeating the whole point of
/// this cache (confirmed empirically: an earlier check-then-insert
/// version of this function passed in isolation but flaked under
/// `cargo test`'s default parallel-thread execution).
fn resolve_font_id(shaper_font: uzor::shaper::ShaperFontId) -> Option<FontId> {
    let mut cache = font_id_cache().lock().ok()?;
    if let Some(&id) = cache.get(&shaper_font) {
        return Some(id);
    }
    let bytes = uzor::shaper::font_bytes_for(shaper_font)?;
    let id = uzor_urx_glyph::register_font(bytes).ok()?;
    cache.insert(shaper_font, id);
    Some(id)
}

/// Family names in this workspace's EMBEDDED font set whose glyphs a
/// monochrome-coverage rasteriser (`uzor_urx_glyph::draw_glyph_run`,
/// `swash::zeno::Format::Alpha`-only — see its own module doc: "COLR/
/// CBDT/CBLC colour glyphs — deferred") cannot represent. Only
/// `uzor_fonts::NOTO_COLOR_EMOJI` qualifies (the embedded `NOTO_EMOJI`
/// — no "Color" — is a plain monochrome outline font and renders
/// through `GlyphRun` exactly like any other face).
const COLOR_GLYPH_FAMILIES: &[&str] = &["Noto Color Emoji"];

fn is_color_glyph_font(shaper_font: uzor::shaper::ShaperFontId) -> bool {
    uzor::shaper::font_family_for(shaper_font)
        .is_some_and(|family| COLOR_GLYPH_FAMILIES.contains(&family.as_str()))
}

/// `DrawCommand::GlyphRun`'s `transform` is translate-ONLY downstream —
/// both `uzor-urx-cpu::draw_glyph_run` and `uzor-urx-wgpu::encode_glyph_run`
/// extract ONLY the translation component (design's own deliberate
/// CPU/GPU parity choice, Wave 2). A non-identity LINEAR part (scale /
/// rotate / shear) on the CURRENT canvas transform can't be represented
/// that way — `fill_text` checks this before choosing the `GlyphRun`
/// path (falls back to the vector-outline path, counted, when false).
fn is_translation_only(t: KAffine) -> bool {
    let c = t.as_coeffs();
    const EPS: f64 = 1e-6;
    (c[0] - 1.0).abs() < EPS && c[1].abs() < EPS && c[2].abs() < EPS && (c[3] - 1.0).abs() < EPS
}

// ── TextRenderer ───────────────────────────────────────────────────────────

impl TextRenderer for UrxRenderContext {
    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_str = font_string(&self.font_info);
        let total_w  = self.measure_text(text);
        let x_off = match self.text_align {
            TextAlign::Center => -total_w / 2.0,
            TextAlign::Right  => -total_w,
            _ => 0.0,
        };
        // Exhaustive match (no `_` wildcard) — `TextBaseline::Alphabetic`
        // used to silently fall into a wildcard arm that applied
        // `Middle`'s offset (an extra `size * 0.35` shift downward).
        // "Alphabetic" means the caller's own `y` IS ALREADY the
        // baseline (standard Canvas2D/CSS definition) — correct offset
        // is `0.0`, same as `Bottom`. `uzor-render-vello-cpu` had the
        // IDENTICAL bug (fixed the same pass, 2026-07-24, while
        // calibrating the typography fixture's line positions against
        // it) — fixing only one side would have introduced a NEW
        // baseline disagreement between the two legs instead of
        // removing one.
        let y_off = match self.text_baseline {
            TextBaseline::Top        => self.font_info.size as f64 * 0.8,
            TextBaseline::Middle     => self.font_info.size as f64 * 0.35,
            TextBaseline::Bottom     => 0.0,
            TextBaseline::Alphabetic => 0.0,
        };
        let text_xform = KAffine::translate((x + x_off, y + y_off));
        let combined   = self.transform * text_xform;

        if !is_translation_only(self.transform) {
            metrics::counter!(
                uzor_urx_core::metrics_keys::KEY_RENDER_PRIMITIVES,
                "kind" => "urx_filltext_glyphrun_transform_fallback",
            ).increment(1);
            self.fill_text_as_path(text, &font_str, combined);
            return;
        }

        let segments = uzor::shaper::shape_glyph_runs(text, &font_str);
        if segments.is_empty() {
            // Nothing shaped (e.g. whitespace-only text) — nothing to
            // fall back to either; same silent no-op Canvas2D itself
            // has for invisible content.
            return;
        }

        if let Some(sh) = self.shadow.clone() {
            let shadow_xform = combined.then_translate(Vec2::new(sh.dx, sh.dy));
            let shadow_brush = PenikoBrush::Solid(apply_alpha(sh.color, self.global_alpha));
            self.emit_text_segments(&segments, &font_str, shadow_brush, shadow_xform);
        }
        let brush = self.effective_fill_brush();
        self.emit_text_segments(&segments, &font_str, brush, combined);
    }
}

impl UrxRenderContext {
    /// Emit one `DrawCommand::GlyphRun` per segment (registering/caching
    /// a `FontId` for each distinct font on first use). Color-glyph
    /// segments (`is_color_glyph_font`) and segments whose font bytes
    /// are unexpectedly unavailable both fall back to the vector-outline
    /// path for JUST that segment — shifted to the segment's own
    /// starting pen position — never silently dropped (both counted).
    fn emit_text_segments(
        &mut self,
        segments: &[uzor::shaper::GlyphSegment],
        font_str: &str,
        brush: PenikoBrush,
        transform: KAffine,
    ) {
        for seg in segments {
            let seg_origin_x = seg.glyphs.first().map(|g| g.x as f64).unwrap_or(0.0);

            if is_color_glyph_font(seg.font) {
                metrics::counter!(
                    uzor_urx_core::metrics_keys::KEY_RENDER_PRIMITIVES,
                    "kind" => "urx_filltext_glyphrun_color_font_fallback",
                ).increment(1);
                self.fill_path_segment(&seg.text, font_str, brush.clone(), transform.then_translate(Vec2::new(seg_origin_x, 0.0)));
                continue;
            }

            let Some(font_id) = resolve_font_id(seg.font) else {
                metrics::counter!(
                    uzor_urx_core::metrics_keys::KEY_RENDER_PRIMITIVES,
                    "kind" => "urx_filltext_glyphrun_font_bytes_unavailable",
                ).increment(1);
                self.fill_path_segment(&seg.text, font_str, brush.clone(), transform.then_translate(Vec2::new(seg_origin_x, 0.0)));
                continue;
            };

            let glyphs: Vec<Glyph> =
                seg.glyphs.iter().map(|g| Glyph { glyph_id: g.glyph_id, x: g.x, y: g.y }).collect();
            self.scene.push(DrawCommand::GlyphRun {
                glyphs,
                font: font_id,
                font_size: seg.font_size,
                brush: brush.clone(),
                transform,
                text: Some(seg.text.clone()),
            });
        }
    }

    /// Whole-call vector-outline fallback (non-translation transform
    /// case) — same shadow-then-main sequencing `fill_text` always used
    /// before this change.
    fn fill_text_as_path(&mut self, text: &str, font_str: &str, transform: KAffine) {
        if let Some(sh) = self.shadow.clone() {
            let shadow_xform = transform.then_translate(Vec2::new(sh.dx, sh.dy));
            self.fill_path_segment(text, font_str, PenikoBrush::Solid(apply_alpha(sh.color, self.global_alpha)), shadow_xform);
        }
        let brush = self.effective_fill_brush();
        self.fill_path_segment(text, font_str, brush, transform);
    }

    /// Render `text` as a vector-outline path via `shaper::text_to_path`
    /// (SVG path string) → `kurbo::BezPath` → `DrawCommand::FillPath`.
    /// This was `fill_text`'s ONLY path before this change — `uzor::shaper`
    /// exposed cluster-level metrics only (`GlyphMetric` has
    /// `x_offset/advance`, not a raw `glyph_id`), so there was no glyph
    /// identity to build a `DrawCommand::GlyphRun` from. That gap closed
    /// when `uzor::shaper::shape_glyph_runs` was added (cosmic-text's own
    /// `LayoutGlyph.glyph_id`/`.font_id` were ALWAYS available internally
    /// — `text_to_path_uncached` already threads the same `glyph_id`
    /// into `SwashCache::get_outline_commands` to build ITS OWN outlines
    /// — just never surfaced to a caller before). This function now
    /// serves only the two genuinely-can't-map cases above.
    fn fill_path_segment(&mut self, text: &str, font_str: &str, brush: PenikoBrush, transform: KAffine) {
        let svg = uzor::shaper::text_to_path(text, font_str);
        if svg.is_empty() { return; }
        let Ok(path) = BezPath::from_svg(&svg) else { return; };
        self.scene.push(DrawCommand::FillPath { path, rule: FillRule::NonZero, brush, transform });
    }
}

fn font_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(" ")
}

// ── TextMetrics ────────────────────────────────────────────────────────────

impl TextMetrics for UrxRenderContext {
    fn measure_text(&self, text: &str) -> f64 {
        let m = uzor::shaper::measure_glyphs(text, &font_string(&self.font_info));
        m.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 m = uzor::shaper::measure_glyphs(text, &font_string(&info));
        let w = m.last().map(|g| g.x_offset + g.advance).unwrap_or(0.0);
        let ascent  = info.size as f64 * 0.9;
        let descent = info.size as f64 * 0.3;
        TextBounds {
            x: 0.0, y: -ascent, w, h: ascent + descent, ascent, descent,
        }
    }

    fn measure_text_glyphs(&self, text: &str, font: &str) -> Vec<GlyphMetric> {
        uzor::shaper::measure_glyphs(text, font)
    }

    /// Real word-wrap via cosmic-text `Wrap::Word` (same delegation as the
    /// other shaper-backed backends; the trait default is a greedy
    /// heuristic).
    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)
    }
}

// ── UiEffectHelpers (all methods have default impls — empty block) ─────────

impl UiEffectHelpers for UrxRenderContext {}

// ── RenderContext supertrait ───────────────────────────────────────────────

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

impl RenderContextExt for UrxRenderContext {
    type BlurImage = ();
}

// ── Tests ──────────────────────────────────────────────────────────────────

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn solid_line_batch_emits_one_line_batch() {
        let mut ctx = UrxRenderContext::new(1.0);
        ctx.begin_frame(100, 100);
        BatchPainter::draw_line_batch(
            &mut ctx,
            &[
                LineSegment { x1: 1.0, y1: 2.0, x2: 3.0, y2: 4.0 },
                LineSegment { x1: 5.0, y1: 6.0, x2: 7.0, y2: 8.0 },
            ],
            "#ffffff",
            1.5,
        );

        let scene = ctx.take_scene();
        assert_eq!(scene.commands.len(), 1);
        assert!(matches!(
            &scene.commands[0],
            DrawCommand::LineBatch { segments, stroke, .. }
                if segments.len() == 2
                    && segments[0].from == Vec2::new(1.0, 2.0)
                    && segments[0].to == Vec2::new(3.0, 4.0)
                    && segments[1].from == Vec2::new(5.0, 6.0)
                    && segments[1].to == Vec2::new(7.0, 8.0)
                    && stroke.dash.is_none()
        ));
    }

    #[test]
    fn dashed_line_batch_retains_batch_stroke_semantics() {
        let mut ctx = UrxRenderContext::new(1.0);
        ctx.begin_frame(100, 100);
        Painter::set_line_dash(&mut ctx, &[8.0, 5.0]);
        BatchPainter::draw_line_batch(
            &mut ctx,
            &[
                LineSegment { x1: 1.0, y1: 2.0, x2: 3.0, y2: 4.0 },
                LineSegment { x1: 5.0, y1: 6.0, x2: 7.0, y2: 8.0 },
            ],
            "#ffffff",
            1.5,
        );

        let scene = ctx.take_scene();
        assert_eq!(scene.commands.len(), 1);
        assert!(matches!(
            &scene.commands[0],
            DrawCommand::LineBatch { segments, stroke, .. }
                if segments.len() == 2 && stroke.dash.is_some()
        ));
    }

    #[test]
    fn circle_batch_emits_sdf_round_rects_with_original_geometry() {
        let mut ctx = UrxRenderContext::new(1.0);
        ctx.begin_frame(100, 100);
        BatchPainter::draw_circle_batch(
            &mut ctx,
            &[
                CircleBatch { cx: 10.0, cy: 20.0, r: 3.0 },
                CircleBatch { cx: 40.0, cy: 50.0, r: 7.5 },
            ],
            "#ffffff",
        );

        let scene = ctx.take_scene();
        assert_eq!(scene.commands.len(), 2);
        let expected = [
            (KRect::new(7.0, 17.0, 13.0, 23.0), [3.0; 4]),
            (KRect::new(32.5, 42.5, 47.5, 57.5), [7.5; 4]),
        ];
        for (command, (expected_rect, expected_radii)) in scene.commands.iter().zip(expected) {
            match command {
                DrawCommand::FillRect { rect, radii: Some(radii), .. } => {
                    assert_eq!(*rect, expected_rect);
                    assert_eq!(*radii, expected_radii);
                }
                other => panic!("expected SDF FillRect circle, got {:?}", other),
            }
        }
        assert!(!scene.commands.iter().any(|command| matches!(command, DrawCommand::FillPath { .. })));
    }

    #[test]
    fn recycle_scene_keeps_command_capacity() {
        let mut ctx = UrxRenderContext::new(1.0);
        ctx.begin_frame(100, 100);
        for x in 0..32 {
            ShapeHelpers::fill_rect(&mut ctx, x as f64, 0.0, 1.0, 1.0);
        }
        let capacity = ctx.scene.commands.capacity();

        ctx.recycle_scene();

        assert!(ctx.scene.commands.is_empty());
        assert_eq!(ctx.scene.commands.capacity(), capacity);
    }

    #[test]
    fn begin_frame_advances_revision_and_reuses_scene_capacity() {
        let mut ctx = UrxRenderContext::new(1.0);
        assert_eq!(ctx.revision(), 0);

        ctx.begin_frame(100, 100);
        let first_revision = ctx.revision();
        for x in 0..32 {
            ShapeHelpers::fill_rect(&mut ctx, x as f64, 0.0, 1.0, 1.0);
        }
        let capacity = ctx.scene().commands.capacity();

        ctx.begin_frame(200, 150);

        assert_eq!(ctx.revision(), first_revision + 1);
        assert!(ctx.scene().is_empty());
        assert_eq!(ctx.scene().commands.capacity(), capacity);
        assert_eq!(ctx.size(), (200, 150));
    }

    #[test]
    fn retained_scene_and_revision_survive_read_only_access() {
        let mut ctx = UrxRenderContext::new(1.0);
        ctx.begin_frame(100, 100);
        ShapeHelpers::fill_rect(&mut ctx, 1.0, 2.0, 3.0, 4.0);
        let revision = ctx.revision();

        assert_eq!(ctx.scene().len(), 1);
        assert_eq!(ctx.scene().len(), 1);
        assert_eq!(ctx.revision(), revision);
    }

    #[test]
    fn full_circle_stroke_emits_native_rounded_stroke_rect() {
        let mut ctx = UrxRenderContext::new(1.0);
        ctx.begin_frame(100, 100);
        Painter::begin_path(&mut ctx);
        Painter::arc(&mut ctx, 30.0, 40.0, 12.0, 0.0, std::f64::consts::TAU);
        Painter::stroke(&mut ctx);

        assert!(matches!(
            &ctx.scene().commands[..],
            [DrawCommand::StrokeRect {
                rect,
                radii: Some(radii),
                ..
            }] if *rect == KRect::new(18.0, 28.0, 42.0, 52.0)
                && *radii == [12.0; 4]
        ));
    }

    #[test]
    fn partial_or_extended_circle_path_keeps_generic_stroke_semantics() {
        let mut ctx = UrxRenderContext::new(1.0);
        ctx.begin_frame(100, 100);
        Painter::begin_path(&mut ctx);
        Painter::arc(&mut ctx, 30.0, 40.0, 12.0, 0.0, std::f64::consts::PI);
        Painter::line_to(&mut ctx, 30.0, 40.0);
        Painter::stroke(&mut ctx);

        assert!(matches!(
            &ctx.scene().commands[..],
            [DrawCommand::StrokePath { .. }]
        ));
    }

    #[test]
    fn dashed_full_circle_keeps_generic_path_dash_phase() {
        let mut ctx = UrxRenderContext::new(1.0);
        ctx.begin_frame(100, 100);
        Painter::set_line_dash(&mut ctx, &[4.0, 3.0]);
        Painter::begin_path(&mut ctx);
        Painter::arc(&mut ctx, 30.0, 40.0, 12.0, 0.0, std::f64::consts::TAU);
        Painter::stroke(&mut ctx);

        assert!(matches!(
            &ctx.scene().commands[..],
            [DrawCommand::StrokePath { stroke, .. }] if stroke.dash.is_some()
        ));
    }
    use uzor::render::Painter;

    #[test]
    fn fill_rect_emits_one_fillrect() {
        let mut ctx = UrxRenderContext::new(1.0);
        ctx.begin_frame(100, 100);
        ctx.set_fill_color("#ff0000");
        ShapeHelpers::fill_rect(&mut ctx, 10.0, 20.0, 30.0, 40.0);
        let scene = ctx.take_scene();
        assert_eq!(scene.commands.len(), 1);
        match &scene.commands[0] {
            DrawCommand::FillRect { rect, .. } => {
                assert_eq!(rect.x0, 10.0);
                assert_eq!(rect.y0, 20.0);
                assert_eq!(rect.x1, 40.0);
                assert_eq!(rect.y1, 60.0);
            }
            other => panic!("expected FillRect, got {:?}", other),
        }
    }

    #[test]
    fn set_line_dash_carries_the_pattern_onto_the_emitted_stroke_path() {
        let mut ctx = UrxRenderContext::new(1.0);
        ctx.begin_frame(100, 100);
        ctx.set_stroke_color("#ffffff");
        Painter::set_line_dash(&mut ctx, &[5.0, 3.0]);
        ctx.begin_path();
        ctx.move_to(0.0, 0.0);
        ctx.line_to(10.0, 0.0);
        Painter::stroke(&mut ctx);
        let scene = ctx.take_scene();
        assert_eq!(scene.commands.len(), 1);
        match &scene.commands[0] {
            DrawCommand::StrokePath { stroke, .. } => {
                let dash = stroke.dash.as_ref().expect("dashed stroke() must carry a Some(Dash)");
                assert_eq!(dash.pattern, vec![5.0, 3.0]);
            }
            other => panic!("expected StrokePath, got {:?}", other),
        }
    }

    #[test]
    fn set_line_dash_empty_clears_a_previously_set_pattern() {
        let mut ctx = UrxRenderContext::new(1.0);
        ctx.begin_frame(100, 100);
        ctx.set_stroke_color("#ffffff");
        Painter::set_line_dash(&mut ctx, &[5.0, 3.0]);
        Painter::set_line_dash(&mut ctx, &[]);
        ctx.begin_path();
        ctx.move_to(0.0, 0.0);
        ctx.line_to(10.0, 0.0);
        Painter::stroke(&mut ctx);
        let scene = ctx.take_scene();
        match &scene.commands[0] {
            DrawCommand::StrokePath { stroke, .. } => {
                assert!(stroke.dash.is_none(), "an empty pattern must clear dashing back to solid");
            }
            other => panic!("expected StrokePath, got {:?}", other),
        }
    }

    #[test]
    fn save_restore_pops_pushed_clip() {
        let mut ctx = UrxRenderContext::new(1.0);
        ctx.begin_frame(100, 100);
        ctx.save();
        ctx.clip_rect(0.0, 0.0, 50.0, 50.0);
        ctx.restore();
        let scene = ctx.take_scene();
        // Should be exactly 2 ops: PushClipRect + PopClip.
        assert_eq!(scene.commands.len(), 2);
        assert!(matches!(scene.commands[0], DrawCommand::PushClipRect { .. }));
        assert!(matches!(scene.commands[1], DrawCommand::PopClip));
    }

    #[test]
    fn path_fill_emits_fillpath() {
        let mut ctx = UrxRenderContext::new(1.0);
        ctx.begin_frame(100, 100);
        ctx.set_fill_color("#0000ff");
        ctx.begin_path();
        ctx.move_to(0.0, 0.0);
        ctx.line_to(10.0, 0.0);
        ctx.line_to(10.0, 10.0);
        ctx.close_path();
        Painter::fill(&mut ctx);
        let scene = ctx.take_scene();
        assert_eq!(scene.commands.len(), 1);
        assert!(matches!(scene.commands[0], DrawCommand::FillPath { .. }));
    }

    // ── GradientPainter (bug fix 2026-07-25: gradient fills were never
    // emitted + leaked into the next fill-brush-consuming call) ─────────

    /// `fill_linear_gradient` must emit exactly one `FillPath` carrying
    /// a `Brush::Gradient` (not a bare no-op that leaves the shape
    /// unpainted, and not a stashed no-command state waiting for a
    /// caller to separately call `fill()`).
    #[test]
    fn fill_linear_gradient_emits_a_gradient_fillpath() {
        let mut ctx = UrxRenderContext::new(1.0);
        ctx.begin_frame(100, 100);
        ctx.begin_path();
        ctx.rect(0.0, 0.0, 20.0, 10.0);
        GradientPainter::fill_linear_gradient(
            &mut ctx,
            &[(0.0, "#ff0000"), (1.0, "#0000ff")],
            0.0, 0.0, 20.0, 0.0,
        );
        let scene = ctx.take_scene();
        assert_eq!(scene.commands.len(), 1, "the gradient fill must emit its own draw command, not silently no-op");
        match &scene.commands[0] {
            DrawCommand::FillPath { brush, .. } => {
                assert!(matches!(brush, PenikoBrush::Gradient(_)), "expected a Gradient brush, got {:?}", brush);
            }
            other => panic!("expected FillPath, got {:?}", other),
        }
    }

    /// Same immediate-emit contract for `fill_radial_gradient`.
    #[test]
    fn fill_radial_gradient_emits_a_gradient_fillpath() {
        let mut ctx = UrxRenderContext::new(1.0);
        ctx.begin_frame(100, 100);
        ctx.begin_path();
        ctx.rect(0.0, 0.0, 20.0, 20.0);
        GradientPainter::fill_radial_gradient(
            &mut ctx,
            10.0, 10.0, 10.0,
            &[(0.0, "#ff0000"), (1.0, "#0000ff")],
            0.0, 0.0, 20.0, 20.0,
        );
        let scene = ctx.take_scene();
        assert_eq!(scene.commands.len(), 1);
        match &scene.commands[0] {
            DrawCommand::FillPath { brush, .. } => {
                assert!(matches!(brush, PenikoBrush::Gradient(_)), "expected a Gradient brush, got {:?}", brush);
            }
            other => panic!("expected FillPath, got {:?}", other),
        }
    }

    /// The defect's own reported shape: a gradient fill followed by an
    /// UNRELATED solid fill must leave the solid fill with its OWN
    /// color — never the gradient (the exact leak the coordinator saw
    /// on `figures_heatmap_backends.png`'s `"36.00"` tick label,
    /// painted in the colorbar gradient's first-stop orange instead of
    /// the theme's white). With the `fill_gradient` stash field removed
    /// entirely, there is no state left to leak — this test pins that.
    #[test]
    fn gradient_fill_does_not_leak_into_the_next_solid_fill() {
        let mut ctx = UrxRenderContext::new(1.0);
        ctx.begin_frame(100, 100);

        // First: a gradient-filled rect (mirrors uzor-figures's colorbar:
        // begin_path -> rect -> fill_linear_gradient, no separate fill()).
        ctx.begin_path();
        ctx.rect(0.0, 0.0, 20.0, 10.0);
        GradientPainter::fill_linear_gradient(
            &mut ctx,
            &[(0.0, "#ff8000"), (1.0, "#000000")],
            0.0, 0.0, 20.0, 0.0,
        );

        // Second: an UNRELATED solid-color fill (mirrors the colorbar's
        // own next call — `ctx.set_fill_color(&theme.label_color);
        // ctx.fill_text(...)`, which routes through `effective_fill_brush`
        // exactly like a plain `fill()` would).
        ctx.set_fill_color("#ffffff");
        ctx.begin_path();
        ctx.rect(30.0, 0.0, 10.0, 10.0);
        Painter::fill(&mut ctx);

        let scene = ctx.take_scene();
        assert_eq!(scene.commands.len(), 2);
        assert!(matches!(scene.commands[0], DrawCommand::FillPath { brush: PenikoBrush::Gradient(_), .. }));
        match &scene.commands[1] {
            DrawCommand::FillPath { brush: PenikoBrush::Solid(c), .. } => {
                assert_eq!(*c, Color::from_rgba8(255, 255, 255, 255), "the second fill must use ITS OWN white, not the gradient's orange leaking through");
            }
            other => panic!("expected a solid-white FillPath, got {:?}", other),
        }
    }

    #[test]
    fn transform_translate_propagates_to_emitted_op() {
        let mut ctx = UrxRenderContext::new(1.0);
        ctx.begin_frame(100, 100);
        ctx.translate(5.0, 7.0);
        ctx.set_fill_color("#00ff00");
        ShapeHelpers::fill_rect(&mut ctx, 0.0, 0.0, 10.0, 10.0);
        let scene = ctx.take_scene();
        match &scene.commands[0] {
            DrawCommand::FillRect { transform, .. } => {
                // The translate ends up as the last column of the Affine.
                let coeffs = transform.as_coeffs();
                assert_eq!(coeffs[4], 5.0);
                assert_eq!(coeffs[5], 7.0);
            }
            _ => panic!("expected FillRect"),
        }
    }

    // ── Defensive subpath-open invariants (2026-06-09 owner-driven) ──
    //
    // kurbo's BezPath panics on any append after an empty or just-
    // closed path. Canvas2D semantics tolerate every path-op as a
    // fresh-subpath starter. UrxRenderContext bridges the two —
    // these tests pin that bridge.

    // Direct-call tests on the inherent impl block (the UzorRenderContext
    // trait impls invoke the same path-op methods). UrxRenderContext
    // exposes them via the trait — UFCS isn't available because the
    // RenderContext supertrait composition causes ambiguity; we exercise
    // via the trait object instead.

    #[test]
    fn arc_on_empty_path_does_not_panic() {
        // Before the fix this panicked with "BezPath must begin with MoveTo".
        let mut ctx = UrxRenderContext::new(1.0);
        ctx.begin_frame(100, 100);
        let rc: &mut dyn uzor::render::RenderContext = &mut ctx;
        rc.begin_path();
        rc.arc(50.0, 50.0, 20.0, 0.0, std::f64::consts::PI);
        rc.stroke();
        let scene = ctx.take_scene();
        assert!(scene.commands.iter().any(|c| matches!(c, DrawCommand::StrokePath { .. })));
    }

    #[test]
    fn ellipse_on_empty_path_does_not_panic() {
        let mut ctx = UrxRenderContext::new(1.0);
        ctx.begin_frame(100, 100);
        let rc: &mut dyn uzor::render::RenderContext = &mut ctx;
        rc.begin_path();
        rc.ellipse(50.0, 50.0, 20.0, 30.0, 0.0, 0.0, std::f64::consts::TAU);
        rc.fill();
        let _ = ctx.take_scene();
    }

    #[test]
    fn line_to_on_empty_path_does_not_panic() {
        let mut ctx = UrxRenderContext::new(1.0);
        ctx.begin_frame(100, 100);
        let rc: &mut dyn uzor::render::RenderContext = &mut ctx;
        rc.begin_path();
        rc.line_to(10.0, 20.0);
        rc.line_to(30.0, 40.0);
        rc.stroke();
        let _ = ctx.take_scene();
    }

    #[test]
    fn close_path_on_empty_is_silent_noop() {
        let mut ctx = UrxRenderContext::new(1.0);
        ctx.begin_frame(100, 100);
        let rc: &mut dyn uzor::render::RenderContext = &mut ctx;
        rc.begin_path();
        rc.close_path();
        let _ = ctx.take_scene();
    }

    #[test]
    fn bezier_after_close_does_not_panic() {
        let mut ctx = UrxRenderContext::new(1.0);
        ctx.begin_frame(100, 100);
        let rc: &mut dyn uzor::render::RenderContext = &mut ctx;
        rc.begin_path();
        rc.move_to(10.0, 10.0);
        rc.line_to(20.0, 20.0);
        rc.close_path();
        rc.bezier_curve_to(30.0, 30.0, 40.0, 40.0, 50.0, 50.0);
        rc.stroke();
        let _ = ctx.take_scene();
    }

    // ── GlyphRun bridging (2026-07-24 follow-up) ─────────────────────

    /// The whole point of this change: plain text under an identity/
    /// translation-only transform must emit `GlyphRun`, never
    /// `FillPath`, now.
    #[test]
    fn fill_text_emits_glyph_run_not_fillpath() {
        let mut ctx = UrxRenderContext::new(1.0);
        ctx.begin_frame(200, 100);
        ctx.set_fill_color("#ffffff");
        TextRenderer::set_font(&mut ctx, "16px Roboto");
        TextRenderer::fill_text(&mut ctx, "Hello", 10.0, 20.0);
        let scene = ctx.take_scene();
        assert_eq!(scene.commands.len(), 1, "one segment (one font) -> exactly one GlyphRun");
        match &scene.commands[0] {
            DrawCommand::GlyphRun { glyphs, font_size, text, .. } => {
                assert_eq!(glyphs.len(), 5, "one glyph per character, no ligatures in \"Hello\"");
                assert_eq!(*font_size, 16.0);
                assert_eq!(text.as_deref(), Some("Hello"));
            }
            other => panic!("expected GlyphRun, got {:?}", other),
        }
    }

    /// The `GlyphRun`'s own `transform` must carry the full `(x, y)`
    /// origin translation `fill_text` was called with (plus the
    /// baseline offset) — same contract `FillPath`'s transform used to
    /// carry, since CPU/GPU both read `coeffs[4]/[5]` off this value.
    #[test]
    fn fill_text_glyph_run_transform_carries_the_origin() {
        let mut ctx = UrxRenderContext::new(1.0);
        ctx.begin_frame(200, 100);
        ctx.set_fill_color("#ffffff");
        TextRenderer::set_font(&mut ctx, "16px Roboto");
        TextRenderer::set_text_baseline(&mut ctx, TextBaseline::Top);
        TextRenderer::fill_text(&mut ctx, "Hi", 30.0, 40.0);
        let scene = ctx.take_scene();
        match &scene.commands[0] {
            DrawCommand::GlyphRun { transform, .. } => {
                let c = transform.as_coeffs();
                assert_eq!(c[4], 30.0);
                assert!((c[5] - (40.0 + 16.0 * 0.8)).abs() < 1e-6, "Top baseline offset must be added: got {}", c[5]);
            }
            other => panic!("expected GlyphRun, got {:?}", other),
        }
    }

    /// Repeated `fill_text` calls with the SAME font must reuse the
    /// SAME `FontId` — proves the `font_id_cache` actually caches
    /// (never mints a second registration for a font already seen).
    #[test]
    fn fill_text_reuses_the_same_font_id_across_calls() {
        let mut ctx = UrxRenderContext::new(1.0);
        ctx.begin_frame(200, 100);
        ctx.set_fill_color("#ffffff");
        TextRenderer::set_font(&mut ctx, "16px Roboto");
        TextRenderer::fill_text(&mut ctx, "AB", 0.0, 20.0);
        TextRenderer::fill_text(&mut ctx, "CD", 0.0, 40.0);
        let scene = ctx.take_scene();
        assert_eq!(scene.commands.len(), 2);
        let font_id = |cmd: &DrawCommand| match cmd {
            DrawCommand::GlyphRun { font, .. } => *font,
            other => panic!("expected GlyphRun, got {:?}", other),
        };
        assert_eq!(font_id(&scene.commands[0]), font_id(&scene.commands[1]), "same font across two calls must reuse the SAME FontId");
    }

    /// A non-identity linear transform (scale) can't be represented by
    /// `GlyphRun`'s translate-only downstream contract — must fall back
    /// to `FillPath`, not silently drop the scale.
    #[test]
    fn fill_text_falls_back_to_fillpath_under_a_scale_transform() {
        let mut ctx = UrxRenderContext::new(1.0);
        ctx.begin_frame(200, 100);
        ctx.set_fill_color("#ffffff");
        Painter::scale(&mut ctx, 2.0, 2.0);
        TextRenderer::set_font(&mut ctx, "16px Roboto");
        TextRenderer::fill_text(&mut ctx, "Hi", 10.0, 20.0);
        let scene = ctx.take_scene();
        assert_eq!(scene.commands.len(), 1);
        assert!(matches!(scene.commands[0], DrawCommand::FillPath { .. }), "scaled text must fall back to FillPath, not silently drop the scale");
    }

    /// Shadow pre-pass still emits (as `GlyphRun` now, matching the
    /// main draw) BEFORE the main glyph run — same ordering the old
    /// FillPath shadow pre-pass used.
    #[test]
    fn fill_text_with_shadow_emits_shadow_then_main_glyph_run() {
        let mut ctx = UrxRenderContext::new(1.0);
        ctx.begin_frame(200, 100);
        ctx.set_fill_color("#ffffff");
        Effects::set_shadow(&mut ctx, 2.0, 2.0, 0.0, "#000000");
        TextRenderer::set_font(&mut ctx, "16px Roboto");
        TextRenderer::fill_text(&mut ctx, "Hi", 10.0, 20.0);
        let scene = ctx.take_scene();
        assert_eq!(scene.commands.len(), 2, "shadow pre-pass + main draw");
        assert!(matches!(scene.commands[0], DrawCommand::GlyphRun { .. }));
        assert!(matches!(scene.commands[1], DrawCommand::GlyphRun { .. }));
    }

    #[test]
    fn empty_text_emits_nothing() {
        let mut ctx = UrxRenderContext::new(1.0);
        ctx.begin_frame(200, 100);
        TextRenderer::set_font(&mut ctx, "16px Roboto");
        TextRenderer::fill_text(&mut ctx, "", 10.0, 20.0);
        let scene = ctx.take_scene();
        assert!(scene.commands.is_empty());
    }

    // -----------------------------------------------------------------
    // 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` 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. This test pins
    // the exact expected device-space mapping of a known local point so a
    // regression to `then_*` fails immediately, with no rendering
    // required.
    #[test]
    fn translate_then_rotate_matches_local_frame_composition() {
        let mut ctx = UrxRenderContext::new(1.0);
        ctx.begin_frame(100, 100);

        // 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.
        Painter::translate(&mut ctx, 10.0, 0.0);
        Painter::rotate(&mut ctx, std::f64::consts::FRAC_PI_2);

        let p = ctx.transform * KPoint::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 = UrxRenderContext::new(1.0);
        ctx.begin_frame(100, 100);

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

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

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