rhwp 0.9.1

HWP/HWPX document engine for Rust applications, WebAssembly, and CLI automation
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
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
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
use crate::model::style::UnderlineType;
use crate::model::ColorRef;
use crate::paint::font::{GlyphRunReplayEligibility, ShapeKey, TextDirection, WritingMode};
use crate::paint::layer_tree::{TextSourceRange, TextSourceSpan};
use crate::paint::resources::{ImageResourceId, ResourceArena, SvgResourceId};
use crate::renderer::render_tree::{
    BoundingBox, EllipseNode, EquationNode, FootnoteMarkerNode, FormObjectNode, ImageNode,
    LineNode, PageBackgroundNode, PathNode, PlaceholderNode, RawSvgNode, RectangleNode,
    TextRunNode,
};
use crate::renderer::{PathCommand, TextStyle};

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum TextDecorationKind {
    Underline,
    Strikethrough,
    EmphasisDot,
}

/// Decoration-only output placement; the paired text/source stays in layout space.
#[derive(Debug, Clone, Copy)]
pub struct TextDecorationPaintGeometry {
    pub bbox: BoundingBox,
    pub inline_scale: f64,
}

impl TextDecorationKind {
    pub fn as_str(self) -> &'static str {
        match self {
            Self::Underline => "underline",
            Self::Strikethrough => "strikethrough",
            Self::EmphasisDot => "emphasisDot",
        }
    }
}

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum ResolvedImageKind {
    FormatConverted,
    /// 원본의 잘린 픽셀 창. 최종 장치 표본은 아니며 원본 bin 키로 조회할 수 없다.
    SourceWindow,
    /// 출력 크기·장치에 따라 바이트가 달라지는 변환. 원본 bin 키와 구분한다.
    OutputDevice,
    /// 원본 가시 창을 이미 담은 출력 바이트. painter에서 crop을 다시 적용하지 않는다.
    OutputDeviceWindow,
    BakedWatermark,
}

#[derive(Debug, Clone)]
pub struct ResolvedImagePayload {
    pub data: Vec<u8>,
    pub mime: &'static str,
    pub kind: ResolvedImageKind,
    pub suppress_effects: bool,
}

/// Page-space layout bounds and a separate estimate of the painted extent.
///
/// `logical` remains the layout/editing contract. `visual` includes known
/// strokes, shadows and explicit text visuals, but is not a font ink proof.
/// Picture recorders must retain a page-wide safety extent for unmeasured ink.
#[derive(Debug, Clone, Copy)]
pub struct PaintBounds {
    pub logical: BoundingBox,
    pub visual: BoundingBox,
}

/// backend가 재생하는 leaf paint operation.
///
/// 1차 전환에서는 기존 leaf payload를 최대한 그대로 유지해
/// semantic container 해석과 leaf draw payload 분리부터 달성한다.
#[derive(Debug, Clone)]
pub enum PaintOp {
    PageBackground {
        bbox: BoundingBox,
        background: Box<PageBackgroundNode>,
    },
    TextRun {
        bbox: BoundingBox,
        run: Box<TextRunNode>,
        source: Option<TextSourceSpan>,
        paint_transform: Option<LayerAffineTransform>,
    },
    GlyphRun {
        bbox: BoundingBox,
        run: Box<LayerGlyphRunPaint>,
        paint_transform: Option<LayerAffineTransform>,
    },
    GlyphOutline {
        bbox: BoundingBox,
        outline: Box<LayerGlyphOutlinePaint>,
        paint_transform: Option<LayerAffineTransform>,
    },
    /// HWP 글자겹침의 명시 visual op.
    ///
    /// 전환기에는 paired TextRun 안에도 legacy mirror payload를 남긴다.
    /// 새 backend는 이 op를 선택하고 TextRun mirror를 건너뛸 수 있다.
    CharOverlap {
        bbox: BoundingBox,
        run: Box<TextRunNode>,
        source: Option<TextSourceSpan>,
        paint_transform: Option<LayerAffineTransform>,
    },
    /// 문단 끝/줄 바꿈/필드 마커처럼 source text와 visual projection이 다른 표식.
    TextControlMark {
        bbox: BoundingBox,
        run: Box<TextRunNode>,
        source: Option<TextSourceSpan>,
    },
    /// 탭 리더 visual geometry.
    TabLeader {
        bbox: BoundingBox,
        run: Box<TextRunNode>,
        source: Option<TextSourceSpan>,
    },
    /// 밑줄/취소선/강조점 visual geometry.
    TextDecoration {
        bbox: BoundingBox,
        run: Box<TextRunNode>,
        kind: TextDecorationKind,
        source: Option<TextSourceSpan>,
        trim_trailing_spaces: usize,
        paint_geometry: Option<TextDecorationPaintGeometry>,
    },
    /// Editor control-code label for a non-text object.
    ControlLabel { bbox: BoundingBox, label: String },
    FootnoteMarker {
        bbox: BoundingBox,
        marker: Box<FootnoteMarkerNode>,
    },
    Line {
        bbox: BoundingBox,
        line: Box<LineNode>,
    },
    Rectangle {
        bbox: BoundingBox,
        rect: Box<RectangleNode>,
    },
    Ellipse {
        bbox: BoundingBox,
        ellipse: Box<EllipseNode>,
    },
    Path {
        bbox: BoundingBox,
        path: Box<PathNode>,
    },
    Image {
        bbox: BoundingBox,
        image: Box<ImageNode>,
        resolved: Option<Box<ResolvedImagePayload>>,
    },
    Equation {
        bbox: BoundingBox,
        equation: Box<EquationNode>,
    },
    FormObject {
        bbox: BoundingBox,
        form: Box<FormObjectNode>,
    },
    Placeholder {
        bbox: BoundingBox,
        placeholder: Box<PlaceholderNode>,
    },
    RawSvg {
        bbox: BoundingBox,
        raw: Box<RawSvgNode>,
    },
}

impl PaintOp {
    pub fn page_background(bbox: BoundingBox, background: PageBackgroundNode) -> Self {
        Self::PageBackground {
            bbox,
            background: Box::new(background),
        }
    }

    pub fn text_run(bbox: BoundingBox, run: TextRunNode) -> Self {
        Self::TextRun {
            paint_transform: None,
            bbox,
            run: Box::new(run),
            source: None,
        }
    }

    pub fn glyph_run(bbox: BoundingBox, run: LayerGlyphRunPaint) -> Self {
        Self::GlyphRun {
            paint_transform: None,
            bbox,
            run: Box::new(run),
        }
    }

    pub fn glyph_outline(bbox: BoundingBox, outline: LayerGlyphOutlinePaint) -> Self {
        Self::GlyphOutline {
            paint_transform: None,
            bbox,
            outline: Box::new(outline),
        }
    }

    pub fn char_overlap(bbox: BoundingBox, run: TextRunNode) -> Self {
        Self::CharOverlap {
            paint_transform: None,
            bbox,
            run: Box::new(run),
            source: None,
        }
    }

    pub fn text_control_mark(bbox: BoundingBox, run: TextRunNode) -> Self {
        Self::TextControlMark {
            bbox,
            run: Box::new(run),
            source: None,
        }
    }

    pub fn tab_leader(bbox: BoundingBox, run: TextRunNode) -> Self {
        Self::TabLeader {
            bbox,
            run: Box::new(run),
            source: None,
        }
    }

    pub fn text_decoration(bbox: BoundingBox, run: TextRunNode, kind: TextDecorationKind) -> Self {
        Self::TextDecoration {
            bbox,
            run: Box::new(run),
            kind,
            source: None,
            trim_trailing_spaces: 0,
            paint_geometry: None,
        }
    }

    pub fn glyph_paint_transform(&self) -> Option<LayerAffineTransform> {
        match self {
            Self::TextRun {
                paint_transform, ..
            }
            | Self::CharOverlap {
                paint_transform, ..
            }
            | Self::GlyphRun {
                paint_transform, ..
            }
            | Self::GlyphOutline {
                paint_transform, ..
            } => *paint_transform,
            _ => None,
        }
    }

    pub fn glyph_paint_transform_is_valid(&self) -> bool {
        self.glyph_paint_transform().is_none_or(|t| {
            [t.a, t.b, t.c, t.d, t.e, t.f]
                .iter()
                .all(|v| v.is_finite() && (*v as f32).is_finite())
                && (t.a * t.d - t.b * t.c).is_finite()
                && (t.a * t.d - t.b * t.c).abs() > 1e-12
        })
    }

    /// 모든 장식 소비자가 같은 배치를 재생한다. 원본 소유·선택·variant 검증에
    /// 사용하는 semantic run은 수정하지 않는다.
    pub(crate) fn decoration_replay(
        &self,
    ) -> Option<(BoundingBox, std::borrow::Cow<'_, TextRunNode>)> {
        let Self::TextDecoration {
            bbox,
            run,
            paint_geometry,
            kind,
            trim_trailing_spaces,
            ..
        } = self
        else {
            return None;
        };
        let terminal_positions = (*kind == TextDecorationKind::Underline
            && *trim_trailing_spaces == 0)
            .then(|| crate::renderer::glyph_fit::terminal_underline_positions(run))
            .flatten();
        let line_baseline = *kind == TextDecorationKind::Underline
            && run.style.underline == crate::model::style::UnderlineType::Bottom
            && run
                .style
                .font_position
                .is_some_and(|position| position != 0);
        if paint_geometry.is_none() && terminal_positions.is_none() && !line_baseline {
            return Some((*bbox, std::borrow::Cow::Borrowed(run.as_ref())));
        }
        let scale = paint_geometry.map_or(1.0, |geometry| geometry.inline_scale);
        let mut replay_bbox = paint_geometry.map_or(*bbox, |geometry| geometry.bbox);
        let terminal_changed = terminal_positions.is_some();
        let positions = terminal_positions
            .map(std::borrow::Cow::Owned)
            .unwrap_or_else(|| run.replay_positions_for(run.display_or_text()));
        if terminal_changed {
            // 장식 폭은 공통 replay의 끝점과 같은 좌표계를 쓴다.
            replay_bbox.width = positions.last().copied().unwrap_or(0.0) * scale;
        }
        let mut replay = run.as_ref().clone();
        // 독립 Print의 -12/0/+12 대조군에서 아래 밑줄은 줄 기준선에 남는다.
        // 원본 소유·검증용 run은 유지하고 실제 장식 재생에만 글자 위치를 제외한다.
        if line_baseline {
            replay.style.font_position = None;
        }
        replay.layout_positions = Some(positions.iter().map(|position| position * scale).collect());
        Some((replay_bbox, std::borrow::Cow::Owned(replay)))
    }

