stet-pdf 0.8.0

PDF output device for stet PostScript interpreter
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
// stet - A PostScript Interpreter
// Copyright (c) 2026 Scott Bowman
// SPDX-License-Identifier: Apache-2.0 OR MIT

//! Convert a DisplayList into PDF content stream bytes.

use std::collections::{HashMap, HashSet};
use std::io::Write as IoWrite;

use crate::font_embedder;
use crate::font_tracker::FontTracker;
use crate::image_ops::{self, ImageXObject};
use crate::pdf_objects::PdfObj;
use crate::text_ops;
use stet_core::context::Context;
use stet_fonts::geometry::{Matrix, PsPath};
use stet_graphics::color::{DeviceColor, FillRule, LineCap, LineJoin};
use stet_graphics::device::{
    AxialShadingParams, BgUcrState, HalftoneState, MeshShadingParams, PatchShadingParams,
    PatternFillParams, RadialShadingParams, SpotColor, SpotColorSpace, StrokeParams, TextParams,
    TransferState,
};
use stet_graphics::display_list::{DisplayElement, DisplayList};

/// Result of generating a content stream from a display list.
pub struct ContentStreamResult {
    /// Raw content stream bytes (before compression).
    pub content: Vec<u8>,
    /// Image XObjects referenced by the content stream.
    pub images: Vec<ImageXObject>,
    /// Indices into the display list for shading elements, paired with
    /// the shading resource name index used in the content stream.
    pub shading_refs: Vec<ShadingRef>,
    /// PDF font names used on this page (e.g., ["F0", "F2"]).
    pub used_font_names: Vec<String>,
    /// ExtGState resource dicts used in the content stream.
    pub ext_gstate_dicts: Vec<ExtGStateDict>,
    /// Color space definitions used in the content stream (Separation/DeviceN).
    /// Vec of (resource_name, SpotColorSpace) pairs.
    pub color_spaces: Vec<(String, SpotColorSpace)>,
    /// ICCBased color space definitions used in the content stream (one
    /// per unique source profile, deduped by `IccColorSpace.profile_hash`).
    /// Vec of (resource_name, IccColorSpace) pairs.
    pub icc_color_spaces: Vec<(String, stet_graphics::device::IccColorSpace)>,
    /// Tiling pattern references used in the content stream.
    pub pattern_refs: Vec<PatternRef>,
    /// Color space entries for uncolored patterns (e.g., [/Pattern /DeviceRGB]).
    pub pattern_cs_entries: Vec<(String, PdfObj)>,
    /// Transfer function references to emit as PDF Type 0 function objects.
    pub transfer_refs: Vec<TransferFunctionRef>,
    /// Halftone references to emit as PDF halftone objects.
    pub halftone_refs: Vec<HalftoneRef>,
    /// Black generation / undercolor removal references for PDF output.
    pub bg_ucr_refs: Vec<BgUcrRef>,
    /// Soft-mask references to patch into ExtGState dicts at write time
    /// (the mask Form XObject's indirect ref is allocated in
    /// `pdf_device.rs`, not here).
    pub soft_mask_refs: Vec<SoftMaskRef>,
    /// Optional-content markers (`/OC /Pn BDC … EMC`) emitted into the
    /// content stream. `pdf_device.rs` builds the corresponding `/OCG`
    /// or `/OCMD` indirect objects and wires them through the page's
    /// `/Resources /Properties` dict + the Catalog's `/OCProperties`.
    pub ocg_marker_refs: Vec<OcgMarkerRef>,
    /// Form XObjects emitted for `DisplayElement::Group` and the content
    /// portion of `DisplayElement::SoftMasked`. The Forms inherit the
    /// page's `/Resources` (PDF 1.7 § 7.8.3), so they carry no `/Resources`
    /// dict of their own; whatever fonts / images / ext-gstates the Form's
    /// content stream references is already in the page-level
    /// resource lists above.
    pub form_xobjects: Vec<FormXObject>,
}

/// A PDF Form XObject — a self-contained content stream wrapped as an
/// indirect object so it can be invoked via `/Xn Do`. stet emits one for
/// each `DisplayElement::Group` and for the mask portion of
/// `DisplayElement::SoftMasked`. The Form's resources are inherited from
/// the enclosing page, so this struct carries only the per-form data.
pub struct FormXObject {
    /// Raw content stream bytes (before compression).
    pub content: Vec<u8>,
    /// `/BBox` in the enclosing content stream's user coordinate system
    /// (device space, the same units the parent's paths use).
    pub bbox: [f64; 4],
    /// Entries that go into the `/Group` transparency dict. `None` means
    /// emit no `/Group` entry — used for the mask Form on a `SoftMasked`
    /// element (the mask doesn't need its own transparency group), and
    /// for other Forms that don't need transparency-group semantics.
    pub group_dict_entries: Option<Vec<(Vec<u8>, PdfObj)>>,
}

/// Reference from an ExtGState to pre-sampled transfer function tables.
pub struct TransferFunctionRef {
    /// Index into ext_gstate_dicts.
    pub ext_gstate_idx: usize,
    /// For single transfer: Some(table) in index 0, rest None.
    /// For 4-component: [R, G, B, Gray], each Some or None (identity).
    pub tables: Vec<Option<std::sync::Arc<Vec<f64>>>>,
    /// True if this is a 4-component (color) transfer.
    pub is_color: bool,
}

/// Reference from an ExtGState to pre-computed halftone screen data.
pub struct HalftoneRef {
    /// Index into ext_gstate_dicts.
    pub ext_gstate_idx: usize,
    /// Halftone state captured at paint time.
    pub state: HalftoneState,
}

/// Reference from an ExtGState to pre-sampled black generation / UCR tables.
pub struct BgUcrRef {
    /// Index into ext_gstate_dicts.
    pub ext_gstate_idx: usize,
    /// BG/UCR state captured at paint time.
    pub state: BgUcrState,
}

/// One Optional-Content marker `(/OC /Pn BDC … EMC)` recorded by the
/// content stream. The Builder allocates the resource name `Pn` at
/// emission time; `pdf_device.rs` resolves the visibility predicate
/// into the right indirect object (a single `/OCG` for the `Single`
/// case, an `/OCMD` for `Membership` / `Expression`) and adds it to the
/// page's `/Resources /Properties` dict.
pub struct OcgMarkerRef {
    /// Resource name written into the content stream (`Pn`).
    pub resource_name: String,
    /// Visibility predicate from the source DisplayList.
    pub visibility: stet_graphics::display_list::OcgVisibility,
}

/// Reference from an ExtGState dict to a soft-mask Form XObject. The
/// content stream emits a placeholder ExtGState dict (just `/Type`)
/// during generation, then `pdf_device.rs` patches the dict with a real
/// `/SMask << /Type /Mask /S /Alpha|/Luminosity /G <form-ref> >>` entry
/// once the Form XObject's indirect object number is known.
pub struct SoftMaskRef {
    /// Index into `ext_gstate_dicts`.
    pub ext_gstate_idx: usize,
    /// Index into `form_xobjects` — the mask form.
    pub mask_form_idx: usize,
    /// `/S` entry on the `/SMask` dict.
    pub subtype: stet_graphics::display_list::SoftMaskSubtype,
    /// `/BC` backdrop color (used only for `/Luminosity` masks).
    pub backdrop_color: Option<[f64; 3]>,
    /// True when the mask values should be inverted — emitted as
    /// `/TR { 1 exch sub }` on the `/SMask` dict.
    pub transfer_invert: bool,
}

/// Reference to a tiling pattern that needs a PDF Pattern XObject.
pub struct PatternRef {
    /// Pre-rendered display list for a single tile.
    pub tile: DisplayList,
    /// Pattern matrix (pattern space → device space).
    pub pattern_matrix: Matrix,
    /// Bounding box of one tile in pattern space [llx, lly, urx, ury].
    pub bbox: [f64; 4],
    /// Horizontal step between tile origins.
    pub xstep: f64,
    /// Vertical step between tile origins.
    pub ystep: f64,
    /// Paint type: 1 = colored, 2 = uncolored.
    pub paint_type: i32,
}

/// An ExtGState resource used in the content stream.
pub struct ExtGStateDict {
    /// PDF dict entries (key-value pairs for the ExtGState resource).
    pub entries: Vec<(Vec<u8>, PdfObj)>,
}

/// Reference to a shading element that needs a PDF shading resource.
pub enum ShadingRef {
    Axial(AxialShadingParams),
    Radial(RadialShadingParams),
    Mesh(MeshShadingParams),
    Patch(PatchShadingParams),
}

/// Cached graphics state for suppressing redundant PDF operators.
#[derive(Clone)]
struct GState {
    fill_color: Option<PdfColor>,
    stroke_color: Option<PdfColor>,
    line_width: f64,
    line_cap: i32,
    line_join: i32,
    miter_limit: f64,
    dash_array: Vec<f64>,
    dash_offset: f64,
    /// `None` = no /OP emission yet in this content stream. The first
    /// paint always force-emits its overprint state so a Form XObject's
    /// content doesn't silently inherit /OP=true from the calling page
    /// scope (per PDF 1.7 §7.8.3 a Form inherits the gstate at /Do time,
    /// but stet's writer treats each Form as a fresh emission context).
    overprint: Option<bool>,
    /// Overprint mode currently set in the PDF graphics state. -1 = no
    /// /OPM emitted yet (PDF default of 0); otherwise the most-recent
    /// value pushed. Tracked separately from `overprint` because OPM is
    /// a distinct graphics-state entry and stet has to round-trip
    /// `params.overprint_mode` from the DisplayList faithfully (the
    /// previous hardcoded /OPM 1 silently broke GWG K-knockouts).
    overprint_mode: i32,
    /// Most-recent /ca (non-stroking alpha) emitted. Tracked separately
    /// from /CA because PDF allows them to be set independently on an
    /// ExtGState dict.
    fill_alpha: f64,
    /// Most-recent /CA (stroking alpha) emitted.
    stroke_alpha: f64,
    /// Most-recent /BM (blend mode) emitted. Blend mode is a shared
    /// graphics-state entry — fills and strokes use the same one.
    blend_mode: u8,
    /// Current fill color space resource name (e.g., "CS0") for Separation/DeviceN.
    fill_cs_name: Option<String>,
    /// Current stroke color space resource name.
    stroke_cs_name: Option<String>,
    /// Rendering intent (0=RelativeColorimetric, 1=Absolute, 2=Perceptual, 3=Saturation).
    rendering_intent: u8,
    /// Dedup key for current transfer state.
    transfer_key: Vec<u8>,
    /// Dedup key for current halftone state.
    halftone_key: Vec<u8>,
    /// Dedup key for current BG/UCR state.
    bg_ucr_key: Vec<u8>,
}

impl GState {
    fn new() -> Self {
        Self {
            fill_color: None,
            stroke_color: None,
            line_width: -1.0, // force first emission
            line_cap: -1,
            line_join: -1,
            miter_limit: -1.0,
            dash_array: Vec::new(),
            dash_offset: -1.0,
            overprint: None,
            overprint_mode: -1,
            fill_alpha: 1.0,
            stroke_alpha: 1.0,
            blend_mode: 0,
            fill_cs_name: None,
            stroke_cs_name: None,
            rendering_intent: 0,
            transfer_key: Vec::new(),
            halftone_key: Vec::new(),
            bg_ucr_key: Vec::new(),
        }
    }

    fn reset(&mut self) {
        *self = Self::new();
    }
}

#[derive(Clone, Debug, PartialEq)]
enum PdfColor {
    Gray(u16),          // quantized to 0..10000
    Rgb(u16, u16, u16), // quantized
    Cmyk(u16, u16, u16, u16),
}

fn quantize(v: f64) -> u16 {
    (v.clamp(0.0, 1.0) * 10000.0) as u16
}

#[cfg(test)]
fn color_to_pdf(c: &DeviceColor) -> PdfColor {
    color_to_pdf_with_channels(c, 0)
}

/// Same as [`color_to_pdf`] but honors the source paint's CMYK channel mask.
///
/// When `painted_channels == CMYK_K` and `native_cmyk = (0, 0, 0, k)`, the
/// paint originated as DeviceGray and was promoted to K-only DeviceCMYK by
/// the PDF reader's `gray_paint_for_gstate`. PDF's OPM semantics differ
/// between DeviceGray and DeviceCMYK (OPM only applies to DeviceCMYK
/// colorants), so a round-trip must emit it back as `g` — emitting `k`
/// would let OPM-1 preserve the underlying CMY components and let the
/// background leak through.
fn color_to_pdf_with_channels(c: &DeviceColor, painted_channels: u8) -> PdfColor {
    use stet_graphics::device::CMYK_K;
    if let Some((c_val, m, y, k)) = c.native_cmyk {
        if painted_channels == CMYK_K && c_val == 0.0 && m == 0.0 && y == 0.0 {
            let g = (1.0 - k).clamp(0.0, 1.0);
            return PdfColor::Gray(quantize(g));
        }
        PdfColor::Cmyk(quantize(c_val), quantize(m), quantize(y), quantize(k))
    } else if c.r == c.g && c.g == c.b {
        PdfColor::Gray(quantize(c.r))
    } else {
        PdfColor::Rgb(quantize(c.r), quantize(c.g), quantize(c.b))
    }
}

/// Stateful builder for one content stream — a page or a tile pattern.
/// Owns the mutable state per-element emission needs, and exposes
/// `emit_list` so nested DisplayLists (the children of Group /
/// SoftMasked / OcgGroup) can be processed recursively with the same
/// state.
struct Builder<'tracker> {
    buf: Vec<u8>,
    images: Vec<ImageXObject>,
    shading_refs: Vec<ShadingRef>,
    clip_depth: u32,
    /// Parallel stack to PDF's q/Q gstate save frames, one entry per
    /// open `Clip` (each emits `q`). InitClip pops in reverse, restoring
    /// `self.gs` to the value saved at the matching Clip's `q`. Without
    /// this, the tracker resets to default after InitClip but PDF's
    /// real gstate restores to whatever was active at the matching q —
    /// so the next paint's emit_overprint/emit_paint_alpha_blend
    /// disagree with reality and skip the operator that would fix the
    /// PDF state (visible as overprint leaking past clip scopes).
    clip_gs_stack: Vec<GState>,
    /// q-scopes the writer has open. Each scope is the list of clip
    /// paths added to that scope. Multiple Clips in one scope emit
    /// `path W n` operations one after another in the same `q...Q` block
    /// rather than nesting a new q for each — that's what PDF source
    /// streams typically look like and what avoids round-trip growth
    /// from the reader's `InitClip + replay-of-outer-clips` pattern.
    clip_scopes: Vec<Vec<stet_fonts::geometry::PsPath>>,
    /// Paths queued for skip-on-emit after the most recent InitClip.
    /// Each InitClip seeds this with the still-active clips (i.e. the
    /// flattened `clip_scopes`). Subsequent Clip elements consume the
    /// front of the queue when paths match; once drained or mismatched,
    /// emission resumes normally — additional clips go into the
    /// currently-open scope without opening a fresh `q`.
    pending_replay_clips: std::collections::VecDeque<stet_fonts::geometry::PsPath>,
    gs: GState,
    ext_gstates: Vec<ExtGStateDict>,
    ext_gstate_map: HashMap<Vec<u8>, usize>,
    color_spaces: Vec<(String, SpotColorSpace)>,
    cs_name_map: HashMap<Vec<u8>, String>,
    icc_color_spaces: Vec<(String, stet_graphics::device::IccColorSpace)>,
    icc_cs_name_map: HashMap<Vec<u8>, String>,
    pattern_refs: Vec<PatternRef>,
    pattern_map: HashMap<u32, usize>,
    pattern_cs_names: Vec<(String, PdfObj)>,
    pattern_cs_set: HashSet<String>,
    transfer_refs: Vec<TransferFunctionRef>,
    halftone_refs: Vec<HalftoneRef>,
    bg_ucr_refs: Vec<BgUcrRef>,
    soft_mask_refs: Vec<SoftMaskRef>,
    ocg_marker_refs: Vec<OcgMarkerRef>,
    form_xobjects: Vec<FormXObject>,
    page_font_names: HashSet<String>,
    has_text_elements: bool,
    page_w: u32,
    page_h: u32,
    /// True when emitting a Pattern XObject tile. `ErasePage` is a no-op
    /// in this mode — tiles have no page background.
    in_tile: bool,
    font_tracker: &'tracker mut FontTracker,
}

impl<'tracker> Builder<'tracker> {
    fn new(
        font_tracker: &'tracker mut FontTracker,
        page_w: u32,
        page_h: u32,
        has_text_elements: bool,
        in_tile: bool,
    ) -> Self {
        Self {
            buf: Vec::with_capacity(if in_tile { 1024 } else { 4096 }),
            images: Vec::new(),
            shading_refs: Vec::new(),
            clip_depth: 0,
            clip_gs_stack: Vec::new(),
            clip_scopes: Vec::new(),
            pending_replay_clips: std::collections::VecDeque::new(),
            gs: GState::new(),
            ext_gstates: Vec::new(),
            ext_gstate_map: HashMap::new(),
            color_spaces: Vec::new(),
            cs_name_map: HashMap::new(),
            icc_color_spaces: Vec::new(),
            icc_cs_name_map: HashMap::new(),
            pattern_refs: Vec::new(),
            pattern_map: HashMap::new(),
            pattern_cs_names: Vec::new(),
            pattern_cs_set: HashSet::new(),
            transfer_refs: Vec::new(),
            halftone_refs: Vec::new(),
            bg_ucr_refs: Vec::new(),
            soft_mask_refs: Vec::new(),
            ocg_marker_refs: Vec::new(),
            form_xobjects: Vec::new(),
            page_font_names: HashSet::new(),
            has_text_elements,
            page_w,
            page_h,
            in_tile,
            font_tracker,
        }
    }