    pub fn control_label(bbox: BoundingBox, label: impl Into<String>) -> Self {
        Self::ControlLabel {
            bbox,
            label: label.into(),
        }
    }

    pub fn footnote_marker(bbox: BoundingBox, marker: FootnoteMarkerNode) -> Self {
        Self::FootnoteMarker {
            bbox,
            marker: Box::new(marker),
        }
    }

    pub fn line(bbox: BoundingBox, line: LineNode) -> Self {
        Self::Line {
            bbox,
            line: Box::new(line),
        }
    }

    pub fn rectangle(bbox: BoundingBox, rect: RectangleNode) -> Self {
        Self::Rectangle {
            bbox,
            rect: Box::new(rect),
        }
    }

    pub fn ellipse(bbox: BoundingBox, ellipse: EllipseNode) -> Self {
        Self::Ellipse {
            bbox,
            ellipse: Box::new(ellipse),
        }
    }

    pub fn path(bbox: BoundingBox, path: PathNode) -> Self {
        Self::Path {
            bbox,
            path: Box::new(path),
        }
    }

    pub fn image(
        bbox: BoundingBox,
        mut image: ImageNode,
        resolved: Option<ResolvedImagePayload>,
    ) -> Self {
        crate::renderer::image_geometry::normalize_gif_crop(&mut image);
        image.original_size_hu = crate::renderer::image_resolver::image_crop_reference(&image);
        if let Some(payload) = resolved.as_ref() {
            crate::renderer::image_resolver::normalize_resolved_image_window(&mut image, payload);
        }
        Self::Image {
            bbox,
            image: Box::new(image),
            resolved: resolved.map(Box::new),
        }
    }

    pub fn equation(bbox: BoundingBox, equation: EquationNode) -> Self {
        Self::Equation {
            bbox,
            equation: Box::new(equation),
        }
    }

    pub fn form_object(bbox: BoundingBox, form: FormObjectNode) -> Self {
        Self::FormObject {
            bbox,
            form: Box::new(form),
        }
    }

    pub fn placeholder(bbox: BoundingBox, placeholder: PlaceholderNode) -> Self {
        Self::Placeholder {
            bbox,
            placeholder: Box::new(placeholder),
        }
    }

    pub fn raw_svg(bbox: BoundingBox, raw: RawSvgNode) -> Self {
        Self::RawSvg {
            bbox,
            raw: Box::new(raw),
        }
    }

    pub fn bounds(&self) -> BoundingBox {
        match self {
            PaintOp::PageBackground { bbox, .. }
            | PaintOp::TextRun { bbox, .. }
            | PaintOp::GlyphRun { bbox, .. }
            | PaintOp::GlyphOutline { bbox, .. }
            | PaintOp::CharOverlap { bbox, .. }
            | PaintOp::TextControlMark { bbox, .. }
            | PaintOp::TabLeader { bbox, .. }
            | PaintOp::TextDecoration { bbox, .. }
            | PaintOp::ControlLabel { bbox, .. }
            | PaintOp::FootnoteMarker { bbox, .. }
            | PaintOp::Line { bbox, .. }
            | PaintOp::Rectangle { bbox, .. }
            | PaintOp::Ellipse { bbox, .. }
            | PaintOp::Path { bbox, .. }
            | PaintOp::Image { bbox, .. }
            | PaintOp::Equation { bbox, .. }
            | PaintOp::FormObject { bbox, .. }
            | PaintOp::Placeholder { bbox, .. }
            | PaintOp::RawSvg { bbox, .. } => *bbox,
        }
    }
}

#[derive(Debug, Clone)]
pub struct LayerGlyphRunPaint {
    pub source: TextSourceSpan,
    pub variant: PaintVariantMeta,
    pub paint_style: PaintTextStyle,
    pub shape_key: ShapeKey,
    pub placement: TextRunPlacement,
    pub glyph_ids: Vec<u32>,
    pub positions: Vec<LayerPoint>,
    pub advances: Option<Vec<LayerVector>>,
    pub clusters: Vec<GlyphCluster>,
    pub direction: TextDirection,
    pub bidi_level: Option<u8>,
    pub writing_mode: WritingMode,
    pub orientation: GlyphRunOrientation,
    pub glyph_transforms: Option<Vec<GlyphTransform>>,
    pub diagnostics: GlyphRunDiagnostics,
}

/// Strict-visual text alternative that carries producer-resolved glyph paths.
///
/// A GlyphOutline is still a text variant, not a generic Path. Consumers must
/// select it through the same equivalence group as the TextRun fallback and
/// reject it when the backend cannot preserve the declared payload.
#[derive(Debug, Clone)]
pub struct LayerGlyphOutlinePaint {
    pub source: TextSourceSpan,
    pub variant: PaintVariantMeta,
    pub payload_kind: GlyphOutlinePayloadKind,
    pub color_layers: Option<ColorLayersPayload>,
    pub bitmap_glyph: Option<BitmapGlyphPayload>,
    pub svg_glyph: Option<SvgGlyphPayload>,
    pub paint_style: PaintTextStyle,
    pub placement: TextRunPlacement,
    pub paths: Vec<LayerGlyphOutlinePath>,
    pub stroke: Option<GlyphOutlineStrokeStyle>,
    pub diagnostics: GlyphRunDiagnostics,
}

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum GlyphOutlinePayloadKind {
    MonochromeFill,
    MonochromeFillStroke,
    ColorLayers,
    BitmapGlyph,
    SvgGlyph,
}

impl GlyphOutlinePayloadKind {
    pub fn as_str(self) -> &'static str {
        match self {
            Self::MonochromeFill => "monochromeFill",
            Self::MonochromeFillStroke => "monochromeFillStroke",
            Self::ColorLayers => "colorLayers",
            Self::BitmapGlyph => "bitmapGlyph",
            Self::SvgGlyph => "svgGlyph",
        }
    }
}

impl LayerGlyphOutlinePaint {
    /// Scalar representability shared by strict outline consumers. Resource
    /// preparation and transformed extents still require backend validation.
    pub(crate) fn has_portable_geometry(&self) -> bool {
        text_placement_is_finite(&self.placement)
            && (!matches!(
                self.payload_kind,
                GlyphOutlinePayloadKind::MonochromeFill
                    | GlyphOutlinePayloadKind::MonochromeFillStroke
            ) || self
                .paths
                .iter()
                .all(|path| path_commands_are_finite(&path.commands)))
    }

    pub fn has_exclusive_payload_family(&self) -> bool {
        let has_stroke = self.stroke.is_some();
        let has_color_layers = self.color_layers.is_some();
        let has_bitmap_glyph = self.bitmap_glyph.is_some();
        let has_svg_glyph = self.svg_glyph.is_some();
        match self.payload_kind {
            GlyphOutlinePayloadKind::MonochromeFill => {
                !has_stroke && !has_color_layers && !has_bitmap_glyph && !has_svg_glyph
            }
            GlyphOutlinePayloadKind::MonochromeFillStroke => {
                has_stroke && !has_color_layers && !has_bitmap_glyph && !has_svg_glyph
            }
            GlyphOutlinePayloadKind::ColorLayers => {
                !has_stroke && has_color_layers && !has_bitmap_glyph && !has_svg_glyph
            }
            GlyphOutlinePayloadKind::BitmapGlyph => {
                !has_stroke && !has_color_layers && has_bitmap_glyph && !has_svg_glyph
            }
            GlyphOutlinePayloadKind::SvgGlyph => {
                !has_stroke && !has_color_layers && !has_bitmap_glyph && has_svg_glyph
            }
        }
    }

    /// Stable, export-local identity for payload resources that sit behind a
    /// GlyphOutline sidecar. The key starts with replay decision metadata and
    /// may append an interned resource digest when bytes are available, so
    /// color/bitmap/SVG payload families do not share a cache slot merely
    /// because a producer reused the same numeric resource id.
    pub fn payload_resource_key(&self) -> Option<String> {
        self.payload_resource_key_with_resources(None)
    }

    pub fn payload_resource_key_with_resources(
        &self,
        resources: Option<&ResourceArena>,
    ) -> Option<String> {
        if !self.has_payload_resource_key() {
            return None;
        }
        match self.payload_kind {
            GlyphOutlinePayloadKind::MonochromeFill
            | GlyphOutlinePayloadKind::MonochromeFillStroke => None,
            GlyphOutlinePayloadKind::ColorLayers => self
                .color_layers
                .as_ref()
                .map(color_layers_payload_resource_key),
            GlyphOutlinePayloadKind::BitmapGlyph => self
                .bitmap_glyph
                .as_ref()
                .map(|payload| bitmap_glyph_payload_resource_key(payload, resources)),
            GlyphOutlinePayloadKind::SvgGlyph => self
                .svg_glyph
                .as_ref()
                .map(|payload| svg_glyph_payload_resource_key(payload, resources)),
        }
    }

    pub fn has_payload_resource_key(&self) -> bool {
        match self.payload_kind {
            GlyphOutlinePayloadKind::MonochromeFill
            | GlyphOutlinePayloadKind::MonochromeFillStroke => false,
            GlyphOutlinePayloadKind::ColorLayers => {
                self.color_layers.as_ref().is_some_and(|payload| {
                    payload.has_colrv0_resolved_layer_contract()
                        || payload.has_colrv1_supported_graph_contract()
                })
            }
            GlyphOutlinePayloadKind::BitmapGlyph => self
                .bitmap_glyph
                .as_ref()
                .is_some_and(BitmapGlyphPayload::has_strict_visual_contract),
            GlyphOutlinePayloadKind::SvgGlyph => self
                .svg_glyph
                .as_ref()
                .is_some_and(SvgGlyphPayload::has_static_sanitized_contract),
        }
    }
}

fn color_layers_payload_resource_key(payload: &ColorLayersPayload) -> String {
    let mut key = format!(
        "glyphPayload:colorLayers:format:{}:source:{}:palette:{}:range:{}:glyphRange:{}",
        payload.color_format.as_str(),
        font_color_glyph_ref_key(payload.source_font_ref.as_ref()),
        palette_ref_key(payload.palette_ref.as_ref()),
        optional_text_range_key(payload.source_range_utf8),
        optional_glyph_range_key(payload.glyph_range),
    );
    // `paint_graph` 와 `layers` 는 독립 필드다(COLRv1 그래프와 COLRv0 해석 레이어가
    // 함께 실린다 — `has_colrv0_resolved_layer_contract` 참고). 둘 중 하나만 키에
    // 넣으면 나머지 하나만 다른 두 페이로드가 같은 캐시 슬롯을 쓴다.
    if let Some(graph) = &payload.paint_graph {
        key.push_str(":graph:");
        key.push_str(&color_paint_graph_key(graph));
    }
    if !payload.layers.is_empty() {
        key.push_str(":layers:");
        for (idx, layer) in payload.layers.iter().enumerate() {
            if idx > 0 {
                key.push('|');
            }
            key.push_str(&color_layer_node_key(layer));
        }
    }
    key
}

/// 레이어 하나의 키. **그려지는 결과를 바꾸는 필드는 전부 들어간다** — 기하
/// (`commands`)·색(`fill`·`color`)·채움 규칙·불투명도·변환이 빠지면 색만 다른
/// 컬러 글리프가 같은 슬롯을 공유한다.
fn color_layer_node_key(layer: &ColorLayerNode) -> String {
    format!(
        "{}:{}:{}:{}:{}:{}:cmds:{}:fill:{}:rule:{}:color:{}:opacity:{}:xform:{}",
        optional_u32_key(layer.layer_index),
        optional_u32_key(layer.glyph_id),
        optional_glyph_range_key(layer.glyph_range),
        optional_text_range_key(layer.source_range_utf8),
        font_color_glyph_ref_key(layer.source_font_ref.as_ref()),
        layer
            .palette_index
            .map(|value| value.to_string())
            .unwrap_or_else(|| "-".to_string()),
        path_commands_key(layer.commands.as_deref()),
        resolved_color_key(layer.fill.as_ref()),
        layer
            .fill_rule
            .map(GlyphOutlineFillRule::as_str)
            .unwrap_or("-"),
        optional_u32_key(layer.color),
        layer
            .opacity
            .map(|value| format!("{value:.6}"))
            .unwrap_or_else(|| "-".to_string()),
        optional_affine_key(layer.transform_to_run),
    )
}

fn optional_u32_key<T: std::fmt::Display>(value: Option<T>) -> String {
    value
        .map(|value| value.to_string())
        .unwrap_or_else(|| "-".to_string())
}

fn resolved_color_key(color: Option<&ResolvedColor>) -> String {
    match color {
        Some(color) => format!(
            "{}/{:.6},{:.6},{:.6},{:.6}",
            color.color_space.as_deref().unwrap_or("-"),
            color.rgba[0],
            color.rgba[1],
            color.rgba[2],
            color.rgba[3],
        ),
        None => "-".to_string(),
    }
}

fn path_commands_key(commands: Option<&[PathCommand]>) -> String {
    let Some(commands) = commands else {
        return "-".to_string();
    };
    let mut key = String::new();
    for (idx, command) in commands.iter().enumerate() {
        if idx > 0 {
            key.push(';');
        }
        match command {
            PathCommand::MoveTo(x, y) => key.push_str(&format!("M{x:.6},{y:.6}")),
            PathCommand::LineTo(x, y) => key.push_str(&format!("L{x:.6},{y:.6}")),
            PathCommand::CurveTo(a, b, c, d, e, f) => {
                key.push_str(&format!("C{a:.6},{b:.6},{c:.6},{d:.6},{e:.6},{f:.6}"))
            }
            PathCommand::ArcTo(rx, ry, rot, large, sweep, x, y) => key.push_str(&format!(
                "A{rx:.6},{ry:.6},{rot:.6},{large},{sweep},{x:.6},{y:.6}"
            )),
            PathCommand::ClosePath => key.push('Z'),
        }
    }
    key
}

fn color_paint_graph_key(graph: &ColorPaintGraphPayload) -> String {
    let mut key = format!("root:{}:nodes:", graph.root_node_id);
    for (idx, node) in graph.nodes.iter().enumerate() {
        if idx > 0 {
            key.push('|');
        }
        key.push_str(&format!(
            "{}:{}:{}:{}:range:{}:paint:{}",
            node.node_id,
            node.kind.as_str(),
            optional_glyph_range_key(node.glyph_range),
            font_color_glyph_ref_key(node.source_font_ref.as_ref()),
            optional_text_range_key(node.source_range_utf8),
            color_paint_graph_node_paint_key(node),
        ));
    }
    key
}

/// 그래프 노드가 **실제로 무엇을 칠하는가**. `kind` 는 종류만 말하고 내용은
/// 말하지 않는다 — 두 SolidPath 노드가 서로 다른 색이어도 `kind` 는 같다.
/// 페인트 내용이 키에 없으면 그 둘이 같은 캐시 슬롯을 쓴다.
fn color_paint_graph_node_paint_key(node: &ColorPaintGraphNode) -> String {
    if let Some(solid) = &node.solid_path {
        return format!(
            "solid:{}:{}:{}:{}:{}",
            path_commands_key(Some(&solid.commands)),
            resolved_color_key(Some(&solid.fill)),
            solid.fill_rule.as_str(),
            optional_u32_key(solid.source_glyph_id),
            optional_u32_key(solid.palette_index),
        );
    }
    if let Some(linear) = &node.linear_gradient_path {
        return format!(
            "linear:{}:{:.6},{:.6},{:.6},{:.6}:{}:{}:{}:{}",
            path_commands_key(Some(&linear.commands)),
            linear.gradient.x0,
            linear.gradient.y0,
            linear.gradient.x1,
            linear.gradient.y1,
            gradient_stops_key(&linear.gradient.stops),
            linear.fill_rule.as_str(),
            optional_u32_key(linear.source_glyph_id),
            optional_u32_key(linear.palette_index),
        );
    }
    if let Some(radial) = &node.radial_gradient_path {
        return format!(
            "radial:{}:{:.6},{:.6},{:.6}:{}:{}:{}:{}",
            path_commands_key(Some(&radial.commands)),
            radial.gradient.cx,
            radial.gradient.cy,
            radial.gradient.radius,
            gradient_stops_key(&radial.gradient.stops),
            radial.fill_rule.as_str(),
            optional_u32_key(radial.source_glyph_id),
            optional_u32_key(radial.palette_index),
        );
    }
    if let Some(sweep) = &node.sweep_gradient_path {
        return format!(
            "sweep:{}:{:.6},{:.6},{:.6},{:.6}:{}:{}:{}:{}",
            path_commands_key(Some(&sweep.commands)),
            sweep.gradient.cx,
            sweep.gradient.cy,
            sweep.gradient.start_angle_degrees,
            sweep.gradient.end_angle_degrees,
            gradient_stops_key(&sweep.gradient.stops),
            sweep.fill_rule.as_str(),
            optional_u32_key(sweep.source_glyph_id),
            optional_u32_key(sweep.palette_index),
        );
    }
    if let Some(transform) = &node.transform {
        return format!(
            "transform:{}:{}",
            transform.child_node_id,
            affine_key(transform.transform),
        );
    }
    if let Some(composite) = &node.composite {
        return format!(
            "composite:{}:{}:{}",
            composite.source_node_id,
            composite.backdrop_node_id,
            composite.mode.as_str(),
        );
    }
    if let Some(clip) = &node.clip {
        return format!(
            "clip:{}:{}:{}",
            clip.child_node_id,
            path_commands_key(Some(&clip.clip_commands)),
            clip.fill_rule.as_str(),
        );
    }
    "-".to_string()
}

fn gradient_stops_key(stops: &[ColorGradientStop]) -> String {
    let mut key = String::from("stops:");
    for (idx, stop) in stops.iter().enumerate() {
        if idx > 0 {
            key.push(';');
        }
        key.push_str(&format!(
            "{:.6}@{}",
            stop.offset,
            resolved_color_key(Some(&stop.color))
        ));
    }
    key
}

fn bitmap_glyph_payload_resource_key(
    payload: &BitmapGlyphPayload,
    resources: Option<&ResourceArena>,
) -> String {
    let mut key = format!(
        "glyphPayload:bitmapGlyph:imageRef:{}:range:{}:glyphRange:{}:placement:{}:alphaPremultiplied:{}:scaling:{}:filtering:{}:transform:{}",
        payload.image_ref.0,
        text_range_key(payload.source_range_utf8),
        glyph_range_key(payload.glyph_range),
        bbox_key(payload.placement),
        payload.alpha_premultiplied,
        payload.scaling_policy.as_str(),
        payload.filtering.as_str(),
        optional_affine_key(payload.transform_to_run),
    );
    if let Some(resource_key) =
        resources.and_then(|resources| resources.image_resource_key(payload.image_ref))
    {
        key.push_str(":resource:");
        key.push_str(resource_key);
    }
    key
}

fn svg_glyph_payload_resource_key(
    payload: &SvgGlyphPayload,
    resources: Option<&ResourceArena>,
) -> String {
    let mut key = format!(
        "glyphPayload:svgGlyph:svgRef:{}:range:{}:glyphRange:{}:viewBox:{}:intrinsicSize:{}:staticSanitized:{}:script:{}:animation:{}:external:{}:interactive:{}:transform:{}",
        payload.svg_ref.0,
        text_range_key(payload.source_range_utf8),
        glyph_range_key(payload.glyph_range),
        bbox_key(payload.view_box),
        payload
            .intrinsic_size
            .map(|size| format!("{:.6},{:.6}", size.dx, size.dy))
            .unwrap_or_else(|| "-".to_string()),
        payload.static_sanitized,
        payload.script_allowed,
        payload.animation_allowed,
        payload.external_resources_allowed,
        payload.interactivity_allowed,
        optional_affine_key(payload.transform_to_run),
    );
    if let Some(em_box) = payload.font_em_box {
        key.push_str(":fontEmBox:");
        key.push_str(&bbox_key(em_box));
    }
    if let Some(resource_key) =
        resources.and_then(|resources| resources.svg_resource_key(payload.svg_ref))
    {
        key.push_str(":resource:");
        key.push_str(resource_key);
    }
    key
}

fn font_color_glyph_ref_key(value: Option<&FontColorGlyphRef>) -> String {
    match value {
        Some(value) => format!(
            "face:{}:glyph:{}:palette:{}:format:{}",
            value.face_key.as_deref().unwrap_or("-"),
            value
                .glyph_id
                .map(|glyph_id| glyph_id.to_string())
                .unwrap_or_else(|| "-".to_string()),
            value
                .palette_index
                .map(|palette_index| palette_index.to_string())
                .unwrap_or_else(|| "-".to_string()),
            value
                .color_format
                .map(ColorGlyphFormat::as_str)
                .unwrap_or("-"),
        ),
        None => "-".to_string(),
    }
}