    /// Walk a DisplayList and emit each element. May recurse via the
    /// Group / SoftMasked / OcgGroup arms.
    fn emit_list<'a>(&mut self, list: &'a DisplayList) {
        let mut text_batch: Vec<&'a TextParams> = Vec::new();
        let mut batch_font: Option<u32> = None;
        for element in list.elements() {
            self.emit_element(element, &mut text_batch, &mut batch_font);
        }
        flush_text_batch(&text_batch, self.font_tracker, &mut self.buf, &mut self.gs);
    }

    fn emit_element<'a>(
        &mut self,
        element: &'a DisplayElement,
        text_batch: &mut Vec<&'a TextParams>,
        batch_font: &mut Option<u32>,
    ) {
        // Text-batching prelude. Text accumulates into the current
        // batch; non-Text elements flush the batch before processing.
        // Glyph-path Fill/Stroke elements paired with Text in the PS
        // pipeline get skipped without disturbing the batch; the same
        // element shapes from the PDF reader (no Text companion) fall
        // through to the main match.
        match element {
            DisplayElement::Text { params } => {
                if *batch_font == Some(params.font_entity) {
                    text_batch.push(params);
                } else {
                    flush_text_batch(text_batch, self.font_tracker, &mut self.buf, &mut self.gs);
                    text_batch.clear();
                    text_batch.push(params);
                    *batch_font = Some(params.font_entity);
                }
                return;
            }
            DisplayElement::Fill { params, .. }
                if params.is_text_glyph && self.has_text_elements =>
            {
                return;
            }
            DisplayElement::Stroke { params, .. }
                if params.is_text_glyph && self.has_text_elements =>
            {
                return;
            }
            _ => {
                flush_text_batch(text_batch, self.font_tracker, &mut self.buf, &mut self.gs);
                text_batch.clear();
                *batch_font = None;
            }
        }

        match element {
            DisplayElement::ErasePage => {
                if self.in_tile {
                    // Tiles have no page background — skip.
                    return;
                }
                self.buf.extend(b"1 g 0 0 ");
                fmt_num(&mut self.buf, self.page_w as f64);
                self.buf.push(b' ');
                fmt_num(&mut self.buf, self.page_h as f64);
                self.buf.extend(b" re f\n");
                self.gs.fill_color = Some(PdfColor::Gray(10000));
            }
            DisplayElement::Fill { path, params } => {
                if params.is_text_glyph && self.has_text_elements {
                    return;
                }
                emit_transfer(
                    &mut self.buf,
                    &params.transfer,
                    &mut self.gs,
                    &mut self.ext_gstates,
                    &mut self.ext_gstate_map,
                    &mut self.transfer_refs,
                );
                emit_halftone(
                    &mut self.buf,
                    &params.halftone,
                    &mut self.gs,
                    &mut self.ext_gstates,
                    &mut self.ext_gstate_map,
                    &mut self.halftone_refs,
                );
                emit_bg_ucr(
                    &mut self.buf,
                    &params.bg_ucr,
                    &mut self.gs,
                    &mut self.ext_gstates,
                    &mut self.ext_gstate_map,
                    &mut self.bg_ucr_refs,
                );
                emit_rendering_intent(&mut self.buf, params.rendering_intent, &mut self.gs);
                emit_overprint(
                    &mut self.buf,
                    params.overprint,
                    params.overprint_mode,
                    &mut self.gs,
                    &mut self.ext_gstates,
                    &mut self.ext_gstate_map,
                );
                emit_paint_alpha_blend(
                    &mut self.buf,
                    false,
                    params.alpha,
                    params.blend_mode,
                    &mut self.gs,
                    &mut self.ext_gstates,
                    &mut self.ext_gstate_map,
                );
                if let Some(spot) = &params.spot_color {
                    emit_fill_color_spot(
                        &mut self.buf,
                        spot,
                        &mut self.gs,
                        &mut self.cs_name_map,
                        &mut self.color_spaces,
                    );
                } else if let Some(icc) = &params.icc_color {
                    emit_fill_color_icc(
                        &mut self.buf,
                        icc,
                        &mut self.gs,
                        &mut self.icc_cs_name_map,
                        &mut self.icc_color_spaces,
                    );
                } else {
                    if self.gs.fill_cs_name.is_some() {
                        self.gs.fill_cs_name = None;
                        self.gs.fill_color = None;
                    }
                    emit_fill_color(
                        &mut self.buf,
                        &params.color,
                        params.painted_channels,
                        &mut self.gs,
                    );
                }
                emit_path(&mut self.buf, path);
                if params.fill_rule == FillRule::EvenOdd {
                    self.buf.extend(b"f*\n");
                } else {
                    self.buf.extend(b"f\n");
                }
            }
            DisplayElement::Stroke { path, params } => {
                if params.is_text_glyph && self.has_text_elements {
                    return;
                }
                let has_ctm = !is_identity(&params.ctm);
                // PDF `q` saves the gstate and `Q` restores it. Mirror that
                // in our tracker by snapshotting `self.gs` before `q` and
                // restoring after `Q` — otherwise state changes we emit
                // inside the q/Q block (CTM, color, line, overprint, …)
                // would leak past the `Q` in the tracker's view, making
                // the next paint think e.g. overprint is still on when
                // PDF has already popped it.
                let saved_gs = if has_ctm {
                    let saved = self.gs.clone();
                    self.buf.extend(b"q\n");
                    emit_cm(&mut self.buf, &params.ctm);
                    Some(saved)
                } else {
                    None
                };
                emit_transfer(
                    &mut self.buf,
                    &params.transfer,
                    &mut self.gs,
                    &mut self.ext_gstates,
                    &mut self.ext_gstate_map,
                    &mut self.transfer_refs,
                );
                emit_halftone(
                    &mut self.buf,
                    &params.halftone,
                    &mut self.gs,
                    &mut self.ext_gstates,
                    &mut self.ext_gstate_map,
                    &mut self.halftone_refs,
                );
                emit_bg_ucr(
                    &mut self.buf,
                    &params.bg_ucr,
                    &mut self.gs,
                    &mut self.ext_gstates,
                    &mut self.ext_gstate_map,
                    &mut self.bg_ucr_refs,
                );
                emit_rendering_intent(&mut self.buf, params.rendering_intent, &mut self.gs);
                emit_overprint(
                    &mut self.buf,
                    params.overprint,
                    params.overprint_mode,
                    &mut self.gs,
                    &mut self.ext_gstates,
                    &mut self.ext_gstate_map,
                );
                emit_paint_alpha_blend(
                    &mut self.buf,
                    true,
                    params.alpha,
                    params.blend_mode,
                    &mut self.gs,
                    &mut self.ext_gstates,
                    &mut self.ext_gstate_map,
                );
                if let Some(spot) = &params.spot_color {
                    emit_stroke_color_spot(
                        &mut self.buf,
                        spot,
                        &mut self.gs,
                        &mut self.cs_name_map,
                        &mut self.color_spaces,
                    );
                } else if let Some(icc) = &params.icc_color {
                    emit_stroke_color_icc(
                        &mut self.buf,
                        icc,
                        &mut self.gs,
                        &mut self.icc_cs_name_map,
                        &mut self.icc_color_spaces,
                    );
                } else {
                    if self.gs.stroke_cs_name.is_some() {
                        self.gs.stroke_cs_name = None;
                        self.gs.stroke_color = None;
                    }
                    emit_stroke_color(
                        &mut self.buf,
                        &params.color,
                        params.painted_channels,
                        &mut self.gs,
                    );
                }
                emit_line_state(&mut self.buf, params, &mut self.gs);
                emit_path(&mut self.buf, path);
                self.buf.extend(b"S\n");
                if let Some(saved) = saved_gs {
                    self.buf.extend(b"Q\n");
                    self.gs = saved;
                }
            }
            DisplayElement::Clip { path, params } => {
                // Replay detection: the reader emits one Clip per still-
                // active clip after every Q (see `restore_clip_from_stack`
                // in stet-pdf-reader). These are state descriptions, not
                // new clips. Consume them silently.
                if let Some(expected) = self.pending_replay_clips.front()
                    && paths_equal(expected, path)
                {
                    self.pending_replay_clips.pop_front();
                    return;
                }
                // Unmatched at this point — discard the rest of the
                // queue so subsequent real clips don't get accidentally
                // dropped.
                self.pending_replay_clips.clear();
                // Open a fresh q scope only when none is currently open;
                // additional clips go into the existing scope by emitting
                // just `path W n`. PDF source streams routinely chain
                // multiple `W n` operations in a single `q ... Q` block
                // (e.g. `q W(A) W(B) Q`), and mirroring that here keeps
                // the round-trip stream-shape-stable.
                if self.clip_scopes.is_empty() {
                    self.clip_gs_stack.push(self.gs.clone());
                    self.buf.extend(b"q\n");
                    self.clip_depth += 1;
                    self.clip_scopes.push(Vec::new());
                }
                emit_path(&mut self.buf, path);
                if params.fill_rule == FillRule::EvenOdd {
                    self.buf.extend(b"W* n\n");
                } else {
                    self.buf.extend(b"W n\n");
                }
                if let Some(scope) = self.clip_scopes.last_mut() {
                    scope.push(path.clone());
                }
            }
            DisplayElement::InitClip => {
                if let Some(_popped) = self.clip_scopes.pop() {
                    self.buf.extend(b"Q\n");
                    if let Some(prev) = self.clip_gs_stack.pop() {
                        self.gs = prev;
                    } else {
                        self.gs.reset();
                    }
                    if self.clip_depth > 0 {
                        self.clip_depth -= 1;
                    }
                }
                // Seed the replay queue with all clips still active
                // (every path in every remaining open scope). The
                // reader's restore_clip_from_stack emits one Clip per
                // entry in `clip_stack` (outermost first); the next K
                // Clip arms consume those.
                self.pending_replay_clips = self
                    .clip_scopes
                    .iter()
                    .flat_map(|s| s.iter().cloned())
                    .collect();
            }
            DisplayElement::Image {
                sample_data,
                params,
            } => {
                let img_idx = self.images.len();
                let xobj = image_ops::convert_image(sample_data, params);
                let m = compute_image_matrix(params);
                let pre_q_gs = self.gs.clone();
                self.buf.extend(b"q ");
                emit_matrix(&mut self.buf, &m);
                self.buf.extend(b" cm\n");
                emit_overprint(
                    &mut self.buf,
                    params.overprint,
                    params.overprint_mode,
                    &mut self.gs,
                    &mut self.ext_gstates,
                    &mut self.ext_gstate_map,
                );
                emit_paint_alpha_blend(
                    &mut self.buf,
                    false,
                    params.alpha,
                    params.blend_mode,
                    &mut self.gs,
                    &mut self.ext_gstates,
                    &mut self.ext_gstate_map,
                );
                if xobj.is_imagemask {
                    if let Some(ref spot) = xobj.mask_spot_color {
                        // Spot/DeviceN imagemask fill — emit `/CSn cs + tint scn`
                        // so the round-trip PDF preserves the spot identity.
                        // Without this the imagemask paint collapses to its
                        // alt-CMYK and a spot-over-cmyk overprint loses its
                        // tint-blend behavior (visible white-X on GWG 2.0
                        // mask cells in the round-trip).
                        emit_fill_color_spot(
                            &mut self.buf,
                            spot,
                            &mut self.gs,
                            &mut self.cs_name_map,
                            &mut self.color_spaces,
                        );
                    } else if let Some(ref mask_color) = xobj.mask_color {
                        // Emit the imagemask's fill color through the same
                        // DeviceColor-aware path the regular Fill arm uses, so a
                        // CMYK source paint (native_cmyk = Some) round-trips as
                        // `c m y k k` rather than getting downconverted to
                        // `r g b rg`. Without this the imagemask's color reads
                        // back as DeviceRGB and OPM-1 overprint with a CMYK
                        // backdrop misbehaves (visible on PDFX-Output-Test
                        // GWG 2.0 image / mask cells).
                        if self.gs.fill_cs_name.is_some() {
                            self.gs.fill_cs_name = None;
                            self.gs.fill_color = None;
                        }
                        emit_fill_color(
                            &mut self.buf,
                            mask_color,
                            params.painted_channels,
                            &mut self.gs,
                        );
                    }
                }
                writeln!(self.buf, "/Im{} Do Q", img_idx).unwrap();
                self.gs = pre_q_gs;
                self.images.push(xobj);
            }
            DisplayElement::AxialShading { params } => {
                let sh_idx = self.shading_refs.len();
                let pre_q_gs = self.gs.clone();
                self.buf.extend(b"q\n");
                if !is_identity(&params.ctm) {
                    emit_matrix(&mut self.buf, &params.ctm);
                    self.buf.extend(b" cm\n");
                }
                emit_overprint(
                    &mut self.buf,
                    params.overprint,
                    params.overprint_mode,
                    &mut self.gs,
                    &mut self.ext_gstates,
                    &mut self.ext_gstate_map,
                );
                emit_paint_alpha_blend(
                    &mut self.buf,
                    false,
                    params.alpha,
                    params.blend_mode,
                    &mut self.gs,
                    &mut self.ext_gstates,
                    &mut self.ext_gstate_map,
                );
                writeln!(self.buf, "/Sh{} sh Q", sh_idx).unwrap();
                self.gs = pre_q_gs;
                self.shading_refs.push(ShadingRef::Axial(params.clone()));
            }
            DisplayElement::RadialShading { params } => {
                let sh_idx = self.shading_refs.len();
                let pre_q_gs = self.gs.clone();
                self.buf.extend(b"q\n");
                if !is_identity(&params.ctm) {
                    emit_matrix(&mut self.buf, &params.ctm);
                    self.buf.extend(b" cm\n");
                }
                emit_overprint(
                    &mut self.buf,
                    params.overprint,
                    params.overprint_mode,
                    &mut self.gs,
                    &mut self.ext_gstates,
                    &mut self.ext_gstate_map,
                );
                emit_paint_alpha_blend(
                    &mut self.buf,
                    false,
                    params.alpha,
                    params.blend_mode,
                    &mut self.gs,
                    &mut self.ext_gstates,
                    &mut self.ext_gstate_map,
                );
                writeln!(self.buf, "/Sh{} sh Q", sh_idx).unwrap();
                self.gs = pre_q_gs;
                self.shading_refs.push(ShadingRef::Radial(params.clone()));
            }
            DisplayElement::MeshShading { params } => {
                let sh_idx = self.shading_refs.len();
                let pre_q_gs = self.gs.clone();
                self.buf.extend(b"q\n");
                if !is_identity(&params.ctm) {
                    emit_matrix(&mut self.buf, &params.ctm);
                    self.buf.extend(b" cm\n");
                }
                emit_overprint(
                    &mut self.buf,
                    params.overprint,
                    params.overprint_mode,
                    &mut self.gs,
                    &mut self.ext_gstates,
                    &mut self.ext_gstate_map,
                );
                emit_paint_alpha_blend(
                    &mut self.buf,
                    false,
                    params.alpha,
                    params.blend_mode,
                    &mut self.gs,
                    &mut self.ext_gstates,
                    &mut self.ext_gstate_map,
                );
                writeln!(self.buf, "/Sh{} sh Q", sh_idx).unwrap();
                self.gs = pre_q_gs;
                self.shading_refs.push(ShadingRef::Mesh(params.clone()));
            }
            DisplayElement::PatchShading { params } => {
                let sh_idx = self.shading_refs.len();
                let pre_q_gs = self.gs.clone();
                self.buf.extend(b"q\n");
                if !is_identity(&params.ctm) {
                    emit_matrix(&mut self.buf, &params.ctm);
                    self.buf.extend(b" cm\n");
                }
                emit_overprint(
                    &mut self.buf,
                    params.overprint,
                    params.overprint_mode,
                    &mut self.gs,
                    &mut self.ext_gstates,
                    &mut self.ext_gstate_map,
                );
                emit_paint_alpha_blend(
                    &mut self.buf,
                    false,
                    params.alpha,
                    params.blend_mode,
                    &mut self.gs,
                    &mut self.ext_gstates,
                    &mut self.ext_gstate_map,
                );
                writeln!(self.buf, "/Sh{} sh Q", sh_idx).unwrap();
                self.gs = pre_q_gs;
                self.shading_refs.push(ShadingRef::Patch(params.clone()));
            }
            DisplayElement::PatternFill { params } => {
                emit_pattern_fill(
                    &mut self.buf,
                    params,
                    &mut self.gs,
                    &mut self.pattern_refs,
                    &mut self.pattern_map,
                    &mut self.pattern_cs_names,
                    &mut self.pattern_cs_set,
                );
            }
            DisplayElement::Text { .. } => unreachable!(), // handled in prelude
            DisplayElement::Group { elements, params } => {
                // Build the Form XObject's content stream by swapping in
                // a fresh buffer and recursing. Resources (images, fonts,
                // ext_gstates, …) stay on the page-level Builder; the
                // Form inherits the page's /Resources per PDF 1.7
                // § 7.8.3, so we never have to duplicate them.
                let saved_buf = std::mem::take(&mut self.buf);
                let saved_gs = std::mem::replace(&mut self.gs, GState::new());
                let saved_clip_depth = std::mem::replace(&mut self.clip_depth, 0);
                let saved_clip_gs_stack = std::mem::take(&mut self.clip_gs_stack);

                self.emit_list(elements);

                // Close any clips still open at the end of the form's
                // content stream — the implicit Q after the form's body
                // would balance them out anyway, but explicit close keeps
                // the stream well-formed under viewer inspection.
                for _ in 0..self.clip_depth {
                    self.buf.extend(b"Q\n");
                }

                let form_content = std::mem::replace(&mut self.buf, saved_buf);
                self.gs = saved_gs;
                self.clip_depth = saved_clip_depth;
                self.clip_gs_stack = saved_clip_gs_stack;

                let form_idx = self.form_xobjects.len();
                let form_name = format!("X{}", form_idx);

                let mut group_entries: Vec<(Vec<u8>, PdfObj)> = vec![
                    (b"Type".to_vec(), PdfObj::name("Group")),
                    (b"S".to_vec(), PdfObj::name("Transparency")),
                ];
                if params.isolated {
                    group_entries.push((b"I".to_vec(), PdfObj::Bool(true)));
                }
                if params.knockout {
                    group_entries.push((b"K".to_vec(), PdfObj::Bool(true)));
                }
                let cs_name: Option<&str> = match params.color_space {
                    stet_graphics::display_list::GroupColorSpace::DeviceGray => Some("DeviceGray"),
                    stet_graphics::display_list::GroupColorSpace::DeviceRGB => Some("DeviceRGB"),
                    stet_graphics::display_list::GroupColorSpace::DeviceCMYK => Some("DeviceCMYK"),
                    stet_graphics::display_list::GroupColorSpace::Inherited => None,
                };
                if let Some(name) = cs_name {
                    group_entries.push((b"CS".to_vec(), PdfObj::name(name)));
                }

                self.form_xobjects.push(FormXObject {
                    content: form_content,
                    bbox: params.bbox,
                    group_dict_entries: Some(group_entries),
                });

                // Invoke the Form on the parent stream. Wrap in q/Q so
                // any /CA/ca/BM ExtGState we push is local to this /Do.
                // Snapshot and restore the gs tracker around the q/Q so
                // the alpha/blend pushed inside (and any state the Form
                // changed and tried to leak) doesn't fool the tracker
                // into thinking PDF state changed past the `Q`.
                let pre_q_gs = self.gs.clone();
                self.buf.extend(b"q\n");
                if params.alpha < 1.0 || params.blend_mode != 0 {
                    emit_group_composite_gs(
                        &mut self.buf,
                        params.alpha,
                        params.blend_mode,
                        &mut self.ext_gstates,
                        &mut self.ext_gstate_map,
                    );
                }
                writeln!(self.buf, "/{} Do", form_name).unwrap();
                self.buf.extend(b"Q\n");
                self.gs = pre_q_gs;
            }
            DisplayElement::SoftMasked {
                mask,
                content,
                params,
                ..
            } => {
                // Mask → Form XObject (transparency group, /CS DeviceGray
                // so luminosity extraction works on Luminosity SMasks; the
                // CS choice is harmless for Alpha SMasks since only the
                // alpha channel is read).
                let saved_buf = std::mem::take(&mut self.buf);
                let saved_gs = std::mem::replace(&mut self.gs, GState::new());
                let saved_clip_depth = std::mem::replace(&mut self.clip_depth, 0);
                let saved_clip_gs_stack = std::mem::take(&mut self.clip_gs_stack);

                self.emit_list(mask);

                for _ in 0..self.clip_depth {
                    self.buf.extend(b"Q\n");
                }

                let mask_content = std::mem::replace(&mut self.buf, saved_buf);
                self.gs = saved_gs;
                self.clip_depth = saved_clip_depth;
                self.clip_gs_stack = saved_clip_gs_stack;

                let mask_form_idx = self.form_xobjects.len();
                let mask_group_entries: Vec<(Vec<u8>, PdfObj)> = vec![
                    (b"Type".to_vec(), PdfObj::name("Group")),
                    (b"S".to_vec(), PdfObj::name("Transparency")),
                    (b"CS".to_vec(), PdfObj::name("DeviceGray")),
                ];
                self.form_xobjects.push(FormXObject {
                    content: mask_content,
                    bbox: params.bbox,
                    group_dict_entries: Some(mask_group_entries),
                });

                // Placeholder ExtGState — pdf_device.rs patches in the
                // real /SMask entry once the mask form's indirect ref
                // exists.
                let ext_gstate_idx = self.ext_gstates.len();
                self.ext_gstates.push(ExtGStateDict {
                    entries: vec![(b"Type".to_vec(), PdfObj::name("ExtGState"))],
                });
                self.soft_mask_refs.push(SoftMaskRef {
                    ext_gstate_idx,
                    mask_form_idx,
                    subtype: params.subtype.clone(),
                    backdrop_color: params.backdrop_color,
                    transfer_invert: params.transfer_invert,
                });

                // Scope: q + /GSn gs (push SMask) + content + Q (pops the
                // SMask along with the rest of the gstate). After the
                // outer Q, the gstate tracker has to return to whatever
                // PDF state existed before the q — snapshot it.
                let pre_q_gs = self.gs.clone();
                self.buf.extend(b"q\n");
                writeln!(self.buf, "/GS{} gs", ext_gstate_idx).unwrap();
                self.gs = GState::new();
                let saved_clip_depth = std::mem::replace(&mut self.clip_depth, 0);
                let saved_clip_gs_stack = std::mem::take(&mut self.clip_gs_stack);

                self.emit_list(content);

                for _ in 0..self.clip_depth {
                    self.buf.extend(b"Q\n");
                }

                self.clip_depth = saved_clip_depth;
                self.clip_gs_stack = saved_clip_gs_stack;
                self.buf.extend(b"Q\n");
                self.gs = pre_q_gs;
            }
            DisplayElement::OcgGroup {
                elements,
                visibility,
            } => {
                // Optional-content marker. The visibility predicate is
                // resolved into an /OCG or /OCMD indirect object by
                // pdf_device.rs; here we just allocate the resource
                // name, emit the BDC/EMC bracket inline, and recurse
                // into the children. Skipping the marker for an empty
                // child list would still pollute /OCProperties, so we
                // record the OcgMarkerRef even when `elements` is empty.
                let resource_name = format!("P{}", self.ocg_marker_refs.len());
                self.ocg_marker_refs.push(OcgMarkerRef {
                    resource_name: resource_name.clone(),
                    visibility: visibility.clone(),
                });
                writeln!(self.buf, "/OC /{} BDC", resource_name).unwrap();
                self.emit_list(elements);
                self.buf.extend(b"EMC\n");
            }
            _ => {}
        }
    }

    fn finish(self) -> ContentStreamResult {
        ContentStreamResult {
            content: self.buf,
            images: self.images,
            shading_refs: self.shading_refs,
            used_font_names: self.page_font_names.into_iter().collect(),
            ext_gstate_dicts: self.ext_gstates,
            color_spaces: self.color_spaces,
            icc_color_spaces: self.icc_color_spaces,
            pattern_refs: self.pattern_refs,
            pattern_cs_entries: self.pattern_cs_names,
            transfer_refs: self.transfer_refs,
            halftone_refs: self.halftone_refs,
            bg_ucr_refs: self.bg_ucr_refs,
            soft_mask_refs: self.soft_mask_refs,
            ocg_marker_refs: self.ocg_marker_refs,
            form_xobjects: self.form_xobjects,
        }
    }
}