fn palette_ref_key(value: Option<&PaletteRef>) -> String {
    match value {
        Some(value) => format!(
            "id:{}:index:{}:digest:{}",
            value.id.as_deref().unwrap_or("-"),
            value
                .index
                .map(|index| index.to_string())
                .unwrap_or_else(|| "-".to_string()),
            value.cpal_digest.as_deref().unwrap_or("-"),
        ),
        None => "-".to_string(),
    }
}

fn optional_text_range_key(range: Option<TextSourceRange>) -> String {
    range.map(text_range_key).unwrap_or_else(|| "-".to_string())
}

fn text_range_key(range: TextSourceRange) -> String {
    format!("{}..{}", range.start, range.end)
}

fn optional_glyph_range_key(range: Option<GlyphRange>) -> String {
    range
        .map(glyph_range_key)
        .unwrap_or_else(|| "-".to_string())
}

fn glyph_range_key(range: GlyphRange) -> String {
    format!("{}..{}", range.start, range.end)
}

fn bbox_key(bbox: BoundingBox) -> String {
    format!(
        "{:.3},{:.3},{:.3},{:.3}",
        bbox.x, bbox.y, bbox.width, bbox.height
    )
}

fn optional_affine_key(transform: Option<LayerAffineTransform>) -> String {
    transform.map(affine_key).unwrap_or_else(|| "-".to_string())
}

fn affine_key(transform: LayerAffineTransform) -> String {
    format!(
        "{:.6},{:.6},{:.6},{:.6},{:.6},{:.6}",
        transform.a, transform.b, transform.c, transform.d, transform.e, transform.f
    )
}

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum ColorGlyphFormat {
    ColrV0,
    ColrV1,
    Other,
}

impl ColorGlyphFormat {
    pub fn as_str(self) -> &'static str {
        match self {
            Self::ColrV0 => "colrV0",
            Self::ColrV1 => "colrV1",
            Self::Other => "other",
        }
    }
}

#[derive(Debug, Clone, PartialEq)]
pub struct FontColorGlyphRef {
    pub face_key: Option<String>,
    pub glyph_id: Option<u32>,
    pub palette_index: Option<u16>,
    pub color_format: Option<ColorGlyphFormat>,
}

#[derive(Debug, Clone, PartialEq)]
pub struct PaletteRef {
    pub id: Option<String>,
    pub index: Option<u16>,
    pub cpal_digest: Option<String>,
}

#[derive(Debug, Clone, PartialEq)]
pub struct ResolvedColor {
    pub color_space: Option<String>,
    pub rgba: [f32; 4],
}

#[derive(Debug, Clone)]
pub struct ColorLayerNode {
    pub layer_index: Option<u32>,
    pub glyph_id: Option<u32>,
    pub glyph_range: Option<GlyphRange>,
    pub source_range_utf8: Option<TextSourceRange>,
    pub source_font_ref: Option<FontColorGlyphRef>,
    pub commands: Option<Vec<PathCommand>>,
    pub fill: Option<ResolvedColor>,
    pub fill_rule: Option<GlyphOutlineFillRule>,
    pub palette_index: Option<u16>,
    pub color: Option<ColorRef>,
    pub opacity: Option<f64>,
    pub transform_to_run: Option<LayerAffineTransform>,
}

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum ColorPaintGraphNodeKind {
    SolidPath,
    LinearGradientPath,
    RadialGradientPath,
    SweepGradientPath,
    Transform,
    Composite,
    Clip,
}

impl ColorPaintGraphNodeKind {
    pub fn as_str(self) -> &'static str {
        match self {
            Self::SolidPath => "solidPath",
            Self::LinearGradientPath => "linearGradientPath",
            Self::RadialGradientPath => "radialGradientPath",
            Self::SweepGradientPath => "sweepGradientPath",
            Self::Transform => "transform",
            Self::Composite => "composite",
            Self::Clip => "clip",
        }
    }

    pub fn is_colrv1_stage1_supported(self) -> bool {
        matches!(
            self,
            Self::SolidPath
                | Self::LinearGradientPath
                | Self::RadialGradientPath
                | Self::SweepGradientPath
                | Self::Transform
                | Self::Composite
                | Self::Clip
        )
    }
}

#[derive(Debug, Clone)]
pub struct ColorPaintSolidPathNode {
    pub commands: Vec<PathCommand>,
    pub fill: ResolvedColor,
    pub fill_rule: GlyphOutlineFillRule,
    pub source_glyph_id: Option<u32>,
    pub palette_index: Option<u16>,
}

#[derive(Debug, Clone, PartialEq)]
pub struct ColorGradientStop {
    pub offset: f64,
    pub color: ResolvedColor,
}

#[derive(Debug, Clone, PartialEq)]
pub struct ColorLinearGradient {
    pub x0: f64,
    pub y0: f64,
    pub x1: f64,
    pub y1: f64,
    pub stops: Vec<ColorGradientStop>,
}

#[derive(Debug, Clone, PartialEq)]
pub struct ColorRadialGradient {
    pub cx: f64,
    pub cy: f64,
    pub radius: f64,
    pub stops: Vec<ColorGradientStop>,
}

#[derive(Debug, Clone, PartialEq)]
pub struct ColorSweepGradient {
    pub cx: f64,
    pub cy: f64,
    pub start_angle_degrees: f64,
    pub end_angle_degrees: f64,
    pub stops: Vec<ColorGradientStop>,
}

#[derive(Debug, Clone)]
pub struct ColorPaintLinearGradientPathNode {
    pub commands: Vec<PathCommand>,
    pub gradient: ColorLinearGradient,
    pub fill_rule: GlyphOutlineFillRule,
    pub source_glyph_id: Option<u32>,
    pub palette_index: Option<u16>,
}

#[derive(Debug, Clone)]
pub struct ColorPaintRadialGradientPathNode {
    pub commands: Vec<PathCommand>,
    pub gradient: ColorRadialGradient,
    pub fill_rule: GlyphOutlineFillRule,
    pub source_glyph_id: Option<u32>,
    pub palette_index: Option<u16>,
}

#[derive(Debug, Clone)]
pub struct ColorPaintSweepGradientPathNode {
    pub commands: Vec<PathCommand>,
    pub gradient: ColorSweepGradient,
    pub fill_rule: GlyphOutlineFillRule,
    pub source_glyph_id: Option<u32>,
    pub palette_index: Option<u16>,
}

#[derive(Debug, Clone, PartialEq)]
pub struct ColorPaintTransformNode {
    pub child_node_id: u32,
    pub transform: LayerAffineTransform,
}

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum ColorPaintCompositeMode {
    SourceOver,
}

impl ColorPaintCompositeMode {
    pub fn as_str(self) -> &'static str {
        match self {
            Self::SourceOver => "sourceOver",
        }
    }
}

#[derive(Debug, Clone, PartialEq)]
pub struct ColorPaintCompositeNode {
    pub source_node_id: u32,
    pub backdrop_node_id: u32,
    pub mode: ColorPaintCompositeMode,
}

#[derive(Debug, Clone)]
pub struct ColorPaintClipNode {
    pub child_node_id: u32,
    pub clip_commands: Vec<PathCommand>,
    pub fill_rule: GlyphOutlineFillRule,
}

#[derive(Debug, Clone)]
pub struct ColorPaintGraphNode {
    pub node_id: u32,
    pub kind: ColorPaintGraphNodeKind,
    pub solid_path: Option<ColorPaintSolidPathNode>,
    pub linear_gradient_path: Option<ColorPaintLinearGradientPathNode>,
    pub radial_gradient_path: Option<ColorPaintRadialGradientPathNode>,
    pub sweep_gradient_path: Option<ColorPaintSweepGradientPathNode>,
    pub transform: Option<ColorPaintTransformNode>,
    pub composite: Option<ColorPaintCompositeNode>,
    pub clip: Option<ColorPaintClipNode>,
    pub source_range_utf8: Option<TextSourceRange>,
    pub glyph_range: Option<GlyphRange>,
    pub source_font_ref: Option<FontColorGlyphRef>,
}

#[derive(Debug, Clone)]
pub struct ColorPaintGraphPayload {
    pub root_node_id: u32,
    pub nodes: Vec<ColorPaintGraphNode>,
}

const MAX_COLRV1_GRAPH_NODES: usize = 64;
const MAX_COLRV1_GRAPH_DEPTH: usize = 64;
/// Shared DAG nodes may be painted repeatedly; the node limit alone does not
/// bound the expanded replay cost of nested composites.
const MAX_COLRV1_GRAPH_REPLAY_VISITS: usize = 4096;

fn text_source_range_is_valid(range: TextSourceRange) -> bool {
    range.end >= range.start
}

fn glyph_range_is_valid(range: GlyphRange) -> bool {
    range.end >= range.start
}

// Skia consumes f32 scalars even when the shared IR stores f64 geometry.
pub(crate) fn portable_glyph_scalar(value: f64) -> bool {
    value.is_finite() && value.abs() <= f64::from(f32::MAX)
}

pub(crate) fn path_commands_are_finite(commands: &[PathCommand]) -> bool {
    !commands.is_empty()
        && commands.len() <= 4096
        && commands.iter().all(|command| match *command {
            PathCommand::MoveTo(x, y) | PathCommand::LineTo(x, y) => {
                portable_glyph_scalar(x) && portable_glyph_scalar(y)
            }
            PathCommand::CurveTo(x1, y1, x2, y2, x, y) => [x1, y1, x2, y2, x, y]
                .into_iter()
                .all(portable_glyph_scalar),
            PathCommand::ArcTo(rx, ry, rotation, _, _, x, y) => [rx, ry, rotation, x, y]
                .into_iter()
                .all(portable_glyph_scalar),
            PathCommand::ClosePath => true,
        })
}

fn resolved_color_is_valid(color: &ResolvedColor) -> bool {
    color
        .color_space
        .as_ref()
        .map(|color_space| !color_space.is_empty())
        .unwrap_or(true)
        && color
            .rgba
            .iter()
            .all(|component| component.is_finite() && (0.0..=1.0).contains(component))
}

fn color_gradient_stops_are_valid(stops: &[ColorGradientStop]) -> bool {
    if stops.len() < 2 {
        return false;
    }
    let mut previous_offset = f64::NEG_INFINITY;
    stops.iter().all(|stop| {
        let valid = stop.offset.is_finite()
            && (0.0..=1.0).contains(&stop.offset)
            && stop.offset >= previous_offset
            && resolved_color_is_valid(&stop.color);
        previous_offset = stop.offset;
        valid
    })
}

fn color_sweep_is_supported_full_circle(start_angle_degrees: f64, end_angle_degrees: f64) -> bool {
    let is_full_circle = |start: f64, end: f64| start < end && (end - start - 360.0).abs() <= 1e-9;
    portable_glyph_scalar(start_angle_degrees)
        && portable_glyph_scalar(end_angle_degrees)
        && is_full_circle(start_angle_degrees, end_angle_degrees)
        && is_full_circle(
            glyph_geometry_wire_scalar(start_angle_degrees, 6),
            glyph_geometry_wire_scalar(end_angle_degrees, 6),
        )
}

fn graph_leaf_metadata_is_valid(node: &ColorPaintGraphNode) -> bool {
    node.source_range_utf8
        .is_some_and(text_source_range_is_valid)
        && node.glyph_range.is_some_and(GlyphRange::is_non_empty)
        && node.source_font_ref.is_some()
}

impl ColorPaintGraphPayload {
    /// Compatibility alias for the P19 first supported COLRv1 graph contract.
    /// New code should use `has_colrv1_supported_graph_contract`.
    #[deprecated(note = "use has_colrv1_supported_graph_contract")]
    pub fn has_colrv1_stage1_contract(&self) -> bool {
        self.has_colrv1_supported_graph_contract()
    }

    pub fn has_colrv1_supported_graph_contract(&self) -> bool {
        use std::collections::{HashMap, HashSet};

        if self.nodes.is_empty() || self.nodes.len() > MAX_COLRV1_GRAPH_NODES {
            return false;
        }

        let mut nodes_by_id = HashMap::with_capacity(self.nodes.len());
        for node in &self.nodes {
            if nodes_by_id.insert(node.node_id, node).is_some() {
                return false;
            }
        }
        if !nodes_by_id.contains_key(&self.root_node_id) {
            return false;
        }

        for node in &self.nodes {
            match node.kind {
                ColorPaintGraphNodeKind::SolidPath => {
                    if node.transform.is_some()
                        || node.composite.is_some()
                        || node.clip.is_some()
                        || node.linear_gradient_path.is_some()
                        || node.radial_gradient_path.is_some()
                        || node.sweep_gradient_path.is_some()
                        || !graph_leaf_metadata_is_valid(node)
                    {
                        return false;
                    }
                    let Some(solid) = node.solid_path.as_ref() else {
                        return false;
                    };
                    if !path_commands_are_finite(&solid.commands)
                        || !resolved_color_is_valid(&solid.fill)
                    {
                        return false;
                    }
                }
                ColorPaintGraphNodeKind::LinearGradientPath => {
                    if node.solid_path.is_some()
                        || node.transform.is_some()
                        || node.composite.is_some()
                        || node.clip.is_some()
                        || node.radial_gradient_path.is_some()
                        || node.sweep_gradient_path.is_some()
                        || !graph_leaf_metadata_is_valid(node)
                    {
                        return false;
                    }
                    let Some(gradient_path) = node.linear_gradient_path.as_ref() else {
                        return false;
                    };
                    if !path_commands_are_finite(&gradient_path.commands)
                        || !portable_glyph_scalar(gradient_path.gradient.x0)
                        || !portable_glyph_scalar(gradient_path.gradient.y0)
                        || !portable_glyph_scalar(gradient_path.gradient.x1)
                        || !portable_glyph_scalar(gradient_path.gradient.y1)
                        || !color_gradient_stops_are_valid(&gradient_path.gradient.stops)
                    {
                        return false;
                    }
                }
                ColorPaintGraphNodeKind::RadialGradientPath => {
                    if node.solid_path.is_some()
                        || node.transform.is_some()
                        || node.composite.is_some()
                        || node.clip.is_some()
                        || node.linear_gradient_path.is_some()
                        || node.sweep_gradient_path.is_some()
                        || !graph_leaf_metadata_is_valid(node)
                    {
                        return false;
                    }
                    let Some(gradient_path) = node.radial_gradient_path.as_ref() else {
                        return false;
                    };
                    if !path_commands_are_finite(&gradient_path.commands)
                        || !portable_glyph_scalar(gradient_path.gradient.cx)
                        || !portable_glyph_scalar(gradient_path.gradient.cy)
                        || !portable_glyph_scalar(gradient_path.gradient.radius)
                        || gradient_path.gradient.radius <= 0.0
                        || glyph_geometry_wire_scalar(gradient_path.gradient.radius, 6) <= 0.0
                        || !color_gradient_stops_are_valid(&gradient_path.gradient.stops)
                    {
                        return false;
                    }
                }
                ColorPaintGraphNodeKind::SweepGradientPath => {
                    if node.solid_path.is_some()
                        || node.transform.is_some()
                        || node.composite.is_some()
                        || node.clip.is_some()
                        || node.linear_gradient_path.is_some()
                        || node.radial_gradient_path.is_some()
                        || !graph_leaf_metadata_is_valid(node)
                    {
                        return false;
                    }
                    let Some(gradient_path) = node.sweep_gradient_path.as_ref() else {
                        return false;
                    };
                    if !path_commands_are_finite(&gradient_path.commands)
                        || !portable_glyph_scalar(gradient_path.gradient.cx)
                        || !portable_glyph_scalar(gradient_path.gradient.cy)
                        || !color_sweep_is_supported_full_circle(
                            gradient_path.gradient.start_angle_degrees,
                            gradient_path.gradient.end_angle_degrees,
                        )
                        || !color_gradient_stops_are_valid(&gradient_path.gradient.stops)
                    {
                        return false;
                    }
                }
                ColorPaintGraphNodeKind::Transform => {
                    if node.solid_path.is_some()
                        || node.linear_gradient_path.is_some()
                        || node.radial_gradient_path.is_some()
                        || node.sweep_gradient_path.is_some()
                        || node.composite.is_some()
                        || node.clip.is_some()
                    {
                        return false;
                    }
                    if node
                        .source_range_utf8
                        .is_some_and(|range| !text_source_range_is_valid(range))
                        || node
                            .glyph_range
                            .is_some_and(|range| !glyph_range_is_valid(range))
                    {
                        return false;
                    }
                    let Some(transform) = node.transform.as_ref() else {
                        return false;
                    };
                    if !layer_affine_is_finite(transform.transform) {
                        return false;
                    }
                    if transform.child_node_id == node.node_id
                        || !nodes_by_id.contains_key(&transform.child_node_id)
                    {
                        return false;
                    }
                }
                ColorPaintGraphNodeKind::Composite => {
                    if node.solid_path.is_some()
                        || node.linear_gradient_path.is_some()
                        || node.radial_gradient_path.is_some()
                        || node.sweep_gradient_path.is_some()
                        || node.transform.is_some()
                        || node.clip.is_some()
                    {
                        return false;
                    }
                    if node
                        .source_range_utf8
                        .is_some_and(|range| !text_source_range_is_valid(range))
                        || node
                            .glyph_range
                            .is_some_and(|range| !glyph_range_is_valid(range))
                    {
                        return false;
                    }
                    let Some(composite) = node.composite.as_ref() else {
                        return false;
                    };
                    if composite.mode != ColorPaintCompositeMode::SourceOver
                        || composite.source_node_id == composite.backdrop_node_id
                        || composite.source_node_id == node.node_id
                        || composite.backdrop_node_id == node.node_id
                        || !nodes_by_id.contains_key(&composite.source_node_id)
                        || !nodes_by_id.contains_key(&composite.backdrop_node_id)
                    {
                        return false;
                    }
                }
                ColorPaintGraphNodeKind::Clip => {
                    if node.solid_path.is_some()
                        || node.linear_gradient_path.is_some()
                        || node.radial_gradient_path.is_some()
                        || node.sweep_gradient_path.is_some()
                        || node.transform.is_some()
                        || node.composite.is_some()
                    {
                        return false;
                    }
                    if node
                        .source_range_utf8
                        .is_some_and(|range| !text_source_range_is_valid(range))
                        || node
                            .glyph_range
                            .is_some_and(|range| !glyph_range_is_valid(range))
                    {
                        return false;
                    }
                    let Some(clip) = node.clip.as_ref() else {
                        return false;
                    };
                    if clip.child_node_id == node.node_id
                        || !nodes_by_id.contains_key(&clip.child_node_id)
                        || !path_commands_are_finite(&clip.clip_commands)
                    {
                        return false;
                    }
                }
            }
        }

        // Reusable DAG subgraphs are valid, but every expanded replay visit is
        // counted so a small graph cannot create exponential paint work.

        fn visit(
            node_id: u32,
            depth: usize,
            nodes_by_id: &HashMap<u32, &ColorPaintGraphNode>,
            visiting: &mut HashSet<u32>,
            visited: &mut HashSet<u32>,
            replay_visits: &mut usize,
        ) -> bool {
            *replay_visits += 1;
            if depth > MAX_COLRV1_GRAPH_DEPTH || *replay_visits > MAX_COLRV1_GRAPH_REPLAY_VISITS {
                return false;
            }
            if visiting.contains(&node_id) {
                return false;
            }
            let Some(node) = nodes_by_id.get(&node_id) else {
                return false;
            };
            visiting.insert(node_id);
            let valid = match node.kind {
                ColorPaintGraphNodeKind::Transform => {
                    node.transform.as_ref().is_some_and(|transform| {
                        visit(
                            transform.child_node_id,
                            depth + 1,
                            nodes_by_id,
                            visiting,
                            visited,
                            replay_visits,
                        )
                    })
                }
                ColorPaintGraphNodeKind::Composite => {
                    node.composite.as_ref().is_some_and(|composite| {
                        visit(
                            composite.backdrop_node_id,
                            depth + 1,
                            nodes_by_id,
                            visiting,
                            visited,
                            replay_visits,
                        ) && visit(
                            composite.source_node_id,
                            depth + 1,
                            nodes_by_id,
                            visiting,
                            visited,
                            replay_visits,
                        )
                    })
                }
                ColorPaintGraphNodeKind::Clip => node.clip.as_ref().is_some_and(|clip| {
                    visit(
                        clip.child_node_id,
                        depth + 1,
                        nodes_by_id,
                        visiting,
                        visited,
                        replay_visits,
                    )
                }),
                ColorPaintGraphNodeKind::SolidPath
                | ColorPaintGraphNodeKind::LinearGradientPath
                | ColorPaintGraphNodeKind::RadialGradientPath
                | ColorPaintGraphNodeKind::SweepGradientPath => true,
            };
            visiting.remove(&node_id);
            if valid {
                visited.insert(node_id);
            }
            valid
        }

        let mut visiting = HashSet::new();
        let mut visited = HashSet::new();
        visit(
            self.root_node_id,
            1,
            &nodes_by_id,
            &mut visiting,
            &mut visited,
            &mut 0,
        ) && visited.len() == self.nodes.len()
    }
}