/// PDF blend-mode name for `GroupParams::blend_mode` u8 codes. These
/// match the encoding used by `stet-graphics`'s `BlendMode`.
fn blend_mode_name(code: u8) -> &'static [u8] {
    match code {
        0 => b"Normal",
        1 => b"Multiply",
        2 => b"Screen",
        3 => b"Overlay",
        4 => b"Darken",
        5 => b"Lighten",
        6 => b"ColorDodge",
        7 => b"ColorBurn",
        8 => b"HardLight",
        9 => b"SoftLight",
        10 => b"Difference",
        11 => b"Exclusion",
        12 => b"Hue",
        13 => b"Saturation",
        14 => b"Color",
        15 => b"Luminosity",
        _ => b"Normal",
    }
}

/// Emit a `/GSn gs` setting `/ca` (non-stroking alpha) or `/CA`
/// (stroking alpha), and `/BM` when the blend mode changes. Used by
/// the Fill and Stroke arms so per-paint transparency on the
/// DisplayList round-trips into the output PDF. Deduplicates so
/// identical (paint-side, alpha, blend) combos share one ExtGState.
fn emit_paint_alpha_blend(
    buf: &mut Vec<u8>,
    is_stroke: bool,
    alpha: f64,
    blend_mode: u8,
    gs: &mut GState,
    ext_gstates: &mut Vec<ExtGStateDict>,
    ext_gstate_map: &mut HashMap<Vec<u8>, usize>,
) {
    let cached_alpha = if is_stroke {
        gs.stroke_alpha
    } else {
        gs.fill_alpha
    };
    if (cached_alpha - alpha).abs() < 1e-6 && gs.blend_mode == blend_mode {
        return;
    }
    if is_stroke {
        gs.stroke_alpha = alpha;
    } else {
        gs.fill_alpha = alpha;
    }
    gs.blend_mode = blend_mode;

    let alpha_q = (alpha.clamp(0.0, 1.0) * 10000.0) as u16;
    let kind = if is_stroke { b'S' } else { b'F' };
    let key = format!("PA-{}-a{}-b{}", kind as char, alpha_q, blend_mode).into_bytes();

    let idx = if let Some(&idx) = ext_gstate_map.get(&key) {
        idx
    } else {
        let idx = ext_gstates.len();
        let mut entries: Vec<(Vec<u8>, PdfObj)> =
            vec![(b"Type".to_vec(), PdfObj::name("ExtGState"))];
        if is_stroke {
            entries.push((b"CA".to_vec(), PdfObj::Real(alpha)));
        } else {
            entries.push((b"ca".to_vec(), PdfObj::Real(alpha)));
        }
        if blend_mode != 0 {
            entries.push((
                b"BM".to_vec(),
                PdfObj::Name(blend_mode_name(blend_mode).to_vec()),
            ));
        } else {
            // Normal explicitly so re-pushing the same dict doesn't
            // inherit a stale BM from a previous gstate.
            entries.push((b"BM".to_vec(), PdfObj::name("Normal")));
        }
        ext_gstates.push(ExtGStateDict { entries });
        ext_gstate_map.insert(key, idx);
        idx
    };
    writeln!(buf, "/GS{} gs", idx).unwrap();
}