#[derive(Debug, Clone)]
pub struct ColorLayersPayload {
    pub color_format: ColorGlyphFormat,
    pub source_font_ref: Option<FontColorGlyphRef>,
    pub palette_ref: Option<PaletteRef>,
    pub layers: Vec<ColorLayerNode>,
    pub paint_graph: Option<ColorPaintGraphPayload>,
    pub source_range_utf8: Option<TextSourceRange>,
    pub glyph_range: Option<GlyphRange>,
}

impl ColorLayersPayload {
    pub fn has_colrv0_resolved_layer_contract(&self) -> bool {
        self.color_format == ColorGlyphFormat::ColrV0
            && self.paint_graph.is_none()
            && !self.layers.is_empty()
            && self.layers.len() <= 256
            && self.layers.iter().all(|layer| {
                layer
                    .commands
                    .as_ref()
                    .is_some_and(|commands| path_commands_are_finite(commands))
                    && layer.fill.as_ref().is_some_and(resolved_color_is_valid)
                    && layer.fill_rule.is_some()
                    && layer
                        .source_range_utf8
                        .is_some_and(text_source_range_is_non_empty)
                    && layer.glyph_range.is_some_and(GlyphRange::is_non_empty)
                    && layer
                        .transform_to_run
                        .map(layer_affine_is_finite)
                        .unwrap_or(true)
                    && layer
                        .opacity
                        .map(|opacity| opacity.is_finite() && (0.0..=1.0).contains(&opacity))
                        .unwrap_or(true)
            })
    }

    /// Compatibility alias for the P19 first supported COLRv1 graph contract.
    /// New code should use `has_colrv1_supported_graph_contract`.
    #[deprecated(note = "use has_colrv1_supported_graph_contract")]
    pub fn has_colrv1_stage1_graph_contract(&self) -> bool {
        self.has_colrv1_supported_graph_contract()
    }

    pub fn has_colrv1_supported_graph_contract(&self) -> bool {
        self.color_format == ColorGlyphFormat::ColrV1
            && self.layers.is_empty()
            && self
                .source_range_utf8
                .is_some_and(text_source_range_is_valid)
            && self.glyph_range.is_some_and(GlyphRange::is_non_empty)
            && self.source_font_ref.is_some()
            && self
                .paint_graph
                .as_ref()
                .is_some_and(ColorPaintGraphPayload::has_colrv1_supported_graph_contract)
    }
}

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum BitmapGlyphScalingPolicy {
    SourceExact,
    PixelAligned,
    BackendDefault,
}

impl BitmapGlyphScalingPolicy {
    pub fn as_str(self) -> &'static str {
        match self {
            Self::SourceExact => "sourceExact",
            Self::PixelAligned => "pixelAligned",
            Self::BackendDefault => "backendDefault",
        }
    }
}

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum BitmapGlyphFiltering {
    Nearest,
    Linear,
}

impl BitmapGlyphFiltering {
    pub fn as_str(self) -> &'static str {
        match self {
            Self::Nearest => "nearest",
            Self::Linear => "linear",
        }
    }
}

#[derive(Debug, Clone)]
pub struct BitmapGlyphPayload {
    pub image_ref: ImageResourceId,
    pub source_range_utf8: TextSourceRange,
    pub glyph_range: GlyphRange,
    pub placement: BoundingBox,
    pub alpha_premultiplied: bool,
    pub scaling_policy: BitmapGlyphScalingPolicy,
    pub filtering: BitmapGlyphFiltering,
    pub transform_to_run: Option<LayerAffineTransform>,
}

impl BitmapGlyphPayload {
    pub fn has_strict_visual_contract(&self) -> bool {
        text_source_range_is_non_empty(self.source_range_utf8)
            && self.glyph_range.is_non_empty()
            && bbox_is_finite_positive(self.placement)
            && !matches!(
                self.scaling_policy,
                BitmapGlyphScalingPolicy::BackendDefault
            )
            && self
                .transform_to_run
                .map(layer_affine_is_finite)
                .unwrap_or(true)
    }
}

#[derive(Debug, Clone)]
pub struct SvgGlyphPayload {
    pub svg_ref: SvgResourceId,
    pub source_range_utf8: TextSourceRange,
    pub glyph_range: GlyphRange,
    pub view_box: BoundingBox,
    /// OpenType SVG initial em-square viewport in page coordinates. Its origin
    /// is the glyph baseline, not the compatibility TextRun bounding box.
    pub font_em_box: Option<BoundingBox>,
    pub intrinsic_size: Option<LayerVector>,
    pub static_sanitized: bool,
    pub script_allowed: bool,
    pub animation_allowed: bool,
    pub external_resources_allowed: bool,
    pub interactivity_allowed: bool,
    pub transform_to_run: Option<LayerAffineTransform>,
}

impl SvgGlyphPayload {
    /// CanvasKit composes T(destination) * S(destination / viewBox) * T(-viewBox).
    /// Both the producer geometry and its fixed-decimal JSON form must fit the
    /// f32 matrix used by replay before the TextRun fallback can be suppressed.
    pub fn has_portable_view_box_mapping(&self, destination: BoundingBox) -> bool {
        bbox_is_finite_positive(self.view_box)
            && bbox_is_finite_positive(destination)
            && svg_view_box_mapping_is_portable(self.view_box, destination)
            && svg_view_box_mapping_is_portable(
                glyph_geometry_wire_bbox(self.view_box),
                glyph_geometry_wire_bbox(destination),
            )
    }

    pub fn has_static_sanitized_contract(&self) -> bool {
        text_source_range_is_non_empty(self.source_range_utf8)
            && self.glyph_range.is_non_empty()
            && bbox_is_finite_positive(self.view_box)
            && self.font_em_box.is_none_or(bbox_is_finite_positive)
            && self
                .intrinsic_size
                .map(|size| {
                    portable_glyph_scalar(size.dx)
                        && portable_glyph_scalar(size.dy)
                        && (size.dx as f32) > 0.0
                        && (size.dy as f32) > 0.0
                        && glyph_geometry_wire_scalar(size.dx, 6) > 0.0
                        && glyph_geometry_wire_scalar(size.dy, 6) > 0.0
                })
                .unwrap_or(true)
            && self.static_sanitized
            && !self.script_allowed
            && !self.animation_allowed
            && !self.external_resources_allowed
            && !self.interactivity_allowed
            && self
                .transform_to_run
                .map(layer_affine_is_finite)
                .unwrap_or(true)
    }
}

fn text_source_range_is_non_empty(range: TextSourceRange) -> bool {
    range.end > range.start
}

pub(crate) fn text_placement_is_finite(placement: &TextRunPlacement) -> bool {
    layer_affine_is_finite(placement.run_to_page) && portable_glyph_scalar(placement.baseline_y)
}

fn layer_affine_is_finite(transform: LayerAffineTransform) -> bool {
    portable_glyph_scalar(transform.a)
        && portable_glyph_scalar(transform.b)
        && portable_glyph_scalar(transform.c)
        && portable_glyph_scalar(transform.d)
        && portable_glyph_scalar(transform.e)
        && portable_glyph_scalar(transform.f)
}

pub(crate) fn bbox_is_finite_positive(bbox: BoundingBox) -> bool {
    // Selection happens before JSON export. The fixed-decimal wire rectangle
    // must also survive both replay backends, or preflight would omit a font
    // that the browser's whole-TextRun fallback still requires.
    bbox_is_positive_in_replay_space(bbox)
        && bbox_is_positive_in_replay_space(glyph_geometry_wire_bbox(bbox))
}

fn glyph_geometry_wire_bbox(bbox: BoundingBox) -> BoundingBox {
    BoundingBox::new(
        glyph_geometry_wire_scalar(bbox.x, 3),
        glyph_geometry_wire_scalar(bbox.y, 3),
        glyph_geometry_wire_scalar(bbox.width, 3),
        glyph_geometry_wire_scalar(bbox.height, 3),
    )
}

fn svg_view_box_mapping_is_portable(view_box: BoundingBox, destination: BoundingBox) -> bool {
    [
        (view_box.x, view_box.width, destination.x, destination.width),
        (
            view_box.y,
            view_box.height,
            destination.y,
            destination.height,
        ),
    ]
    .into_iter()
    .all(|(origin, extent, destination_origin, destination_extent)| {
        let scale = destination_extent / extent;
        let scaled_origin = origin * scale;
        let narrowed_scale = scale as f32;
        let narrowed_origin = (origin as f32) * narrowed_scale;
        portable_glyph_scalar(scale)
            && narrowed_scale > 0.0
            && portable_glyph_scalar(scaled_origin)
            && portable_glyph_scalar(destination_origin - scaled_origin)
            && narrowed_origin.is_finite()
            && ((destination_origin as f32) - narrowed_origin).is_finite()
    })
}

pub(crate) fn glyph_geometry_wire_scalar(value: f64, precision: usize) -> f64 {
    // Match json.rs: bbox components use 3 decimals, other glyph geometry uses 6.
    format!("{value:.precision$}").parse().unwrap_or(f64::NAN)
}

fn bbox_is_positive_in_replay_space(bbox: BoundingBox) -> bool {
    let [x, y, width, height] = [bbox.x, bbox.y, bbox.width, bbox.height].map(|v| v as f32);
    // Native Skia narrows the components before adding; CanvasKit's XYWHRect
    // adds the f64 components before storing f32 edges. Both must remain
    // finite and retain a positive span before suppressing the TextRun.
    portable_glyph_scalar(bbox.x)
        && portable_glyph_scalar(bbox.y)
        && portable_glyph_scalar(bbox.width)
        && portable_glyph_scalar(bbox.height)
        && portable_glyph_scalar(bbox.x + bbox.width)
        && portable_glyph_scalar(bbox.y + bbox.height)
        && width > 0.0
        && height > 0.0
        && [
            (x + width, y + height),
            ((bbox.x + bbox.width) as f32, (bbox.y + bbox.height) as f32),
        ]
        .into_iter()
        .all(|(right, bottom)| right.is_finite() && bottom.is_finite() && right > x && bottom > y)
}

#[derive(Debug, Clone)]
pub struct LayerGlyphOutlinePath {
    pub glyph_id: u32,
    pub source_range_utf8: TextSourceRange,
    pub glyph_range: GlyphRange,
    pub commands: Vec<PathCommand>,
    pub fill_rule: GlyphOutlineFillRule,
}

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum GlyphOutlineFillRule {
    NonZero,
    EvenOdd,
}

impl GlyphOutlineFillRule {
    pub fn as_str(self) -> &'static str {
        match self {
            Self::NonZero => "nonzero",
            Self::EvenOdd => "evenodd",
        }
    }
}

#[derive(Debug, Clone, PartialEq)]
pub struct GlyphOutlineStrokeStyle {
    pub color: ColorRef,
    pub width: f64,
    pub join: GlyphOutlineStrokeJoin,
    pub cap: GlyphOutlineStrokeCap,
    pub miter_limit: f64,
    pub paint_order: GlyphOutlinePaintOrder,
}

impl GlyphOutlineStrokeStyle {
    pub fn is_strict_subset(&self) -> bool {
        portable_glyph_scalar(self.width)
            && self.width > 0.0
            && glyph_geometry_wire_scalar(self.width, 6) > 0.0
            && portable_glyph_scalar(self.miter_limit)
            && self.miter_limit >= 1.0
            && matches!(self.join, GlyphOutlineStrokeJoin::Miter)
            && matches!(self.cap, GlyphOutlineStrokeCap::Butt)
            && matches!(
                self.paint_order,
                GlyphOutlinePaintOrder::FillThenStroke | GlyphOutlinePaintOrder::StrokeThenFill
            )
    }
}

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum GlyphOutlineStrokeJoin {
    Miter,
    Round,
    Bevel,
}

impl GlyphOutlineStrokeJoin {
    pub fn as_str(self) -> &'static str {
        match self {
            Self::Miter => "miter",
            Self::Round => "round",
            Self::Bevel => "bevel",
        }
    }
}

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum GlyphOutlineStrokeCap {
    Butt,
    Round,
    Square,
}

impl GlyphOutlineStrokeCap {
    pub fn as_str(self) -> &'static str {
        match self {
            Self::Butt => "butt",
            Self::Round => "round",
            Self::Square => "square",
        }
    }
}

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum GlyphOutlinePaintOrder {
    FillOnly,
    StrokeOnly,
    FillThenStroke,
    StrokeThenFill,
}

impl GlyphOutlinePaintOrder {
    pub fn as_str(self) -> &'static str {
        match self {
            Self::FillOnly => "fillOnly",
            Self::StrokeOnly => "strokeOnly",
            Self::FillThenStroke => "fillThenStroke",
            Self::StrokeThenFill => "strokeThenFill",
        }
    }
}

/// Variant grouping metadata for TextRun/GlyphRun/GlyphOutline alternatives.
///
/// Consumers select one `variant_id` per `equivalence_group` and paint every
/// part belonging to that variant. A `TextRun` fallback remains required.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct PaintVariantMeta {
    pub equivalence_group: String,
    pub variant_id: String,
    pub variant_kind: TextVariantKind,
    pub part_index: u32,
    pub part_count: u32,
    pub is_default_fallback: bool,
    pub requires: Vec<String>,
    pub quality: Option<TextVariantQuality>,
    pub anchor_op_id: Option<String>,
    pub local_paint_order: Option<u32>,
}

impl PaintVariantMeta {
    pub fn text_run_default(equivalence_group: impl Into<String>) -> Self {
        Self {
            equivalence_group: equivalence_group.into(),
            variant_id: "textRun".to_string(),
            variant_kind: TextVariantKind::TextRun,
            part_index: 0,
            part_count: 1,
            is_default_fallback: true,
            requires: Vec::new(),
            quality: None,
            anchor_op_id: None,
            local_paint_order: None,
        }
    }
}

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum TextVariantKind {
    TextRun,
    GlyphRun,
    GlyphOutline,
}

impl TextVariantKind {
    pub fn as_str(self) -> &'static str {
        match self {
            Self::TextRun => "textRun",
            Self::GlyphRun => "glyphRun",
            Self::GlyphOutline => "glyphOutline",
        }
    }
}

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum TextVariantQuality {
    Exact,
    PositionAdjusted,
    Approximate,
    DiagnosticOnly,
    Omitted,
}

impl TextVariantQuality {
    pub fn as_str(self) -> &'static str {
        match self {
            Self::Exact => "exact",
            Self::PositionAdjusted => "positionAdjusted",
            Self::Approximate => "approximate",
            Self::DiagnosticOnly => "diagnosticOnly",
            Self::Omitted => "omitted",
        }
    }
}

#[derive(Debug, Clone, Copy, PartialEq)]
pub struct LayerPoint {
    pub x: f64,
    pub y: f64,
}

#[derive(Debug, Clone, Copy, PartialEq)]
pub struct LayerVector {
    pub dx: f64,
    pub dy: f64,
}

#[derive(Debug, Clone, Copy, PartialEq)]
pub struct LayerAffineTransform {
    pub a: f64,
    pub b: f64,
    pub c: f64,
    pub d: f64,
    pub e: f64,
    pub f: f64,
}

#[derive(Debug, Clone, Copy, PartialEq)]
pub struct TextRunPlacement {
    pub run_to_page: LayerAffineTransform,
    pub baseline_y: f64,
}

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum GlyphRunOrientation {
    Horizontal,
    VerticalUpright,
    VerticalSideways,
    MixedPerGlyph,
}

impl GlyphRunOrientation {
    pub fn from_text_run(run: &TextRunNode) -> Self {
        if !run.is_vertical {
            Self::Horizontal
        } else if run.rotation.abs() > f64::EPSILON {
            Self::VerticalSideways
        } else {
            Self::VerticalUpright
        }
    }

    pub fn as_str(self) -> &'static str {
        match self {
            Self::Horizontal => "horizontal",
            Self::VerticalUpright => "vertical-upright",
            Self::VerticalSideways => "vertical-sideways",
            Self::MixedPerGlyph => "mixedPerGlyph",
        }
    }
}

#[derive(Debug, Clone, Copy, PartialEq)]
pub struct GlyphTransform {
    pub xx: f32,
    pub xy: f32,
    pub yx: f32,
    pub yy: f32,
    pub tx: f32,
    pub ty: f32,
}

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct GlyphRange {
    pub start: u32,
    pub end: u32,
}

impl GlyphRange {
    pub fn new(start: u32, end: u32) -> Self {
        Self { start, end }
    }

    pub fn is_non_empty(self) -> bool {
        self.end > self.start
    }
}

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum GlyphClusterFlag {
    Ligature,
    FallbackBoundary,
}

impl GlyphClusterFlag {
    pub fn as_str(self) -> &'static str {
        match self {
            Self::Ligature => "ligature",
            Self::FallbackBoundary => "fallbackBoundary",
        }
    }
}

#[derive(Debug, Clone, PartialEq)]
pub struct GlyphCluster {
    pub source_range_utf8: TextSourceRange,
    pub source_range_utf16: Option<TextSourceRange>,
    pub text_range_utf8: Option<TextSourceRange>,
    pub glyph_range: GlyphRange,
    pub flags: Vec<GlyphClusterFlag>,
}

#[derive(Debug, Clone, PartialEq)]
pub struct GlyphRunDiagnostics {
    pub quality: TextVariantQuality,
    pub replay_eligibility: GlyphRunReplayEligibility,
    pub strict_visual_eligible: bool,
    pub max_origin_delta_px: f64,
    pub max_advance_delta_px: f64,
    pub max_residual_after_adjustment_px: f64,
    pub cluster_mismatch_count: u32,
    pub missing_glyph_count: u32,
    pub used_fallback_font_count: u32,
    pub reason: Option<String>,
}

#[derive(Debug, Clone)]
pub struct PaintTextStyle {
    pub text_paint: Option<crate::model::text_paint::TextPaintStyle>,
    pub script_metrics: crate::renderer::script_metrics::ScriptMetricsContract,
    pub font_family: String,
    pub font_size: f64,
    pub font_position: Option<i8>,
    pub color: ColorRef,
    pub bold: bool,
    pub italic: bool,
    pub underline: UnderlineType,
    pub strikethrough: bool,
    pub ratio: f64,
    pub tab_leaders: Vec<crate::renderer::TabLeaderInfo>,
    pub outline_type: u8,
    pub shadow_type: u8,
    pub shadow_color: ColorRef,
    pub shadow_offset_x: f64,
    pub shadow_offset_y: f64,
    /// 공통 paint에서 확정한 연속 표본을 직렬화 소비자에게도 전달한다.
    pub continuous_shadow: Option<crate::paint::text_shadow::ContinuousTextShadow>,
    pub emboss: bool,
    pub engrave: bool,
    pub superscript: bool,
    pub subscript: bool,
    pub emphasis_dot: u8,
    pub underline_shape: u8,
    pub strike_shape: u8,
    pub underline_color: ColorRef,
    pub strike_color: ColorRef,
    pub shade_color: ColorRef,
}

impl From<&TextStyle> for PaintTextStyle {
    fn from(style: &TextStyle) -> Self {
        Self {
            script_metrics: style.script_metrics,
            font_family: style.font_family.clone(),
            font_size: style.effective_font_size(),
            font_position: style.font_position,
            color: style.color,
            bold: style.bold,
            italic: style.italic,
            underline: style.underline,
            strikethrough: style.strikethrough,
            ratio: style.ratio,
            tab_leaders: style.tab_leaders.clone(),
            text_paint: style.text_paint,
            outline_type: style.outline_type,
            shadow_type: style.shadow_type,
            shadow_color: style.shadow_color,
            shadow_offset_x: style.shadow_offset_x,
            shadow_offset_y: style.shadow_offset_y,
            continuous_shadow: style.continuous_shadow.clone(),
            emboss: style.emboss,
            engrave: style.engrave,
            superscript: style.superscript,
            subscript: style.subscript,
            emphasis_dot: style.emphasis_dot,
            underline_shape: style.underline_shape,
            strike_shape: style.strike_shape,
            underline_color: style.underline_color,
            strike_color: style.strike_color,
            shade_color: style.shade_color,
        }
    }
}

impl PaintTextStyle {
    /// Returns whether a backend may replay this text as a simple fill-only
    /// positioned glyph run without losing HWP text effects.
    pub fn is_fill_only_glyph_replay(&self) -> bool {
        self.is_simple_glyph_run_replay()
            && self.outline_type == 0
            && self.shadow_type == 0
            && !self.emboss
            && !self.engrave
    }