/// Emit a `/GSn gs` setting `/CA`, `/ca`, and `/BM` for a transparency
/// group's composite. Used before a `/Xn Do` referencing a Form XObject
/// when alpha != 1.0 or the blend mode is non-Normal. Deduplicates so
/// identical group composites share one ExtGState resource.
fn emit_group_composite_gs(
    buf: &mut Vec<u8>,
    alpha: f64,
    blend_mode: u8,
    ext_gstates: &mut Vec<ExtGStateDict>,
    ext_gstate_map: &mut HashMap<Vec<u8>, usize>,
) {
    let alpha_q = (alpha.clamp(0.0, 1.0) * 10000.0) as u16;
    let key = format!("GRP-a{}-b{}", alpha_q, blend_mode).into_bytes();

    let idx = if let Some(&idx) = ext_gstate_map.get(&key) {
        idx
    } else {
        let idx = ext_gstates.len();
        let mut entries: Vec<(Vec<u8>, PdfObj)> =
            vec![(b"Type".to_vec(), PdfObj::name("ExtGState"))];
        if alpha < 1.0 {
            entries.push((b"CA".to_vec(), PdfObj::Real(alpha)));
            entries.push((b"ca".to_vec(), PdfObj::Real(alpha)));
        }
        if blend_mode != 0 {
            entries.push((
                b"BM".to_vec(),
                PdfObj::Name(blend_mode_name(blend_mode).to_vec()),
            ));
        }
        ext_gstates.push(ExtGStateDict { entries });
        ext_gstate_map.insert(key, idx);
        idx
    };
    writeln!(buf, "/GS{} gs", idx).unwrap();
}

/// Pre-pass: register fonts referenced by Text elements and detect
/// whether the list has any Text at all. The page-side path emits paired
/// `DisplayElement::Text` + glyph-path `Fill`; the PDF reader path emits
/// only the glyph-path Fill. When the list has no Text, glyph fills fall
/// through to be emitted as filled paths instead of being skipped.
fn scan_text_elements(
    list: &DisplayList,
    font_tracker: &mut FontTracker,
    page_font_names: &mut HashSet<String>,
) -> bool {
    let mut has_text = false;
    for element in list.elements() {
        if let DisplayElement::Text { params } = element {
            has_text = true;
            let name = font_tracker.track(params).to_string();
            page_font_names.insert(name);
        }
    }
    has_text
}

/// Generate PDF content stream bytes from a display list.
///
/// Uses a shared document-level `FontTracker` to register fonts across pages.
/// When `ctx` is available, pre-computes font widths for TJ kern values
/// and batches consecutive same-font text elements into single BT/ET blocks.
pub fn build_content_stream(
    list: &DisplayList,
    page_w: u32,
    page_h: u32,
    dpi: f64,
    ctx: Option<&Context>,
    font_tracker: &mut FontTracker,
    emit_page_box_clip: bool,
) -> ContentStreamResult {
    let scale = 72.0 / dpi;
    let page_h_pts = page_h as f64 * scale;

    let mut page_font_names: HashSet<String> = HashSet::new();
    let has_text_elements = scan_text_elements(list, font_tracker, &mut page_font_names);

    // Pre-compute glyph widths for TJ kern values when Context is available
    if let Some(c) = ctx {
        for usage in font_tracker.fonts_mut() {
            if usage.widths.is_empty() {
                usage.widths = font_embedder::extract_widths(usage, c);
            }
        }
    }

    let mut builder = Builder::new(font_tracker, page_w, page_h, has_text_elements, false);
    builder.page_font_names = page_font_names;

    // Initial CTM: device space (Y-down, pixels) → PDF space (Y-up, points)
    fmt_num(&mut builder.buf, scale);
    builder.buf.extend(b" 0 0 ");
    fmt_num(&mut builder.buf, -scale);
    builder.buf.extend(b" 0 ");
    fmt_num(&mut builder.buf, page_h_pts);
    builder.buf.extend(b" cm\n");

    // Clip to page bounds (device coordinates). The rasterizer implicitly
    // clips to the pixmap, but PDF has no implicit page clip. Suppressed in
    // PDF→PDF round-trip — the source already constrained content to the page
    // and the implicit clip would re-parse as a spurious top-level `Clip`
    // element, perturbing the DisplayList and the renderer's overprint /
    // transparency-group decisions downstream.
    if emit_page_box_clip {
        builder.buf.extend(b"0 0 ");
        fmt_num(&mut builder.buf, page_w as f64);
        builder.buf.push(b' ');
        fmt_num(&mut builder.buf, page_h as f64);
        builder.buf.extend(b" re W n\n");
    }

    builder.emit_list(list);

    // Close remaining clips left open at the end of the list.
    for _ in 0..builder.clip_depth {
        builder.buf.extend(b"Q\n");
    }

    // Transform pattern matrices from device pixel space → PDF initial
    // coordinate space. The content stream's initial `cm` maps device
    // pixels → PDF points. The PDF spec says Pattern /Matrix maps pattern
    // space → the initial (pre-cm) coordinate system. So: pdf_matrix =
    // pattern_matrix × initial_cm (row-vector convention).
    let initial_cm = Matrix::new(scale, 0.0, 0.0, -scale, 0.0, page_h_pts);
    for pat_ref in &mut builder.pattern_refs {
        pat_ref.pattern_matrix = initial_cm.concat(&pat_ref.pattern_matrix);
    }

    builder.finish()
}

/// Generate PDF content stream bytes from a tile display list (for Pattern XObjects).
///
/// Unlike `build_content_stream`, this emits no initial CTM or page clip —
/// tile coordinates are already in pattern space.
pub fn build_tile_content_stream(
    list: &DisplayList,
    font_tracker: &mut FontTracker,
) -> ContentStreamResult {
    let mut page_font_names: HashSet<String> = HashSet::new();
    let has_text_elements = scan_text_elements(list, font_tracker, &mut page_font_names);

    let mut builder = Builder::new(font_tracker, 0, 0, has_text_elements, true);
    builder.page_font_names = page_font_names;

    builder.emit_list(list);

    for _ in 0..builder.clip_depth {
        builder.buf.extend(b"Q\n");
    }

    builder.finish()
}

/// Flush accumulated text batch as optimized BT/ET blocks.
fn flush_text_batch(
    batch: &[&TextParams],
    font_tracker: &FontTracker,
    buf: &mut Vec<u8>,
    gs: &mut GState,
) {
    if batch.is_empty() {
        return;
    }
    text_ops::emit_text_batch(buf, batch, font_tracker);
    // Text blocks emit color operators (g/rg/k) that change the PDF's current
    // color space. Reset all color tracking to force re-emission.
    gs.fill_color = None;
    gs.fill_cs_name = None;
    gs.stroke_color = None;
    gs.stroke_cs_name = None;
}

/// Emit a non-stroking (fill) color command.
fn emit_fill_color(buf: &mut Vec<u8>, color: &DeviceColor, painted_channels: u8, gs: &mut GState) {
    let pc = color_to_pdf_with_channels(color, painted_channels);
    if gs.fill_color.as_ref() == Some(&pc) {
        return;
    }
    match &pc {
        PdfColor::Cmyk(c, m, y, k) => {
            fmt_num(buf, *c as f64 / 10000.0);
            buf.push(b' ');
            fmt_num(buf, *m as f64 / 10000.0);
            buf.push(b' ');
            fmt_num(buf, *y as f64 / 10000.0);
            buf.push(b' ');
            fmt_num(buf, *k as f64 / 10000.0);
            buf.extend(b" k\n");
        }
        PdfColor::Gray(g) => {
            fmt_num(buf, *g as f64 / 10000.0);
            buf.extend(b" g\n");
        }
        PdfColor::Rgb(r, g, b) => {
            fmt_num(buf, *r as f64 / 10000.0);
            buf.push(b' ');
            fmt_num(buf, *g as f64 / 10000.0);
            buf.push(b' ');
            fmt_num(buf, *b as f64 / 10000.0);
            buf.extend(b" rg\n");
        }
    }
    gs.fill_color = Some(pc);
}

/// Emit a stroking color command.
fn emit_stroke_color(
    buf: &mut Vec<u8>,
    color: &DeviceColor,
    painted_channels: u8,
    gs: &mut GState,
) {
    let pc = color_to_pdf_with_channels(color, painted_channels);
    if gs.stroke_color.as_ref() == Some(&pc) {
        return;
    }
    match &pc {
        PdfColor::Cmyk(c, m, y, k) => {
            fmt_num(buf, *c as f64 / 10000.0);
            buf.push(b' ');
            fmt_num(buf, *m as f64 / 10000.0);
            buf.push(b' ');
            fmt_num(buf, *y as f64 / 10000.0);
            buf.push(b' ');
            fmt_num(buf, *k as f64 / 10000.0);
            buf.extend(b" K\n");
        }
        PdfColor::Gray(g) => {
            fmt_num(buf, *g as f64 / 10000.0);
            buf.extend(b" G\n");
        }
        PdfColor::Rgb(r, g, b) => {
            fmt_num(buf, *r as f64 / 10000.0);
            buf.push(b' ');
            fmt_num(buf, *g as f64 / 10000.0);
            buf.push(b' ');
            fmt_num(buf, *b as f64 / 10000.0);
            buf.extend(b" RG\n");
        }
    }
    gs.stroke_color = Some(pc);
}

/// Compute a dedup key for a SpotColorSpace.
fn spot_cs_key(spot: &SpotColor) -> Vec<u8> {
    match &spot.color_space {
        SpotColorSpace::Separation { name, .. } => {
            let mut key = b"Sep:".to_vec();
            key.extend(name);
            key
        }
        SpotColorSpace::DeviceN { names, .. } => {
            let mut key = b"DN:".to_vec();
            let mut sorted: Vec<&Vec<u8>> = names.iter().collect();
            sorted.sort();
            for (i, n) in sorted.iter().enumerate() {
                if i > 0 {
                    key.push(b',');
                }
                key.extend(*n);
            }
            key
        }
        _ => b"unknown".to_vec(),
    }
}

/// Get or create a color space resource name for a spot color.
fn get_or_create_cs_name(
    spot: &SpotColor,
    cs_map: &mut HashMap<Vec<u8>, String>,
    color_spaces: &mut Vec<(String, SpotColorSpace)>,
) -> String {
    let key = spot_cs_key(spot);
    if let Some(name) = cs_map.get(&key) {
        return name.clone();
    }
    let name = format!("CS{}", color_spaces.len());
    cs_map.insert(key, name.clone());
    color_spaces.push((name.clone(), spot.color_space.clone()));
    name
}

/// Emit a non-stroking Separation/DeviceN color: `/CSn cs` + `tint scn`.
fn emit_fill_color_spot(
    buf: &mut Vec<u8>,
    spot: &SpotColor,
    gs: &mut GState,
    cs_map: &mut HashMap<Vec<u8>, String>,
    color_spaces: &mut Vec<(String, SpotColorSpace)>,
) {
    let cs_name = get_or_create_cs_name(spot, cs_map, color_spaces);
    if gs.fill_cs_name.as_deref() != Some(&cs_name) {
        writeln!(buf, "/{} cs", cs_name).unwrap();
        gs.fill_cs_name = Some(cs_name);
        gs.fill_color = None; // force re-emit tint values
    }
    for v in &spot.tint_values {
        fmt_num(buf, *v);
        buf.push(b' ');
    }
    buf.extend(b"scn\n");
}

/// Emit a stroking Separation/DeviceN color: `/CSn CS` + `tint SCN`.
fn emit_stroke_color_spot(
    buf: &mut Vec<u8>,
    spot: &SpotColor,
    gs: &mut GState,
    cs_map: &mut HashMap<Vec<u8>, String>,
    color_spaces: &mut Vec<(String, SpotColorSpace)>,
) {
    let cs_name = get_or_create_cs_name(spot, cs_map, color_spaces);
    if gs.stroke_cs_name.as_deref() != Some(&cs_name) {
        writeln!(buf, "/{} CS", cs_name).unwrap();
        gs.stroke_cs_name = Some(cs_name);
        gs.stroke_color = None;
    }
    for v in &spot.tint_values {
        fmt_num(buf, *v);
        buf.push(b' ');
    }
    buf.extend(b"SCN\n");
}

/// Get or create a color space resource name for an ICCBased color,
/// deduplicating by profile hash so identical profiles share one
/// `/ICCBased` stream in the output.
fn get_or_create_icc_cs_name(
    icc: &stet_graphics::device::IccColor,
    cs_map: &mut HashMap<Vec<u8>, String>,
    icc_color_spaces: &mut Vec<(String, stet_graphics::device::IccColorSpace)>,
) -> String {
    let key = icc.color_space.profile_hash.to_vec();
    if let Some(name) = cs_map.get(&key) {
        return name.clone();
    }
    let name = format!("ICC{}", icc_color_spaces.len());
    cs_map.insert(key, name.clone());
    icc_color_spaces.push((name.clone(), icc.color_space.clone()));
    name
}

/// Emit a non-stroking ICCBased color: `/ICCn cs` + `c1 c2 c3 scn`.
fn emit_fill_color_icc(
    buf: &mut Vec<u8>,
    icc: &stet_graphics::device::IccColor,
    gs: &mut GState,
    icc_cs_map: &mut HashMap<Vec<u8>, String>,
    icc_color_spaces: &mut Vec<(String, stet_graphics::device::IccColorSpace)>,
) {
    let cs_name = get_or_create_icc_cs_name(icc, icc_cs_map, icc_color_spaces);
    if gs.fill_cs_name.as_deref() != Some(&cs_name) {
        writeln!(buf, "/{} cs", cs_name).unwrap();
        gs.fill_cs_name = Some(cs_name);
        gs.fill_color = None; // force re-emit component values
    }
    for v in &icc.components {
        fmt_num(buf, *v);
        buf.push(b' ');
    }
    buf.extend(b"scn\n");
}

/// Emit a stroking ICCBased color: `/ICCn CS` + `c1 c2 c3 SCN`.
fn emit_stroke_color_icc(
    buf: &mut Vec<u8>,
    icc: &stet_graphics::device::IccColor,
    gs: &mut GState,
    icc_cs_map: &mut HashMap<Vec<u8>, String>,
    icc_color_spaces: &mut Vec<(String, stet_graphics::device::IccColorSpace)>,
) {
    let cs_name = get_or_create_icc_cs_name(icc, icc_cs_map, icc_color_spaces);
    if gs.stroke_cs_name.as_deref() != Some(&cs_name) {
        writeln!(buf, "/{} CS", cs_name).unwrap();
        gs.stroke_cs_name = Some(cs_name);
        gs.stroke_color = None;
    }
    for v in &icc.components {
        fmt_num(buf, *v);
        buf.push(b' ');
    }
    buf.extend(b"SCN\n");
}