    /// Geometry-compatible glyph replay for backends that explicitly reproduce
    /// outline, shadow, emboss and engrave. This does not enable those effects
    /// for fill-only consumers or change the default text variant policy.
    pub fn is_simple_glyph_run_replay(&self) -> bool {
        let ratio = if self.ratio > 0.0 { self.ratio } else { 1.0 };
        self.text_paint.is_none()
            && (ratio - 1.0).abs() <= 0.001
            && self.font_size.is_finite()
            && self.font_size > 0.0
            && self.font_size <= 4096.0
            && self.tab_leaders.is_empty()
            && self.underline == UnderlineType::None
            && !self.strikethrough
            && [self.shadow_offset_x, self.shadow_offset_y]
                .into_iter()
                .all(|offset| offset.is_finite() && offset.abs() <= f32::MAX as f64)
            && !self.superscript
            && !self.subscript
            // 단순 glyph replay의 위치는 줄 기준선이다. 별도 글자 위치가 있는
            // run은 그 속성을 소비하는 positioned text 경로를 사용한다.
            && self.font_position.unwrap_or_default() == 0
            && self.emphasis_dot == 0
            // [#4155] 종전엔 흰색만 "음영 없음"으로 봐서, 미지정 잔재 0 을 가진 텍스트
            // (HWP3 변환본 전건)가 늘 fill-only 경로에서 빠졌다. 판정 정본은 model::color.
            && crate::model::color::char_shade(self.shade_color).is_none()
    }
}

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

    fn layer() -> ColorLayerNode {
        ColorLayerNode {
            layer_index: Some(0),
            glyph_id: Some(7),
            glyph_range: None,
            source_range_utf8: None,
            source_font_ref: None,
            commands: None,
            fill: None,
            fill_rule: None,
            palette_index: None,
            color: None,
            opacity: None,
            transform_to_run: None,
        }
    }

    fn payload(layers: Vec<ColorLayerNode>) -> ColorLayersPayload {
        ColorLayersPayload {
            color_format: ColorGlyphFormat::ColrV0,
            source_font_ref: None,
            palette_ref: None,
            layers,
            paint_graph: None,
            source_range_utf8: None,
            glyph_range: None,
        }
    }

    fn graph_node() -> ColorPaintGraphNode {
        ColorPaintGraphNode {
            node_id: 1,
            kind: ColorPaintGraphNodeKind::SolidPath,
            solid_path: None,
            linear_gradient_path: None,
            radial_gradient_path: None,
            sweep_gradient_path: None,
            transform: None,
            composite: None,
            clip: None,
            source_range_utf8: None,
            glyph_range: None,
            source_font_ref: None,
        }
    }

    fn graph() -> ColorPaintGraphPayload {
        ColorPaintGraphPayload {
            root_node_id: 1,
            nodes: vec![graph_node()],
        }
    }

    fn graph_of(node: ColorPaintGraphNode) -> ColorPaintGraphPayload {
        ColorPaintGraphPayload {
            root_node_id: 1,
            nodes: vec![node],
        }
    }

    fn color(rgba: [f32; 4]) -> ResolvedColor {
        ResolvedColor {
            color_space: None,
            rgba,
        }
    }

    fn square() -> Vec<PathCommand> {
        vec![
            PathCommand::MoveTo(0.0, 0.0),
            PathCommand::LineTo(10.0, 10.0),
            PathCommand::ClosePath,
        ]
    }

    fn solid_node(fill: [f32; 4]) -> ColorPaintGraphNode {
        let mut node = graph_node();
        node.solid_path = Some(ColorPaintSolidPathNode {
            commands: square(),
            fill: color(fill),
            fill_rule: GlyphOutlineFillRule::NonZero,
            source_glyph_id: None,
            palette_index: None,
        });
        node
    }

    fn linear_node(x1: f64, stop_color: [f32; 4]) -> ColorPaintGraphNode {
        let mut node = graph_node();
        node.kind = ColorPaintGraphNodeKind::LinearGradientPath;
        node.linear_gradient_path = Some(ColorPaintLinearGradientPathNode {
            commands: square(),
            gradient: ColorLinearGradient {
                x0: 0.0,
                y0: 0.0,
                x1,
                y1: 0.0,
                stops: vec![ColorGradientStop {
                    offset: 0.0,
                    color: color(stop_color),
                }],
            },
            fill_rule: GlyphOutlineFillRule::NonZero,
            source_glyph_id: None,
            palette_index: None,
        });
        node
    }

    fn graph_key(node: ColorPaintGraphNode) -> String {
        let mut payload = payload(vec![]);
        payload.paint_graph = Some(graph_of(node));
        color_layers_payload_resource_key(&payload)
    }

    /// `kind` 는 종류만 말한다. 두 SolidPath 노드가 서로 다른 색이어도 종전 키는
    /// 같았고, 캐시가 앞서 그린 색을 돌려줬다.
    #[test]
    fn graph_solid_path_fill_changes_the_resource_key() {
        assert_ne!(
            graph_key(solid_node([1.0, 0.0, 0.0, 1.0])),
            graph_key(solid_node([0.0, 0.0, 1.0, 1.0])),
            "SolidPath 채움색이 다른데 같은 캐시 키가 나왔다"
        );
    }

    #[test]
    fn graph_solid_path_geometry_changes_the_resource_key() {
        let base = solid_node([1.0, 0.0, 0.0, 1.0]);
        let mut wider = solid_node([1.0, 0.0, 0.0, 1.0]);
        wider.solid_path.as_mut().unwrap().commands = vec![
            PathCommand::MoveTo(0.0, 0.0),
            PathCommand::LineTo(99.0, 0.0),
        ];

        assert_ne!(graph_key(base), graph_key(wider));
    }

    /// 그라디언트 기하와 stop 색이 각각 키를 바꿔야 한다.
    #[test]
    fn graph_linear_gradient_geometry_and_stops_change_the_resource_key() {
        let base = graph_key(linear_node(10.0, [1.0, 0.0, 0.0, 1.0]));

        assert_ne!(
            base,
            graph_key(linear_node(20.0, [1.0, 0.0, 0.0, 1.0])),
            "그라디언트 끝점이 달라도 키가 같다"
        );
        assert_ne!(
            base,
            graph_key(linear_node(10.0, [0.0, 1.0, 0.0, 1.0])),
            "그라디언트 stop 색이 달라도 키가 같다"
        );
    }

    /// 같은 `kind` 라도 페인트 내용이 없는 노드와 있는 노드는 달라야 한다.
    #[test]
    fn graph_node_without_paint_differs_from_one_with_paint() {
        assert_ne!(
            graph_key(graph_node()),
            graph_key(solid_node([1.0, 0.0, 0.0, 1.0])),
        );
    }

    #[test]
    fn identical_graphs_share_one_key() {
        assert_eq!(
            graph_key(solid_node([0.25, 0.5, 0.75, 1.0])),
            graph_key(solid_node([0.25, 0.5, 0.75, 1.0])),
        );
    }

    /// 채워지는 색이 다르면 캐시 슬롯도 달라야 한다. 종전 키는 `fill` 을 싣지
    /// 않아 빨간 글리프와 파란 글리프가 같은 슬롯을 썼다.
    #[test]
    fn layer_fill_color_changes_the_resource_key() {
        let mut red = layer();
        red.fill = Some(ResolvedColor {
            color_space: None,
            rgba: [1.0, 0.0, 0.0, 1.0],
        });
        let mut blue = layer();
        blue.fill = Some(ResolvedColor {
            color_space: None,
            rgba: [0.0, 0.0, 1.0, 1.0],
        });

        assert_ne!(
            color_layers_payload_resource_key(&payload(vec![red])),
            color_layers_payload_resource_key(&payload(vec![blue])),
            "채움색이 다른데 같은 캐시 키가 나왔다"
        );
    }

    /// 경로 기하가 다르면 그려지는 모양이 다르다.
    #[test]
    fn layer_path_commands_change_the_resource_key() {
        let mut square = layer();
        square.commands = Some(vec![
            PathCommand::MoveTo(0.0, 0.0),
            PathCommand::LineTo(10.0, 0.0),
            PathCommand::ClosePath,
        ]);
        let mut wider = layer();
        wider.commands = Some(vec![
            PathCommand::MoveTo(0.0, 0.0),
            PathCommand::LineTo(20.0, 0.0),
            PathCommand::ClosePath,
        ]);

        assert_ne!(
            color_layers_payload_resource_key(&payload(vec![square])),
            color_layers_payload_resource_key(&payload(vec![wider])),
        );
    }

    #[test]
    fn layer_opacity_fill_rule_color_and_transform_change_the_resource_key() {
        let base = color_layers_payload_resource_key(&payload(vec![layer()]));

        let mut opaque = layer();
        opaque.opacity = Some(0.5);
        let mut ruled = layer();
        ruled.fill_rule = Some(GlyphOutlineFillRule::EvenOdd);
        let mut colored = layer();
        colored.color = Some(0x00FF_0000);
        let mut moved = layer();
        moved.transform_to_run = Some(LayerAffineTransform {
            a: 1.0,
            b: 0.0,
            c: 0.0,
            d: 1.0,
            e: 5.0,
            f: 0.0,
        });

        for (name, changed) in [
            ("opacity", opaque),
            ("fill_rule", ruled),
            ("color", colored),
            ("transform_to_run", moved),
        ] {
            assert_ne!(
                base,
                color_layers_payload_resource_key(&payload(vec![changed])),
                "{name} 이 달라도 키가 같다"
            );
        }
    }

    /// `paint_graph` 와 `layers` 는 공존한다. 그래프만 키에 실리면 레이어가
    /// 다른 두 페이로드가 같은 슬롯을 쓴다.
    #[test]
    fn layers_are_keyed_even_when_a_paint_graph_is_present() {
        let mut with_graph_a = payload(vec![layer()]);
        with_graph_a.paint_graph = Some(graph());

        let mut other = layer();
        other.glyph_id = Some(99);
        let mut with_graph_b = payload(vec![other]);
        with_graph_b.paint_graph = Some(graph());

        assert_ne!(
            color_layers_payload_resource_key(&with_graph_a),
            color_layers_payload_resource_key(&with_graph_b),
            "그래프가 같고 레이어만 다른데 키가 같다"
        );
    }

    /// 같은 입력은 같은 키여야 한다 — 캐시가 계속 빗나가면 안 된다.
    #[test]
    fn identical_payloads_share_one_key() {
        let mut a = layer();
        a.fill = Some(ResolvedColor {
            color_space: Some("srgb".to_string()),
            rgba: [0.25, 0.5, 0.75, 1.0],
        });
        a.commands = Some(vec![PathCommand::MoveTo(1.0, 2.0), PathCommand::ClosePath]);
        let b = a.clone();

        assert_eq!(
            color_layers_payload_resource_key(&payload(vec![a])),
            color_layers_payload_resource_key(&payload(vec![b])),
        );
    }
}