/// Emit line state commands (width, cap, join, miter limit, dash).
fn emit_line_state(buf: &mut Vec<u8>, params: &StrokeParams, gs: &mut GState) {
    if gs.line_width != params.line_width {
        fmt_num(buf, params.line_width);
        buf.extend(b" w\n");
        gs.line_width = params.line_width;
    }

    let lc = match params.line_cap {
        LineCap::Butt => 0,
        LineCap::Round => 1,
        LineCap::Square => 2,
        _ => 0,
    };
    if gs.line_cap != lc {
        writeln!(buf, "{} J", lc).unwrap();
        gs.line_cap = lc;
    }

    let lj = match params.line_join {
        LineJoin::Miter => 0,
        LineJoin::Round => 1,
        LineJoin::Bevel => 2,
        _ => 0,
    };
    if gs.line_join != lj {
        writeln!(buf, "{} j", lj).unwrap();
        gs.line_join = lj;
    }

    if gs.miter_limit != params.miter_limit {
        fmt_num(buf, params.miter_limit);
        buf.extend(b" M\n");
        gs.miter_limit = params.miter_limit;
    }

    let dash = &params.dash_pattern;
    if gs.dash_array != dash.array || gs.dash_offset != dash.offset {
        buf.push(b'[');
        for (i, &d) in dash.array.iter().enumerate() {
            if i > 0 {
                buf.push(b' ');
            }
            fmt_num(buf, d);
        }
        buf.extend(b"] ");
        fmt_num(buf, dash.offset);
        buf.extend(b" d\n");
        gs.dash_array.clone_from(&dash.array);
        gs.dash_offset = dash.offset;
    }
}

/// Emit a `gs` operator to set overprint mode when it changes.
///
/// Deduplicates ExtGState dicts — identical overprint settings share one resource.
fn emit_overprint(
    buf: &mut Vec<u8>,
    overprint: bool,
    overprint_mode: i32,
    gs: &mut GState,
    ext_gstates: &mut Vec<ExtGStateDict>,
    ext_gstate_map: &mut HashMap<Vec<u8>, usize>,
) {
    // OPM only affects rendering when overprint is on, but we still
    // round-trip the requested mode so a subsequent overprint=true
    // emission picks up the right value. When overprint is off, the
    // mode entry on the gstate is irrelevant for the next paint.
    let effective_mode = if overprint {
        overprint_mode
    } else {
        gs.overprint_mode
    };
    if gs.overprint == Some(overprint) && gs.overprint_mode == effective_mode {
        return;
    }
    gs.overprint = Some(overprint);
    gs.overprint_mode = effective_mode;

    let key = format!("OP{}-M{}", overprint as u8, effective_mode).into_bytes();

    let idx = if let Some(&idx) = ext_gstate_map.get(&key) {
        idx
    } else {
        let idx = ext_gstates.len();
        let mut entries = vec![
            (b"Type".to_vec(), PdfObj::name("ExtGState")),
            (b"OP".to_vec(), PdfObj::Bool(overprint)),
            (b"op".to_vec(), PdfObj::Bool(overprint)),
        ];
        if overprint {
            entries.push((b"OPM".to_vec(), PdfObj::Int(overprint_mode.into())));
        }
        ext_gstates.push(ExtGStateDict { entries });
        ext_gstate_map.insert(key, idx);
        idx
    };

    writeln!(buf, "/GS{} gs", idx).unwrap();
}

/// Emit rendering intent operator if it changed.
fn emit_rendering_intent(buf: &mut Vec<u8>, intent: u8, gs: &mut GState) {
    if gs.rendering_intent == intent {
        return;
    }
    gs.rendering_intent = intent;
    let name = match intent {
        0 => b"RelativeColorimetric" as &[u8],
        1 => b"AbsoluteColorimetric",
        2 => b"Perceptual",
        3 => b"Saturation",
        _ => return,
    };
    buf.push(b'/');
    buf.extend_from_slice(name);
    buf.extend(b" ri\n");
}

/// Build a dedup key from a TransferState based on Arc pointer identity.
fn build_transfer_key(transfer: &TransferState) -> Vec<u8> {
    use std::sync::Arc;
    let mut key = Vec::new();
    if let Some(ref color) = transfer.color {
        key.extend(b"C");
        for table in color {
            if let Some(t) = table {
                let ptr = Arc::as_ptr(t) as usize;
                key.extend(ptr.to_le_bytes());
            } else {
                key.extend(b"I"); // identity
            }
        }
    } else if let Some(ref gray) = transfer.gray {
        key.extend(b"G");
        let ptr = Arc::as_ptr(gray) as usize;
        key.extend(ptr.to_le_bytes());
    }
    // Empty key = identity (no transfer)
    key
}

/// Emit a `gs` operator to set transfer function when it changes.
fn emit_transfer(
    buf: &mut Vec<u8>,
    transfer: &TransferState,
    gs: &mut GState,
    ext_gstates: &mut Vec<ExtGStateDict>,
    ext_gstate_map: &mut HashMap<Vec<u8>, usize>,
    transfer_refs: &mut Vec<TransferFunctionRef>,
) {
    let key = build_transfer_key(transfer);
    if key == gs.transfer_key {
        return;
    }
    gs.transfer_key = key.clone();

    // Identity transfer — no ExtGState needed
    if key.is_empty() {
        return;
    }

    if let Some(&idx) = ext_gstate_map.get(&key) {
        writeln!(buf, "/GS{} gs", idx).unwrap();
        return;
    }

    let idx = ext_gstates.len();
    // Placeholder entries — actual /TR2 value set by pdf_device when building function objects
    let entries = vec![(b"Type".to_vec(), PdfObj::name("ExtGState"))];
    ext_gstates.push(ExtGStateDict { entries });
    ext_gstate_map.insert(key, idx);

    // Collect the actual sample data
    let (tables, is_color) = if let Some(ref color) = transfer.color {
        (color.to_vec(), true)
    } else if let Some(ref gray) = transfer.gray {
        (vec![Some(gray.clone())], false)
    } else {
        (vec![], false)
    };

    transfer_refs.push(TransferFunctionRef {
        ext_gstate_idx: idx,
        tables,
        is_color,
    });
    writeln!(buf, "/GS{} gs", idx).unwrap();
}

/// Build a dedup key from a HalftoneState based on Arc pointer identity.
fn build_halftone_key(halftone: &HalftoneState) -> Vec<u8> {
    use std::sync::Arc;
    let mut key = Vec::new();
    if let Some(ref color) = halftone.color {
        key.extend(b"C");
        for screen in color {
            if let Some(s) = screen {
                let ptr = Arc::as_ptr(s) as usize;
                key.extend(ptr.to_le_bytes());
            } else {
                key.extend(b"D"); // default
            }
        }
    } else if let Some(ref gray) = halftone.gray {
        key.extend(b"G");
        let ptr = Arc::as_ptr(gray) as usize;
        key.extend(ptr.to_le_bytes());
    }
    // Empty key = default (no halftone)
    key
}

/// Emit a `gs` operator to set halftone when it changes.
fn emit_halftone(
    buf: &mut Vec<u8>,
    halftone: &HalftoneState,
    gs: &mut GState,
    ext_gstates: &mut Vec<ExtGStateDict>,
    ext_gstate_map: &mut HashMap<Vec<u8>, usize>,
    halftone_refs: &mut Vec<HalftoneRef>,
) {
    let key = build_halftone_key(halftone);
    if key == gs.halftone_key {
        return;
    }
    gs.halftone_key = key.clone();

    // Default halftone — no ExtGState needed
    if key.is_empty() {
        return;
    }

    // Prefix key for dedup namespace separation from transfer keys
    let mut map_key = b"HT:".to_vec();
    map_key.extend(&key);

    if let Some(&idx) = ext_gstate_map.get(&map_key) {
        writeln!(buf, "/GS{} gs", idx).unwrap();
        return;
    }

    let idx = ext_gstates.len();
    let entries = vec![(b"Type".to_vec(), PdfObj::name("ExtGState"))];
    ext_gstates.push(ExtGStateDict { entries });
    ext_gstate_map.insert(map_key, idx);

    halftone_refs.push(HalftoneRef {
        ext_gstate_idx: idx,
        state: halftone.clone(),
    });
    writeln!(buf, "/GS{} gs", idx).unwrap();
}

/// Build a dedup key from a BgUcrState based on Arc pointer identity.
fn build_bg_ucr_key(state: &BgUcrState) -> Vec<u8> {
    use std::sync::Arc;
    let mut key = Vec::new();
    if let Some(ref bg) = state.bg {
        key.extend(b"B");
        let ptr = Arc::as_ptr(bg) as usize;
        key.extend(ptr.to_le_bytes());
    }
    if let Some(ref ucr) = state.ucr {
        key.extend(b"U");
        let ptr = Arc::as_ptr(ucr) as usize;
        key.extend(ptr.to_le_bytes());
    }
    key
}

/// Emit a `gs` operator to set BG/UCR when it changes.
fn emit_bg_ucr(
    buf: &mut Vec<u8>,
    state: &BgUcrState,
    gs: &mut GState,
    ext_gstates: &mut Vec<ExtGStateDict>,
    ext_gstate_map: &mut HashMap<Vec<u8>, usize>,
    bg_ucr_refs: &mut Vec<BgUcrRef>,
) {
    let key = build_bg_ucr_key(state);
    if key == gs.bg_ucr_key {
        return;
    }
    gs.bg_ucr_key = key.clone();

    if key.is_empty() {
        return;
    }

    let mut map_key = b"BU:".to_vec();
    map_key.extend(&key);

    if let Some(&idx) = ext_gstate_map.get(&map_key) {
        writeln!(buf, "/GS{} gs", idx).unwrap();
        return;
    }

    let idx = ext_gstates.len();
    let entries = vec![(b"Type".to_vec(), PdfObj::name("ExtGState"))];
    ext_gstates.push(ExtGStateDict { entries });
    ext_gstate_map.insert(map_key, idx);

    bg_ucr_refs.push(BgUcrRef {
        ext_gstate_idx: idx,
        state: state.clone(),
    });
    writeln!(buf, "/GS{} gs", idx).unwrap();
}

/// Coordinate-wise equality for two paths. Used by the Clip arm to
/// detect "replay" Clip elements the reader emits after each
/// `restore_clip_from_stack`. Path segment counts and corresponding
/// segment shapes/coords must match.
fn paths_equal(a: &PsPath, b: &PsPath) -> bool {
    use stet_fonts::geometry::PathSegment;
    if a.segments.len() != b.segments.len() {
        return false;
    }
    for (sa, sb) in a.segments.iter().zip(b.segments.iter()) {
        let eq = match (sa, sb) {
            (PathSegment::MoveTo(x1, y1), PathSegment::MoveTo(x2, y2))
            | (PathSegment::LineTo(x1, y1), PathSegment::LineTo(x2, y2)) => {
                (x1 - x2).abs() < 1e-6 && (y1 - y2).abs() < 1e-6
            }
            (
                PathSegment::CurveTo {
                    x1: a1,
                    y1: b1,
                    x2: c1,
                    y2: d1,
                    x3: e1,
                    y3: f1,
                },
                PathSegment::CurveTo {
                    x1: a2,
                    y1: b2,
                    x2: c2,
                    y2: d2,
                    x3: e2,
                    y3: f2,
                },
            ) => {
                (a1 - a2).abs() < 1e-6
                    && (b1 - b2).abs() < 1e-6
                    && (c1 - c2).abs() < 1e-6
                    && (d1 - d2).abs() < 1e-6
                    && (e1 - e2).abs() < 1e-6
                    && (f1 - f2).abs() < 1e-6
            }
            (PathSegment::ClosePath, PathSegment::ClosePath) => true,
            _ => false,
        };
        if !eq {
            return false;
        }
    }
    true
}

/// Emit path segments as PDF path operators.
fn emit_path(buf: &mut Vec<u8>, path: &PsPath) {
    use stet_fonts::geometry::PathSegment;
    for seg in &path.segments {
        match seg {
            PathSegment::MoveTo(x, y) => {
                fmt_num(buf, *x);
                buf.push(b' ');
                fmt_num(buf, *y);
                buf.extend(b" m\n");
            }
            PathSegment::LineTo(x, y) => {
                fmt_num(buf, *x);
                buf.push(b' ');
                fmt_num(buf, *y);
                buf.extend(b" l\n");
            }
            PathSegment::CurveTo {
                x1,
                y1,
                x2,
                y2,
                x3,
                y3,
            } => {
                fmt_num(buf, *x1);
                buf.push(b' ');
                fmt_num(buf, *y1);
                buf.push(b' ');
                fmt_num(buf, *x2);
                buf.push(b' ');
                fmt_num(buf, *y2);
                buf.push(b' ');
                fmt_num(buf, *x3);
                buf.push(b' ');
                fmt_num(buf, *y3);
                buf.extend(b" c\n");
            }
            PathSegment::ClosePath => {
                buf.extend(b"h\n");
            }
        }
    }
}

/// Compute the PDF cm matrix for image placement.
///
/// Maps the unit square (0,0)-(1,0)-(0,1) to the image rectangle in device space.
/// The content stream's base CTM then maps device space to PDF space.
fn compute_image_matrix(params: &stet_graphics::device::ImageParams) -> Matrix {
    // image_matrix maps user space → image pixel space (PostScript convention)
    // Its inverse maps image pixels → user space
    // CTM maps user space → device space
    // M_scale maps unit square → image pixel grid
    let m_scale = Matrix::new(
        params.width as f64,
        0.0,
        0.0,
        params.height as f64,
        0.0,
        0.0,
    );
    let inv_im = params.image_matrix.invert().unwrap_or(Matrix::identity());

    // PDF image coordinate (0,0) is bottom-left, but data is stored top-to-bottom.
    // The content stream CTM flips Y (device→PDF), which would flip the image.
    // Compensate by flipping the v-axis of the unit square: (u,v) → (u, 1-v).
    let flip_v = Matrix::new(1.0, 0.0, 0.0, -1.0, 0.0, 1.0);

    // Row-vector composition: flip_v × M_scale × inv_im × CTM
    // Using concat: ctm.concat(&inv_im).concat(&m_scale).concat(&flip_v)
    params.ctm.concat(&inv_im).concat(&m_scale).concat(&flip_v)
}

/// Emit a 6-element matrix as PDF `a b c d e f`.
fn emit_matrix(buf: &mut Vec<u8>, m: &Matrix) {
    fmt_num(buf, m.a);
    buf.push(b' ');
    fmt_num(buf, m.b);
    buf.push(b' ');
    fmt_num(buf, m.c);
    buf.push(b' ');
    fmt_num(buf, m.d);
    buf.push(b' ');
    fmt_num(buf, m.tx);
    buf.push(b' ');
    fmt_num(buf, m.ty);
}

/// Emit a `cm` (concat matrix) operator.
fn emit_cm(buf: &mut Vec<u8>, m: &Matrix) {
    emit_matrix(buf, m);
    buf.extend(b" cm\n");
}

/// Check if a matrix is (approximately) identity.
fn is_identity(m: &Matrix) -> bool {
    (m.a - 1.0).abs() < 1e-10
        && m.b.abs() < 1e-10
        && m.c.abs() < 1e-10
        && (m.d - 1.0).abs() < 1e-10
        && m.tx.abs() < 1e-10
        && m.ty.abs() < 1e-10
}

/// Emit a tiling pattern fill: set pattern color space, select pattern, emit path + fill.
fn emit_pattern_fill(
    buf: &mut Vec<u8>,
    params: &PatternFillParams,
    gs: &mut GState,
    pattern_refs: &mut Vec<PatternRef>,
    pattern_map: &mut HashMap<u32, usize>,
    pattern_cs_names: &mut Vec<(String, PdfObj)>,
    pattern_cs_set: &mut HashSet<String>,
) {
    // Dedup by pattern_id — each makepattern call gets a unique ID,
    // so same-pattern reuses share one Pattern XObject.
    let pat_idx = if let Some(&idx) = pattern_map.get(&params.pattern_id) {
        idx
    } else {
        let idx = pattern_refs.len();
        pattern_refs.push(PatternRef {
            tile: params.tile.clone(),
            pattern_matrix: params.pattern_matrix,
            bbox: params.bbox,
            xstep: params.xstep,
            ystep: params.ystep,
            paint_type: params.paint_type,
        });
        pattern_map.insert(params.pattern_id, idx);
        idx
    };

    let pat_name = format!("P{}", pat_idx);

    if params.paint_type == 2 {
        // Uncolored pattern: need [/Pattern /DeviceXxx] color space
        let base_cs = match &params.underlying_color {
            Some(c) if c.native_cmyk.is_some() => "DeviceCMYK",
            Some(c) if c.r == c.g && c.g == c.b => "DeviceGray",
            _ => "DeviceRGB",
        };
        let cs_name = format!("CSP{}", pat_idx);
        if !pattern_cs_set.contains(&cs_name) {
            pattern_cs_names.push((
                cs_name.clone(),
                PdfObj::Array(vec![PdfObj::name("Pattern"), PdfObj::name(base_cs)]),
            ));
            pattern_cs_set.insert(cs_name.clone());
        }
        // Set color space
        if gs.fill_cs_name.as_deref() != Some(&cs_name) {
            writeln!(buf, "/{} cs", cs_name).unwrap();
            gs.fill_cs_name = Some(cs_name);
            gs.fill_color = None;
        }
        // Emit underlying color components + pattern name
        if let Some(color) = &params.underlying_color {
            if let Some((c, m, y, k)) = color.native_cmyk {
                fmt_num(buf, c);
                buf.push(b' ');
                fmt_num(buf, m);
                buf.push(b' ');
                fmt_num(buf, y);
                buf.push(b' ');
                fmt_num(buf, k);
            } else if color.r == color.g && color.g == color.b {
                fmt_num(buf, color.r);
            } else {
                fmt_num(buf, color.r);
                buf.push(b' ');
                fmt_num(buf, color.g);
                buf.push(b' ');
                fmt_num(buf, color.b);
            }
            buf.push(b' ');
        }
        writeln!(buf, "/{} scn", pat_name).unwrap();
    } else {
        // Colored pattern (PaintType 1)
        if gs.fill_cs_name.as_deref() != Some("Pattern") {
            buf.extend(b"/Pattern cs\n");
            gs.fill_cs_name = Some("Pattern".to_string());
            gs.fill_color = None;
        }
        writeln!(buf, "/{} scn", pat_name).unwrap();
    }

    emit_path(buf, &params.path);
    if params.fill_rule == FillRule::EvenOdd {
        buf.extend(b"f*\n");
    } else {
        buf.extend(b"f\n");
    }
}

/// Format a number compactly for PDF content streams.
pub(crate) fn fmt_num(buf: &mut Vec<u8>, v: f64) {
    if v == 0.0 {
        buf.push(b'0');
    } else if v == v.round() && v.abs() < 2_147_483_647.0 {
        write!(buf, "{}", v as i64).unwrap();
    } else {
        // 4 decimal places — enough precision for sub-pixel coordinates
        let s = format!("{:.4}", v);
        let s = s.trim_end_matches('0');
        let s = s.trim_end_matches('.');
        buf.extend(s.as_bytes());
    }
}

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

    #[test]
    fn test_fmt_num() {
        let mut buf = Vec::new();
        fmt_num(&mut buf, 0.0);
        assert_eq!(&buf, b"0");

        buf.clear();
        fmt_num(&mut buf, 1.0);
        assert_eq!(&buf, b"1");

        buf.clear();
        fmt_num(&mut buf, -42.0);
        assert_eq!(&buf, b"-42");

        buf.clear();
        fmt_num(&mut buf, 1.5);
        assert_eq!(&buf, b"1.5");

        buf.clear();
        fmt_num(&mut buf, 0.001);
        assert_eq!(&buf, b"0.001");
    }

    #[test]
    fn test_color_to_pdf() {
        let gray = DeviceColor::from_gray(0.5);
        assert_eq!(color_to_pdf(&gray), PdfColor::Gray(5000));

        let rgb = DeviceColor::from_rgb(1.0, 0.0, 0.5);
        assert_eq!(color_to_pdf(&rgb), PdfColor::Rgb(10000, 0, 5000));
    }
}