pdfboss-render 0.6.0

Page rasterization to RGBA pixmaps and PNG for pdfboss
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
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
//! Content-op execution against a graphics state stack: transforms, colors,
//! clipping, ExtGState, form XObject recursion, and paint dispatch.
//!
//! Limitations (v0.1): only embedded-TrueType glyph outlines are painted
//! (other fonts are positioned but not drawn); `sh` shadings are skipped;
//! pattern fills paint mid-gray; masks and blend modes are ignored;
//! annotation appearance streams are not drawn. Everything on that list
//! except the glyph tiers -- which the caller chooses -- is recorded in the
//! [`RenderReport`] this module returns, along with every content stream and
//! image leniency drops, so no caller is handed a blank page it cannot
//! account for.

use pdfboss_core::FastMap;
use std::rc::Rc;

use pdfboss_core::content::{parse_content, ImageParams, Op, TextItem};
use pdfboss_core::filters::decode_stream;
use pdfboss_core::geom::{Matrix, Point};
use pdfboss_core::{Dict, Document, Error, Name, Object, Page, Result, Stream};

use crate::color::{self, ColorSpace};
use crate::glyph::GlyphFont;
use crate::image::{self, DrawParams};
use crate::path::{PathBuilder, Subpath};
use crate::raster::{fill_path, FillRule, Mask};
use crate::stroke::stroke_path;
#[cfg(feature = "substitute-fonts")]
use crate::substitute::BuiltinProvider;
use crate::substitute::{DirProvider, SubstituteProvider};
use crate::type3::Type3Font;
use crate::{
    GlyphPainting, Pixmap, RenderOptions, RenderReport, SkipReason, SkippedKind, SubstituteSource,
};

/// Maximum `q`/`Q` nesting depth.
const MAX_GSTATE_DEPTH: usize = 64;
/// Maximum form XObject recursion depth.
const MAX_FORM_DEPTH: u32 = 16;
/// Maximum pixmap side length, guarding malformed boxes and huge scales.
const MAX_SIDE: f32 = 16384.0;
/// Bound on `Executor::clip_cache`'s size: many real documents repeat the
/// exact same clip path (often a page-bounds "reset" rect) hundreds of times
/// per page, which used to re-rasterize it from scratch every time. Capped
/// like `GlyphFont`'s `flat_cache` so a pathological stream minting endless
/// distinct clip paths can't grow this unboundedly.
const MAX_CLIP_CACHE: usize = 256;

/// Identifies a clip path by its exact flattened (device-space) geometry and
/// fill rule, so an identical clip repeated later in the same page reuses
/// its rasterized [`Mask`] instead of rebuilding it. `f32` coordinates are
/// compared by bit pattern (exact match only — this is a cache key, not a
/// geometric equivalence test, so two paths that are merely numerically
/// close still miss and just re-rasterize).
#[derive(PartialEq, Eq, Hash, Clone)]
struct ClipKey {
    even_odd: bool,
    subpaths: Vec<(bool, Vec<(u32, u32)>)>,
}

impl ClipKey {
    fn new(polys: &[Subpath], rule: FillRule) -> ClipKey {
        ClipKey {
            even_odd: rule == FillRule::EvenOdd,
            subpaths: polys
                .iter()
                .map(|s| {
                    (
                        s.closed,
                        s.points
                            .iter()
                            .map(|p| (p.x.to_bits(), p.y.to_bits()))
                            .collect(),
                    )
                })
                .collect(),
        }
    }
}

/// The graphics state carried across operators and saved/restored by
/// `q`/`Q`.
#[derive(Debug, Clone)]
struct GState {
    /// Current transformation matrix, user space to device pixels.
    ctm: Matrix,
    fill_space: ColorSpace,
    stroke_space: ColorSpace,
    /// Fill color already converted to RGB in 0..=1.
    fill_rgb: [f32; 3],
    stroke_rgb: [f32; 3],
    /// A `/Pattern` fill space is active: paint mid-gray instead.
    fill_pattern: bool,
    stroke_pattern: bool,
    /// Line width in user space.
    line_width: f32,
    /// Stored but unused: stroking approximates round caps (v0.1).
    #[allow(dead_code)]
    line_cap: i32,
    /// Stored but unused: stroking approximates round joins (v0.1).
    #[allow(dead_code)]
    line_join: i32,
    /// Stored but unused: joins are round, so the miter limit never cuts.
    #[allow(dead_code)]
    miter_limit: f32,
    /// Dash pattern lengths in user space (empty = solid).
    dash: Vec<f32>,
    dash_phase: f32,
    /// Constant fill alpha (`ca`).
    fill_alpha: f32,
    /// Constant stroke alpha (`CA`).
    stroke_alpha: f32,
    /// Active clip as a device-space coverage mask. Shared behind an `Rc` so
    /// that saving state (`q`) and entering a form clone the graphics state
    /// without copying the full-page mask buffer; a new clip always builds a
    /// fresh `Mask`, so this is effectively clone-on-write.
    clip: Option<Rc<Mask>>,
}

impl GState {
    fn new(ctm: Matrix) -> GState {
        GState {
            ctm,
            fill_space: ColorSpace::DeviceGray,
            stroke_space: ColorSpace::DeviceGray,
            fill_rgb: [0.0; 3],
            stroke_rgb: [0.0; 3],
            fill_pattern: false,
            stroke_pattern: false,
            line_width: 1.0,
            line_cap: 0,
            line_join: 0,
            miter_limit: 10.0,
            dash: Vec::new(),
            dash_phase: 0.0,
            fill_alpha: 1.0,
            stroke_alpha: 1.0,
            clip: None,
        }
    }

    /// The fill color as RGBA8 (patterns paint mid-gray, documented v0.1
    /// approximation).
    fn fill_rgba8(&self) -> [u8; 4] {
        rgba8(if self.fill_pattern {
            [0.5; 3]
        } else {
            self.fill_rgb
        })
    }

    /// The stroke color as RGBA8.
    fn stroke_rgba8(&self) -> [u8; 4] {
        rgba8(if self.stroke_pattern {
            [0.5; 3]
        } else {
            self.stroke_rgb
        })
    }
}

/// Text-showing state within a `BT`/`ET` block. Held per content stream (not
/// saved by `q`/`Q`), matching how the extractor tracks text.
struct TextState {
    /// Text matrix and line matrix.
    tm: Matrix,
    tlm: Matrix,
    font: Option<Rc<GlyphFont>>,
    /// A `/Type3` font whose glyphs paint by re-entering the executor per
    /// CharProc (ISO 32000-1 §9.6.5). Invariant: at most one of `font`
    /// (outline) / `type3` is `Some`.
    type3: Option<Rc<Type3Font>>,
    size: f32,
    char_spacing: f32,
    word_spacing: f32,
    /// Horizontal scale as a fraction (`Tz` / 100).
    horiz: f32,
    leading: f32,
    rise: f32,
}

impl Default for TextState {
    fn default() -> TextState {
        TextState {
            tm: Matrix::identity(),
            tlm: Matrix::identity(),
            font: None,
            type3: None,
            size: 0.0,
            char_spacing: 0.0,
            word_spacing: 0.0,
            horiz: 1.0,
            leading: 0.0,
            rise: 0.0,
        }
    }
}

/// Converts unit-range RGB to opaque RGBA8.
fn rgba8(rgb: [f32; 3]) -> [u8; 4] {
    let q = |v: f32| (v.clamp(0.0, 1.0) * 255.0 + 0.5) as u8;
    [q(rgb[0]), q(rgb[1]), q(rgb[2]), 255]
}

/// Approximate device scale of `m`: the square root of the absolute
/// determinant (exact for uniform scaling), used to size stroke widths and
/// dash lengths in device space.
fn ctm_scale(m: Matrix) -> f32 {
    let det = (m.a * m.d - m.b * m.c).abs();
    if det.is_finite() && det > 0.0 {
        det.sqrt()
    } else {
        1.0
    }
}

/// True when every value is finite (NaN/Inf operands skip the op).
fn all_finite(vals: &[f32]) -> bool {
    vals.iter().all(|v| v.is_finite())
}

/// True when all six matrix entries are finite.
fn finite_matrix(m: &Matrix) -> bool {
    all_finite(&[m.a, m.b, m.c, m.d, m.e, m.f])
}

/// The base transform mapping the (normalized) crop box to device pixels:
/// translate the crop origin away, apply `/Rotate` clockwise into the
/// display quadrant, then flip y and scale so the display top-left lands
/// on pixel (0, 0).
fn base_ctm(crop: pdfboss_core::Rect, rotate: i32, scale: f32) -> Matrix {
    let (cw, ch) = (crop.width(), crop.height());
    let spin = match rotate {
        90 => Matrix {
            a: 0.0,
            b: -1.0,
            c: 1.0,
            d: 0.0,
            e: 0.0,
            f: cw,
        },
        180 => Matrix {
            a: -1.0,
            b: 0.0,
            c: 0.0,
            d: -1.0,
            e: cw,
            f: ch,
        },
        270 => Matrix {
            a: 0.0,
            b: 1.0,
            c: -1.0,
            d: 0.0,
            e: ch,
            f: 0.0,
        },
        _ => Matrix::identity(),
    };
    let disp_h = if rotate == 90 || rotate == 270 {
        cw
    } else {
        ch
    };
    let flip = Matrix {
        a: scale,
        b: 0.0,
        c: 0.0,
        d: -scale,
        e: 0.0,
        f: disp_h * scale,
    };
    Matrix::translate(-crop.x0, -crop.y0)
        .concat(spin)
        .concat(flip)
}

/// Renders `page` from `doc` at `scale` onto a white background. The pixel
/// size is `ceil(crop_w * scale) x ceil(crop_h * scale)` after `/Rotate`.
/// Content errors are lenient: an unreadable stream renders blank. The
/// returned [`RenderReport`] names everything that leniency dropped or
/// approximated, so a caller can tell a blank page from an unreadable one.
pub(crate) fn render_page_reporting(
    doc: &Document,
    page: &Page,
    scale: f32,
    opts: &RenderOptions,
) -> Result<(Pixmap, RenderReport)> {
    let scale = if scale.is_finite() && scale > 0.0 {
        scale
    } else {
        1.0
    };
    let (w_pt, h_pt) = page.size();
    let pw = (w_pt * scale).ceil().clamp(1.0, MAX_SIDE) as u32;
    let ph = (h_pt * scale).ceil().clamp(1.0, MAX_SIDE) as u32;
    let mut pix = Pixmap::new(pw, ph);
    pix.fill([255, 255, 255, 255]);
    let mut report = RenderReport::default();
    // A page whose own `/Contents` will not decode or will not parse
    // rasterizes blank, which is indistinguishable from an empty page unless
    // the report says so.
    let content = match page.content(doc) {
        Ok(content) => content,
        Err(e) => {
            report.record(SkippedKind::PageContents, skip_reason_for(&e));
            Vec::new()
        }
    };
    let ops = match parse_content(&content) {
        Ok(ops) => ops,
        Err(e) => {
            report.record(SkippedKind::PageContents, skip_reason_for(&e));
            Vec::new()
        }
    };
    record_annotations(doc, page, &mut report);
    let ctm = base_ctm(page.crop_box.normalize(), page.rotate, scale);
    let provider: Option<Box<dyn SubstituteProvider>> = match &opts.substitutes {
        SubstituteSource::Dir(dir) => Some(Box::new(DirProvider { dir: dir.clone() })),
        #[cfg(feature = "substitute-fonts")]
        SubstituteSource::Builtin => Some(Box::new(BuiltinProvider)),
        // Without the `substitute-fonts` feature there are no compiled-in
        // faces, so `Builtin` falls back to no provider (`Full` degrades to
        // `AllEmbedded` for non-embedded fonts). `None` never substitutes.
        #[cfg(not(feature = "substitute-fonts"))]
        SubstituteSource::Builtin => None,
        SubstituteSource::None => None,
    };
    let mut exec = Executor {
        doc,
        pix,
        painting: opts.glyph_painting,
        color_locked: false,
        provider,
        glyph_blit: Vec::new(),
        clip_cache: FastMap::default(),
        report,
    };
    exec.run(&ops, &[&page.resources], GState::new(ctm), 0);
    Ok((exec.pix, exec.report))
}

/// Records every annotation this renderer leaves unpainted. Annotation
/// appearance streams (ISO 32000-1 §12.5.5) are not drawn at all, so a page
/// whose visible content is a stamp or a filled form field rasterizes blank
/// and would otherwise have nothing to say for itself. Annotations with no
/// `/AP` have no appearance to paint, and ones flagged Hidden (bit 2) or
/// NoView (bit 6) are invisible on screen anyway (§12.5.3), so neither
/// counts as a drop.
fn record_annotations(doc: &Document, page: &Page, report: &mut RenderReport) {
    /// `/F` bits whose annotations are not displayed even by a renderer
    /// that paints appearance streams.
    const INVISIBLE: i64 = (1 << 1) | (1 << 5);
    let Some(annots) = page.dict().get("Annots") else {
        return;
    };
    let Ok(Object::Array(items)) = doc.resolve(annots) else {
        return;
    };
    for item in &items {
        let Ok(resolved) = doc.resolve(item) else {
            continue;
        };
        let Some(dict) = resolved.as_dict() else {
            continue;
        };
        if dict.get("AP").is_none() || dict.get_int("F").unwrap_or(0) & INVISIBLE != 0 {
            continue;
        }
        report.record(SkippedKind::Annotation, SkipReason::Unsupported);
    }
}

/// Executes parsed content operators against a shared pixmap; forms
/// recurse through [`Executor::run`] with their own resource chain.
struct Executor<'a> {
    doc: &'a Document,
    pix: Pixmap,
    painting: GlyphPainting,
    /// Set while painting a `d1` (uncolored) Type3 CharProc: ISO 32000-1
    /// §9.6.5.2 says such a glyph "shall not specify any color", so
    /// `run_color_or_misc` turns every fill/stroke color-setting op into a
    /// no-op and the glyph keeps the color inherited from the text state.
    color_locked: bool,
    /// The `Full`-tier substitute source built from
    /// [`RenderOptions::substitutes`], if any. Passed through to
    /// [`GlyphFont::load`], which consults it to substitute a non-embedded
    /// SIMPLE font (`/TrueType`, `/Type1`, `/MMType1`) at the `Full` tier;
    /// `/Type0` and `/Type3` fonts never consult it (see `glyph.rs`'s module
    /// doc).
    provider: Option<Box<dyn SubstituteProvider>>,
    /// Reused scratch for painting a cached glyph outline: the flattened
    /// (origin-relative) subpaths from [`GlyphFont::flattened`] are copied
    /// here translated to the glyph's device origin, so a whole page of text
    /// paints its glyphs without allocating a fresh polygon set per glyph.
    glyph_blit: Vec<Subpath>,
    /// Rasterized clip masks by exact path geometry, shared across the whole
    /// page render (including nested forms — a repeated clip means the same
    /// device-space geometry regardless of which resource scope drew it).
    /// See [`MAX_CLIP_CACHE`].
    clip_cache: FastMap<ClipKey, Rc<Mask>>,
    /// Content this render dropped rather than painted, accumulated across
    /// the page (forms and Type3 CharProcs included, since they run through
    /// the same [`Executor`]).
    report: RenderReport,
}

impl Executor<'_> {
    /// Runs `ops` with resource lookups walking `chain` (innermost first).
    /// `depth` counts form recursion. All failures are lenient skips.
    fn run(&mut self, ops: &[Op], chain: &[&Dict], base: GState, depth: u32) {
        let mut gs = base;
        let mut stack: Vec<GState> = Vec::new();
        let mut path: Option<PathBuilder> = None;
        let mut pending_clip: Option<FillRule> = None;
        let mut ts = TextState::default();
        let mut fonts: FastMap<String, Option<Rc<GlyphFont>>> = FastMap::default();
        for op in ops {
            match op {
                Op::Save => {
                    if stack.len() < MAX_GSTATE_DEPTH {
                        stack.push(gs.clone());
                    }
                }
                Op::Restore => {
                    if let Some(prev) = stack.pop() {
                        gs = prev;
                    }
                }
                Op::Concat(m) => {
                    if finite_matrix(m) {
                        gs.ctm = m.concat(gs.ctm);
                    }
                }
                Op::SetLineWidth(w) => {
                    if w.is_finite() && *w >= 0.0 {
                        gs.line_width = *w;
                    }
                }
                Op::SetLineCap(c) => gs.line_cap = *c,
                Op::SetLineJoin(j) => gs.line_join = *j,
                Op::SetMiterLimit(m) => {
                    if m.is_finite() {
                        gs.miter_limit = *m;
                    }
                }
                Op::SetDash(d, phase) => {
                    if all_finite(d) && phase.is_finite() {
                        gs.dash = d.clone();
                        gs.dash_phase = *phase;
                    }
                }
                Op::SetExtGState(name) => self.apply_ext_gstate(name, chain, &mut gs),
                Op::SetRenderingIntent(_) | Op::SetFlatness(_) => {}

                // Path construction (user space; the builder applies the
                // CTM captured when the path starts).
                Op::MoveTo(x, y) => {
                    if all_finite(&[*x, *y]) {
                        builder(&mut path, &gs).move_to(*x, *y);
                    }
                }
                Op::LineTo(x, y) => {
                    if all_finite(&[*x, *y]) {
                        builder(&mut path, &gs).line_to(*x, *y);
                    }
                }
                Op::CurveTo(x1, y1, x2, y2, x3, y3) => {
                    if all_finite(&[*x1, *y1, *x2, *y2, *x3, *y3]) {
                        builder(&mut path, &gs).curve_to(*x1, *y1, *x2, *y2, *x3, *y3);
                    }
                }
                Op::CurveToV(x2, y2, x3, y3) => {
                    if all_finite(&[*x2, *y2, *x3, *y3]) {
                        builder(&mut path, &gs).curve_to_v(*x2, *y2, *x3, *y3);
                    }
                }
                Op::CurveToY(x1, y1, x3, y3) => {
                    if all_finite(&[*x1, *y1, *x3, *y3]) {
                        builder(&mut path, &gs).curve_to_y(*x1, *y1, *x3, *y3);
                    }
                }
                Op::ClosePath => {
                    if let Some(pb) = path.as_mut() {
                        pb.close();
                    }
                }
                Op::Rect(x, y, w, h) => {
                    if all_finite(&[*x, *y, *w, *h]) {
                        builder(&mut path, &gs).rect(*x, *y, *w, *h);
                    }
                }

                // Path painting: fill first, then stroke; a pending W/W*
                // clip takes effect after any of these (including n).
                Op::Stroke => self.paint(&mut gs, &mut path, &mut pending_clip, PAINT_STROKE),
                Op::CloseStroke => self.paint(
                    &mut gs,
                    &mut path,
                    &mut pending_clip,
                    Paint {
                        close: true,
                        ..PAINT_STROKE
                    },
                ),
                Op::Fill => self.paint(&mut gs, &mut path, &mut pending_clip, PAINT_FILL),
                Op::FillEvenOdd => self.paint(&mut gs, &mut path, &mut pending_clip, PAINT_FILL_EO),
                Op::FillStroke => self.paint(&mut gs, &mut path, &mut pending_clip, PAINT_BOTH),
                Op::FillStrokeEvenOdd => {
                    self.paint(&mut gs, &mut path, &mut pending_clip, PAINT_BOTH_EO)
                }
                Op::CloseFillStroke => self.paint(
                    &mut gs,
                    &mut path,
                    &mut pending_clip,
                    Paint {
                        close: true,
                        ..PAINT_BOTH
                    },
                ),
                Op::CloseFillStrokeEvenOdd => self.paint(
                    &mut gs,
                    &mut path,
                    &mut pending_clip,
                    Paint {
                        close: true,
                        ..PAINT_BOTH_EO
                    },
                ),
                Op::EndPath => self.paint(&mut gs, &mut path, &mut pending_clip, PAINT_NONE),
                Op::ClipNonZero => pending_clip = Some(FillRule::NonZero),
                Op::ClipEvenOdd => pending_clip = Some(FillRule::EvenOdd),

                // Text: a minimal show-string state machine that paints
                // embedded TrueType glyph outlines (other fonts stay unpainted).
                Op::BeginText => {
                    ts.tm = Matrix::identity();
                    ts.tlm = Matrix::identity();
                }
                Op::SetCharSpacing(v) if v.is_finite() => ts.char_spacing = *v,
                Op::SetWordSpacing(v) if v.is_finite() => ts.word_spacing = *v,
                Op::SetHorizScaling(v) if v.is_finite() => ts.horiz = v / 100.0,
                Op::SetLeading(v) if v.is_finite() => ts.leading = *v,
                Op::SetTextRise(v) if v.is_finite() => ts.rise = *v,
                Op::SetFont(name, size) => {
                    ts.size = if size.is_finite() { *size } else { 0.0 };
                    ts.font = self.glyph_font(&name.0, chain, &mut fonts);
                    // Type3 is the fallback when no outline font loads: a
                    // `/Type3` dict at a tier that paints embedded programs.
                    // The invariant (at most one of font/type3) holds because
                    // this only runs when `ts.font` is `None`.
                    ts.type3 = if ts.font.is_some() {
                        None
                    } else {
                        self.type3_font(&name.0, chain)
                    };
                }
                Op::SetTextMatrix(m) if finite_matrix(m) => {
                    ts.tm = *m;
                    ts.tlm = *m;
                }
                Op::TextMove(tx, ty) if all_finite(&[*tx, *ty]) => {
                    ts.tlm = Matrix::translate(*tx, *ty).concat(ts.tlm);
                    ts.tm = ts.tlm;
                }
                Op::TextMoveSetLeading(tx, ty) if all_finite(&[*tx, *ty]) => {
                    ts.leading = -*ty;
                    ts.tlm = Matrix::translate(*tx, *ty).concat(ts.tlm);
                    ts.tm = ts.tlm;
                }
                Op::TextNextLine => {
                    ts.tlm = Matrix::translate(0.0, -ts.leading).concat(ts.tlm);
                    ts.tm = ts.tlm;
                }
                Op::ShowText(s) => self.show_text(&gs, &mut ts, s, chain, depth),
                Op::ShowTextAdjusted(items) => {
                    for item in items {
                        match item {
                            TextItem::Str(s) => self.show_text(&gs, &mut ts, s, chain, depth),
                            TextItem::Offset(n) => {
                                let tx = -n / 1000.0 * ts.size * ts.horiz;
                                if tx.is_finite() {
                                    ts.tm = Matrix::translate(tx, 0.0).concat(ts.tm);
                                }
                            }
                        }
                    }
                }
                Op::NextLineShowText(s) => {
                    ts.tlm = Matrix::translate(0.0, -ts.leading).concat(ts.tlm);
                    ts.tm = ts.tlm;
                    self.show_text(&gs, &mut ts, s, chain, depth);
                }
                Op::NextLineShowTextSpaced(aw, ac, s) => {
                    if aw.is_finite() {
                        ts.word_spacing = *aw;
                    }
                    if ac.is_finite() {
                        ts.char_spacing = *ac;
                    }
                    ts.tlm = Matrix::translate(0.0, -ts.leading).concat(ts.tlm);
                    ts.tm = ts.tlm;
                    self.show_text(&gs, &mut ts, s, chain, depth);
                }

                other => self.run_color_or_misc(other, chain, &mut gs, depth),
            }
        }
    }
}

/// Starts (or continues) the current path with the CTM in effect.
fn builder<'p>(path: &'p mut Option<PathBuilder>, gs: &GState) -> &'p mut PathBuilder {
    path.get_or_insert_with(|| PathBuilder::new(gs.ctm))
}

/// What a painting operator does with the current path.
#[derive(Clone, Copy)]
struct Paint {
    close: bool,
    fill: Option<FillRule>,
    stroke: bool,
}

const PAINT_NONE: Paint = Paint {
    close: false,
    fill: None,
    stroke: false,
};
const PAINT_STROKE: Paint = Paint {
    stroke: true,
    ..PAINT_NONE
};
const PAINT_FILL: Paint = Paint {
    fill: Some(FillRule::NonZero),
    ..PAINT_NONE
};
const PAINT_FILL_EO: Paint = Paint {
    fill: Some(FillRule::EvenOdd),
    ..PAINT_NONE
};
const PAINT_BOTH: Paint = Paint {
    stroke: true,
    ..PAINT_FILL
};
const PAINT_BOTH_EO: Paint = Paint {
    stroke: true,
    ..PAINT_FILL_EO
};

impl Executor<'_> {
    /// Fills and/or strokes the current path, applies any pending clip
    /// from `W`/`W*`, and resets the path.
    fn paint(
        &mut self,
        gs: &mut GState,
        path: &mut Option<PathBuilder>,
        pending: &mut Option<FillRule>,
        how: Paint,
    ) {
        let polys = match path.take() {
            Some(mut pb) => {
                if how.close {
                    pb.close();
                }
                pb.finish()
            }
            None => Vec::new(),
        };
        // A pattern paints its stand-in gray (see `GState::fill_rgba8`), so
        // every such paint is an approximation the caller should hear about
        // -- but only once the path actually covers something.
        if !polys.is_empty()
            && ((how.fill.is_some() && gs.fill_pattern) || (how.stroke && gs.stroke_pattern))
        {
            self.skip(SkippedKind::Pattern, SkipReason::Unsupported);
        }
        if let Some(rule) = how.fill {
            fill_path(
                &mut self.pix,
                &polys,
                rule,
                gs.fill_rgba8(),
                gs.fill_alpha,
                gs.clip.as_deref(),
            );
        }
        if how.stroke {
            let s = ctm_scale(gs.ctm);
            let dash: Vec<f32> = gs.dash.iter().map(|d| d * s).collect();
            let quads = stroke_path(&polys, gs.line_width * s, &dash, gs.dash_phase * s);
            fill_path(
                &mut self.pix,
                &quads,
                FillRule::NonZero,
                gs.stroke_rgba8(),
                gs.stroke_alpha,
                gs.clip.as_deref(),
            );
        }
        if let Some(rule) = pending.take() {
            let rasterized = self.rasterize_clip(&polys, rule);
            gs.clip = Some(match &gs.clip {
                Some(old) => Rc::new(Mask::intersected(&rasterized, old)),
                None => rasterized,
            });
        }
    }

    /// Rasterizes `polys` under `rule` into a clip [`Mask`], reusing a
    /// cached rasterization when the exact same path was clipped earlier on
    /// this page (very common: many generators repeat an identical
    /// page-bounds "reset" clip hundreds of times per page, and re-running
    /// the scanline rasterizer over the same geometry every time is pure
    /// waste). The returned mask is pre-intersection — the caller still
    /// applies any enclosing clip on top.
    fn rasterize_clip(&mut self, polys: &[Subpath], rule: FillRule) -> Rc<Mask> {
        let key = ClipKey::new(polys, rule);
        if let Some(cached) = self.clip_cache.get(&key) {
            return Rc::clone(cached);
        }
        let mask = Rc::new(Mask::from_path(
            self.pix.width,
            self.pix.height,
            polys,
            rule,
        ));
        if self.clip_cache.len() < MAX_CLIP_CACHE {
            self.clip_cache.insert(key, Rc::clone(&mask));
        }
        mask
    }

    /// Resolves and caches a paintable font by resource name (`None` for fonts
    /// whose glyphs cannot be drawn).
    fn glyph_font(
        &self,
        name: &str,
        chain: &[&Dict],
        cache: &mut FastMap<String, Option<Rc<GlyphFont>>>,
    ) -> Option<Rc<GlyphFont>> {
        if let Some(f) = cache.get(name) {
            return f.clone();
        }
        let loaded = self
            .find_res(chain, "Font", name)
            .and_then(|o| o.as_dict().cloned())
            .and_then(|d| {
                GlyphFont::load(self.doc, &d, self.painting, self.provider.as_deref()).map(Rc::new)
            });
        cache.insert(name.to_string(), loaded.clone());
        loaded
    }

    /// Resolves a `/Type3` font resource for painting, or `None` when the tier
    /// forbids embedded programs, the name is missing, or the resource is not a
    /// `/Type3` dict. Called only after the outline loader declined the name.
    fn type3_font(&self, name: &str, chain: &[&Dict]) -> Option<Rc<Type3Font>> {
        if !self.painting.paints_all_embedded() {
            return None;
        }
        let dict = self
            .find_res(chain, "Font", name)
            .and_then(|o| o.as_dict().cloned())?;
        if dict.get_name("Subtype").map(|n| n.0.as_str()) != Some("Type3") {
            return None;
        }
        Type3Font::load(self.doc, &dict).map(Rc::new)
    }

    /// Paints a cached, origin-relative flattened glyph outline at device
    /// origin `(dx, dy)` in color `fill`, reusing [`Executor::glyph_blit`] so
    /// a page of text paints without a fresh polygon allocation per glyph.
    /// The fill is anti-aliased, nonzero-rule, alpha- and clip-scaled exactly
    /// as a direct `fill_path` on the untranslated glyph would be.
    fn blit_glyph(&mut self, cached: &[Subpath], dx: f32, dy: f32, fill: [u8; 4], gs: &GState) {
        for (i, src) in cached.iter().enumerate() {
            if i == self.glyph_blit.len() {
                self.glyph_blit.push(Subpath {
                    points: Vec::new(),
                    closed: src.closed,
                });
            }
            let dst = &mut self.glyph_blit[i];
            dst.points.clear();
            dst.points
                .extend(src.points.iter().map(|p| Point::new(p.x + dx, p.y + dy)));
            dst.closed = src.closed;
        }
        fill_path(
            &mut self.pix,
            &self.glyph_blit[..cached.len()],
            FillRule::NonZero,
            fill,
            gs.fill_alpha,
            gs.clip.as_deref(),
        );
    }

    /// Paints one show-string's glyphs and advances the text matrix. Codes with
    /// no drawable glyph still advance, so surrounding text stays positioned.
    /// `chain`/`depth` thread the resource chain and form-recursion depth
    /// through to a Type3 glyph's CharProc (which re-enters [`Executor::run`]).
    fn show_text(
        &mut self,
        gs: &GState,
        ts: &mut TextState,
        bytes: &[u8],
        chain: &[&Dict],
        depth: u32,
    ) {
        if ts.type3.is_some() {
            self.show_text_type3(gs, ts, bytes, chain, depth);
            return;
        }
        let Some(font) = ts.font.clone() else {
            return;
        };
        let upm = font.units_per_em();
        let two_byte = font.two_byte();
        let fill = gs.fill_rgba8();
        let mut i = 0;
        while i < bytes.len() {
            let (code, n) = if two_byte && i + 1 < bytes.len() {
                (u32::from(u16::from_be_bytes([bytes[i], bytes[i + 1]])), 2)
            } else {
                (u32::from(bytes[i]), 1)
            };
            i += n;
            let gid = font.gid(code);

            // glyph units -> text space (÷ em, then the text-scaling params),
            // -> user space (Tm) -> device (CTM).
            let params = Matrix {
                a: ts.size * ts.horiz,
                b: 0.0,
                c: 0.0,
                d: ts.size,
                e: 0.0,
                f: ts.rise,
            };
            let to_device = Matrix::scale(1.0 / upm, 1.0 / upm)
                .concat(params)
                .concat(ts.tm)
                .concat(gs.ctm);
            if gid != 0 && finite_matrix(&to_device) {
                // Flatten under the linear part only (memoized per glyph +
                // linear map); the per-glyph translation is applied when the
                // cached outline is blitted, keeping the flatten reusable
                // across every occurrence in the run.
                let linear = Matrix {
                    a: to_device.a,
                    b: to_device.b,
                    c: to_device.c,
                    d: to_device.d,
                    e: 0.0,
                    f: 0.0,
                };
                let polys = font.flattened(gid, linear);
                if !polys.is_empty() {
                    self.blit_glyph(&polys, to_device.e, to_device.f, fill, gs);
                }
            }

            // Advance: (w0·Tfs + Tc + Tw[single-byte space]) · Th.
            let w0 = font.advance(code) / upm;
            let word = if n == 1 && code == 32 {
                ts.word_spacing
            } else {
                0.0
            };
            let tx = (w0 * ts.size + ts.char_spacing + word) * ts.horiz;
            if tx.is_finite() {
                ts.tm = Matrix::translate(tx, 0.0).concat(ts.tm);
            }
        }
    }

    /// Paints a `/Type3` show-string: each one-byte code's CharProc runs as a
    /// nested content stream (ISO 32000-1 §9.6.5). The glyph matrix mirrors the
    /// outline path with `/FontMatrix` in place of the `1/upm` scale, so glyph
    /// space maps through text space, the text state, and the CTM to device.
    /// Codes with no CharProc, a non-finite matrix, or a depth at the recursion
    /// limit still advance, keeping surrounding text positioned.
    fn show_text_type3(
        &mut self,
        gs: &GState,
        ts: &mut TextState,
        bytes: &[u8],
        chain: &[&Dict],
        depth: u32,
    ) {
        let Some(t3) = ts.type3.clone() else {
            return;
        };
        let font_matrix = t3.font_matrix();
        for &byte in bytes {
            let code = u32::from(byte);

            // glyph space -> text space (/FontMatrix), -> the text-scaling
            // params, -> user space (Tm) -> device (CTM): the outline chain
            // with `font_matrix` substituted for `scale(1/upm)`.
            let params = Matrix {
                a: ts.size * ts.horiz,
                b: 0.0,
                c: 0.0,
                d: ts.size,
                e: 0.0,
                f: ts.rise,
            };
            let glyph_ctm = font_matrix.concat(params).concat(ts.tm).concat(gs.ctm);

            // The depth guard bounds a self-referential glyph (one that shows
            // itself, directly or via a form): each CharProc re-entry increments
            // `depth`, so painting stops at `MAX_FORM_DEPTH`.
            if depth < MAX_FORM_DEPTH && finite_matrix(&glyph_ctm) {
                if let Some(proc_obj) = t3.char_proc(code).cloned() {
                    self.run_char_proc(&proc_obj, &t3, chain, gs, glyph_ctm, depth);
                }
            }

            // Advance: the glyph-space width becomes a text-space displacement
            // via the matrix x-scale, then (w0·Tfs + Tc + Tw[space]) · Th.
            let w0 = t3.width(code).unwrap_or(0.0) * font_matrix.a;
            let word = if code == 32 { ts.word_spacing } else { 0.0 };
            let tx = (w0 * ts.size + ts.char_spacing + word) * ts.horiz;
            if tx.is_finite() {
                ts.tm = Matrix::translate(tx, 0.0).concat(ts.tm);
            }
        }
    }

    /// Runs one Type3 CharProc: resolve its stream, parse it, and re-enter
    /// [`Executor::run`] with the glyph CTM, the font's own `/Resources`
    /// prepended to `chain`, and `depth + 1`. Inherits the caller's clip,
    /// alpha, and fill color (the color a `d0` glyph paints in). Every failure
    /// is a silent skip, matching the caller's still-advance leniency.
    ///
    /// ISO 32000-1 §9.6.5.2: the CharProc's *first* operator is `d0`
    /// (colored) or `d1` (uncolored). A `d1` glyph "shall not specify any
    /// color" -- its own color operators are ignored and it paints in the
    /// current text fill color -- so `color_locked` is set for the nested
    /// `run` iff the first op is `Op::SetGlyphWidthBBox`. The previous lock
    /// is saved and restored around the call (not just set to `true`) so a
    /// `d0` glyph nested inside a `d1` glyph regains color control for its
    /// own subtree, while a `d1` nested inside a `d1` stays locked, and the
    /// lock never leaks into sibling or outer content.
    fn run_char_proc(
        &mut self,
        proc_obj: &Object,
        t3: &Type3Font,
        chain: &[&Dict],
        base: &GState,
        glyph_ctm: Matrix,
        depth: u32,
    ) {
        let Ok(Object::Stream(stream)) = self.doc.resolve(proc_obj) else {
            return;
        };
        let Ok(data) = self.doc.stream_data(&stream) else {
            return;
        };
        let Ok(ops) = parse_content(&data) else {
            return;
        };
        let mut inner = base.clone();
        inner.ctm = glyph_ctm;
        let mut inner_chain: Vec<&Dict> = Vec::with_capacity(chain.len() + 1);
        if let Some(d) = t3.resources() {
            inner_chain.push(d);
        }
        inner_chain.extend_from_slice(chain);
        let is_d1 = matches!(ops.first(), Some(Op::SetGlyphWidthBBox(..)));
        let saved_lock = self.color_locked;
        self.color_locked = is_d1;
        self.run(&ops, &inner_chain, inner, depth + 1);
        self.color_locked = saved_lock;
    }

    /// Dispatches color, XObject, and marked-content operators (the remainder
    /// of the [`Op`] alphabet not handled directly in `run`).
    ///
    /// Every fill/stroke color-setting arm is a no-op while
    /// `self.color_locked` (inside a `d1` Type3 CharProc, ISO 32000-1
    /// §9.6.5.2): the glyph keeps the fill/stroke color inherited from the
    /// text graphics state instead of applying its own. XObject, inline
    /// image, shading, and marked-content ops are unaffected by the lock.
    fn run_color_or_misc(&mut self, op: &Op, chain: &[&Dict], gs: &mut GState, depth: u32) {
        if self.color_locked {
            match op {
                Op::SetFillColorSpace(_)
                | Op::SetStrokeColorSpace(_)
                | Op::SetFillColor(_)
                | Op::SetStrokeColor(_)
                | Op::SetFillColorN(_, _)
                | Op::SetStrokeColorN(_, _)
                | Op::SetFillGray(_)
                | Op::SetStrokeGray(_)
                | Op::SetFillRGB(_, _, _)
                | Op::SetStrokeRGB(_, _, _)
                | Op::SetFillCMYK(_, _, _, _)
                | Op::SetStrokeCMYK(_, _, _, _) => return,
                _ => {}
            }
        }
        match op {
            Op::SetFillColorSpace(name) => {
                let (cs, pattern) = self.resolve_colorspace(name, chain);
                gs.fill_rgb = initial_color(&cs);
                gs.fill_space = cs;
                gs.fill_pattern = pattern;
            }
            Op::SetStrokeColorSpace(name) => {
                let (cs, pattern) = self.resolve_colorspace(name, chain);
                gs.stroke_rgb = initial_color(&cs);
                gs.stroke_space = cs;
                gs.stroke_pattern = pattern;
            }
            Op::SetFillColor(c) => gs.fill_rgb = gs.fill_space.to_rgb(c),
            Op::SetStrokeColor(c) => gs.stroke_rgb = gs.stroke_space.to_rgb(c),
            Op::SetFillColorN(c, pattern_name) => {
                if pattern_name.is_some() {
                    gs.fill_pattern = true;
                } else if !gs.fill_pattern {
                    gs.fill_rgb = gs.fill_space.to_rgb(c);
                }
            }
            Op::SetStrokeColorN(c, pattern_name) => {
                if pattern_name.is_some() {
                    gs.stroke_pattern = true;
                } else if !gs.stroke_pattern {
                    gs.stroke_rgb = gs.stroke_space.to_rgb(c);
                }
            }
            Op::SetFillGray(g) => {
                gs.fill_space = ColorSpace::DeviceGray;
                gs.fill_pattern = false;
                gs.fill_rgb = ColorSpace::DeviceGray.to_rgb(&[*g]);
            }
            Op::SetStrokeGray(g) => {
                gs.stroke_space = ColorSpace::DeviceGray;
                gs.stroke_pattern = false;
                gs.stroke_rgb = ColorSpace::DeviceGray.to_rgb(&[*g]);
            }
            Op::SetFillRGB(r, g, b) => {
                gs.fill_space = ColorSpace::DeviceRGB;
                gs.fill_pattern = false;
                gs.fill_rgb = ColorSpace::DeviceRGB.to_rgb(&[*r, *g, *b]);
            }
            Op::SetStrokeRGB(r, g, b) => {
                gs.stroke_space = ColorSpace::DeviceRGB;
                gs.stroke_pattern = false;
                gs.stroke_rgb = ColorSpace::DeviceRGB.to_rgb(&[*r, *g, *b]);
            }
            Op::SetFillCMYK(c, m, y, k) => {
                gs.fill_space = ColorSpace::DeviceCMYK;
                gs.fill_pattern = false;
                gs.fill_rgb = ColorSpace::DeviceCMYK.to_rgb(&[*c, *m, *y, *k]);
            }
            Op::SetStrokeCMYK(c, m, y, k) => {
                gs.stroke_space = ColorSpace::DeviceCMYK;
                gs.stroke_pattern = false;
                gs.stroke_rgb = ColorSpace::DeviceCMYK.to_rgb(&[*c, *m, *y, *k]);
            }
            Op::XObject(name) => self.do_xobject(name, chain, gs, depth),
            Op::InlineImage(img) => self.draw_inline_image(img, chain, gs),
            // Shadings are out of scope for v0.1: `sh` paints nothing, so a
            // page whose visible content is a gradient comes out blank.
            Op::Shading(_) => self.skip(SkippedKind::Shading, SkipReason::Unsupported),
            // Text and marked content: state-only in v0.1, nothing painted.
            _ => {}
        }
    }
}

/// The initial color after selecting a color space: black for the device
/// and Indexed spaces (CMYK black is `K = 1`). Separation/DeviceN start at
/// full tint 1.0 (ISO 32000-1 8.6.6.4/8.6.6.5), which the tint
/// approximation paints as gray 0; feeding 1.0 everywhere also gives the
/// right dark initial color for Lab (`L = 0`), the other `Other` space.
fn initial_color(cs: &ColorSpace) -> [f32; 3] {
    match cs {
        ColorSpace::DeviceCMYK => cs.to_rgb(&[0.0, 0.0, 0.0, 1.0]),
        ColorSpace::Other(_) => cs.to_rgb(&[1.0; 8]),
        _ => cs.to_rgb(&[0.0, 0.0, 0.0, 0.0]),
    }
}

impl Executor<'_> {
    /// Looks up `/category/name` in the resource chain (innermost dict
    /// first), resolving references at every step.
    fn find_res(&self, chain: &[&Dict], category: &str, name: &str) -> Option<Object> {
        for res in chain {
            let Some(cat) = res.get(category) else {
                continue;
            };
            let Ok(Object::Dict(dict)) = self.doc.resolve(cat) else {
                continue;
            };
            let Some(value) = dict.get(name) else {
                continue;
            };
            if let Ok(obj) = self.doc.resolve(value) {
                if !obj.is_null() {
                    return Some(obj);
                }
            }
        }
        None
    }

    /// Resolves a `cs`/`CS` operand: a device space name directly, the
    /// `/Pattern` space as a mid-gray flag, anything else through the
    /// `/ColorSpace` resource dictionary. Returns `(space, is_pattern)`.
    fn resolve_colorspace(&self, name: &Name, chain: &[&Dict]) -> (ColorSpace, bool) {
        match name.0.as_str() {
            "Pattern" => return (ColorSpace::DeviceGray, true),
            "DeviceGray" | "G" | "CalGray" => return (ColorSpace::DeviceGray, false),
            "DeviceRGB" | "RGB" | "CalRGB" => return (ColorSpace::DeviceRGB, false),
            "DeviceCMYK" | "CMYK" => return (ColorSpace::DeviceCMYK, false),
            _ => {}
        }
        match self.find_res(chain, "ColorSpace", &name.0) {
            Some(obj) => {
                // `[/Pattern base]` resource entries are pattern spaces too.
                if let Object::Array(items) = &obj {
                    if let Some(Object::Name(n)) = items.first() {
                        if n.0 == "Pattern" {
                            return (ColorSpace::DeviceGray, true);
                        }
                    }
                }
                (ColorSpace::parse(self.doc, &obj), false)
            }
            None => (ColorSpace::DeviceGray, false),
        }
    }

    /// Applies the `/ca /CA /LW /LC /LJ /D` entries of the named
    /// `/ExtGState` resource. Other entries are ignored in v0.1; the two
    /// that change what the page looks like -- a `/SMask` mask group and a
    /// non-`Normal` `/BM` blend mode -- are reported so the caller knows the
    /// render is an approximation.
    fn apply_ext_gstate(&mut self, name: &Name, chain: &[&Dict], gs: &mut GState) {
        let Some(Object::Dict(dict)) = self.find_res(chain, "ExtGState", &name.0) else {
            return;
        };
        if ignores_mask(self.doc, &dict) {
            self.skip(SkippedKind::SoftMask, SkipReason::Unsupported);
        }
        if ignores_blend_mode(self.doc, &dict) {
            self.skip(SkippedKind::BlendMode, SkipReason::Unsupported);
        }
        let num = |key: &str| -> Option<f32> {
            let v = self.doc.resolve(dict.get(key)?).ok()?.as_f64()? as f32;
            v.is_finite().then_some(v)
        };
        if let Some(ca) = num("ca") {
            gs.fill_alpha = ca.clamp(0.0, 1.0);
        }
        if let Some(ca) = num("CA") {
            gs.stroke_alpha = ca.clamp(0.0, 1.0);
        }
        if let Some(lw) = num("LW") {
            if lw >= 0.0 {
                gs.line_width = lw;
            }
        }
        if let Some(lc) = num("LC") {
            gs.line_cap = lc as i32;
        }
        if let Some(lj) = num("LJ") {
            gs.line_join = lj as i32;
        }
        if let Some(Ok(Object::Array(items))) = dict.get("D").map(|o| self.doc.resolve(o)) {
            if let (Some(Ok(Object::Array(lens))), Some(phase)) = (
                items.first().map(|o| self.doc.resolve(o)),
                items
                    .get(1)
                    .and_then(|o| self.doc.resolve(o).ok()?.as_f64()),
            ) {
                let dash: Vec<f32> = lens.iter().filter_map(|o| num_f32(self.doc, o)).collect();
                if dash.len() == lens.len() && (phase as f32).is_finite() {
                    gs.dash = dash;
                    gs.dash_phase = phase as f32;
                }
            }
        }
    }
}

/// Resolves an object to a finite `f32`.
fn num_f32(doc: &Document, obj: &Object) -> Option<f32> {
    let v = doc.resolve(obj).ok()?.as_f64()? as f32;
    v.is_finite().then_some(v)
}

/// Reads the first `n` finite numbers of a (possibly indirect) array.
fn floats_from(doc: &Document, obj: Option<&Object>, n: usize) -> Option<Vec<f32>> {
    let arr = match doc.resolve(obj?) {
        Ok(Object::Array(a)) if a.len() >= n => a,
        _ => return None,
    };
    let out: Vec<f32> = arr.iter().take(n).filter_map(|o| num_f32(doc, o)).collect();
    (out.len() == n).then_some(out)
}

/// Maps a stream-decode or content-parse failure onto the reason reported
/// to callers.
fn skip_reason_for(e: &Error) -> SkipReason {
    match e {
        Error::UnsupportedFilter(name) => SkipReason::UnsupportedFilter(name.clone()),
        other => SkipReason::DecodeFailed(other.to_string()),
    }
}

/// Whether an image dictionary carries masking this renderer ignores: a
/// `/SMask` alpha channel, or a `/Mask` stencil or color-key array (ISO
/// 32000-1 8.9.6). What the author masked out paints solid instead, so the
/// caller reports it rather than passing the result off as the real image.
fn ignores_mask(doc: &Document, dict: &Dict) -> bool {
    ["SMask", "Mask"].iter().any(|key| {
        match dict.get(key).map(|obj| doc.resolve(obj)) {
            None | Some(Ok(Object::Null)) => false,
            // `/SMask /None` in particular is the explicit "no mask" value.
            Some(Ok(Object::Name(n))) => n.0 != "None",
            _ => true,
        }
    })
}

/// Whether an `/ExtGState` selects a blend mode this renderer does not
/// apply (ISO 32000-1 11.3.5). Everything composites source-over, so
/// anything but `Normal` (and its deprecated alias `Compatible`) paints
/// differently than the page asks for.
fn ignores_blend_mode(doc: &Document, dict: &Dict) -> bool {
    // An array-valued `/BM` names the first mode the reader supports.
    let selected = match dict.get("BM").map(|obj| doc.resolve(obj)) {
        Some(Ok(Object::Name(n))) => n.0,
        Some(Ok(Object::Array(items))) => match items.first().map(|obj| doc.resolve(obj)) {
            Some(Ok(Object::Name(n))) => n.0,
            _ => return false,
        },
        _ => return false,
    };
    !matches!(selected.as_str(), "Normal" | "Compatible")
}

impl Executor<'_> {
    /// Executes `Do`: draws an image XObject or recurses into a form.
    fn do_xobject(&mut self, name: &Name, chain: &[&Dict], gs: &GState, depth: u32) {
        let Some(Object::Stream(stream)) = self.find_res(chain, "XObject", &name.0) else {
            // The name resolves to nothing, or to something that is not a
            // stream: whatever it was meant to draw, it is not drawn.
            self.skip(SkippedKind::XObject, SkipReason::Missing);
            return;
        };
        match stream.dict.get_name("Subtype").map(|n| n.0.as_str()) {
            Some("Image") => self.draw_image_xobject(&stream, chain, gs),
            Some("Form") => self.run_form(&stream, chain, gs, depth),
            // Neither subtype: a `/PS` XObject, or (seen in the wild) an
            // image whose dictionary omits `/Subtype` entirely.
            _ => self.skip(SkippedKind::XObject, SkipReason::Unsupported),
        }
    }

    /// Runs a form XObject: `/Matrix` concatenated before the CTM, `/BBox`
    /// intersected into the clip, own `/Resources` prepended to the chain,
    /// bounded recursion.
    fn run_form(&mut self, stream: &Stream, chain: &[&Dict], gs: &GState, depth: u32) {
        // Every bail-out below drops the form's whole content subtree --
        // images, shadings and nested forms included -- so each one is
        // reported rather than leaving a hole nobody can account for.
        if depth >= MAX_FORM_DEPTH {
            self.skip(SkippedKind::Form, SkipReason::LimitExceeded);
            return;
        }
        let data = match self.doc.stream_data(stream) {
            Ok(data) => data,
            Err(e) => {
                self.skip(SkippedKind::Form, skip_reason_for(&e));
                return;
            }
        };
        let ops = match parse_content(&data) {
            Ok(ops) => ops,
            Err(e) => {
                self.skip(SkippedKind::Form, skip_reason_for(&e));
                return;
            }
        };
        let mut inner = gs.clone();
        if let Some(m) = floats_from(self.doc, stream.dict.get("Matrix"), 6) {
            let matrix = Matrix {
                a: m[0],
                b: m[1],
                c: m[2],
                d: m[3],
                e: m[4],
                f: m[5],
            };
            inner.ctm = matrix.concat(inner.ctm);
        }
        if let Some(b) = floats_from(self.doc, stream.dict.get("BBox"), 4) {
            let (x0, x1) = (b[0].min(b[2]), b[0].max(b[2]));
            let (y0, y1) = (b[1].min(b[3]), b[1].max(b[3]));
            let mut pb = PathBuilder::new(inner.ctm);
            pb.rect(x0, y0, x1 - x0, y1 - y0);
            let rasterized = self.rasterize_clip(&pb.finish(), FillRule::NonZero);
            inner.clip = Some(match &inner.clip {
                Some(old) => Rc::new(Mask::intersected(&rasterized, old)),
                None => rasterized,
            });
        }
        let own_res = match stream.dict.get("Resources").map(|o| self.doc.resolve(o)) {
            Some(Ok(Object::Dict(d))) => Some(d),
            _ => None,
        };
        let mut inner_chain: Vec<&Dict> = Vec::with_capacity(chain.len() + 1);
        if let Some(d) = &own_res {
            inner_chain.push(d);
        }
        inner_chain.extend_from_slice(chain);
        self.run(&ops, &inner_chain, inner, depth + 1);
    }

    /// Records one piece of content this render could not reproduce.
    fn skip(&mut self, kind: SkippedKind, reason: SkipReason) {
        self.report.record(kind, reason);
    }

    /// Draws an image XObject with the current CTM/clip/alpha; the fill
    /// color paints through `/ImageMask` stencils.
    fn draw_image_xobject(&mut self, stream: &Stream, chain: &[&Dict], gs: &GState) {
        let data = match self.doc.stream_data(stream) {
            Ok(data) => data,
            Err(e) => {
                self.skip(SkippedKind::Image, skip_reason_for(&e));
                return;
            }
        };
        let cs_obj = self.image_colorspace(&stream.dict, chain);
        self.blit_image(&stream.dict, &data, cs_obj, gs);
    }

    /// Draws an inline image: its filters (abbreviations included) are
    /// applied here, then it follows the XObject path.
    fn draw_inline_image(&mut self, img: &ImageParams, chain: &[&Dict], gs: &GState) {
        let stream = Stream {
            dict: img.dict.clone(),
            data: img.data.clone(),
        };
        let data = match decode_stream(&stream, self.doc) {
            Ok(data) => data,
            Err(e) => {
                self.skip(SkippedKind::Image, skip_reason_for(&e));
                return;
            }
        };
        let cs_obj = self.image_colorspace(&img.dict, chain);
        self.blit_image(&img.dict, &data, cs_obj, gs);
    }

    fn blit_image(&mut self, dict: &Dict, data: &[u8], cs_obj: Option<Object>, gs: &GState) {
        // `data` is decoded samples or a raw JPEG: the filter chain passes
        // only `DCTDecode` through (ISO 32000-1 7.4.9) and rejects every
        // other codec, so no codestream reaches the sample reader. That
        // rejection surfaces above, where `stream_data` fails.
        //
        // An `/Indexed` palette stored as a stream that will not decode
        // leaves the space with no palette at all, painting every sample
        // black; the image still draws, but not as the page describes it.
        if let Some(e) = cs_obj
            .as_ref()
            .and_then(|o| color::palette_error(self.doc, o))
        {
            self.skip(SkippedKind::Image, skip_reason_for(&e));
        }
        if ignores_mask(self.doc, dict) {
            self.skip(SkippedKind::SoftMask, SkipReason::Unsupported);
        }
        if gs.fill_pattern && image::is_stencil(self.doc, dict) {
            // The stencil paints the pattern's stand-in gray, not the
            // pattern (see `GState::fill_rgba8`).
            self.skip(SkippedKind::Pattern, SkipReason::Unsupported);
        }
        let fill = gs.fill_rgba8();
        let outcome = image::draw(
            self.doc,
            &mut self.pix,
            dict,
            data,
            cs_obj.as_ref(),
            &DrawParams {
                ctm: gs.ctm,
                alpha: gs.fill_alpha,
                fill_rgb: [fill[0], fill[1], fill[2]],
                clip: gs.clip.as_deref(),
            },
        );
        match outcome {
            image::Drawn::Whole => {}
            image::Drawn::Truncated => self.skip(SkippedKind::Image, SkipReason::Truncated),
            image::Drawn::Nothing => self.skip(SkippedKind::Image, SkipReason::Undecodable),
        }
    }

    /// The image's `/ColorSpace` value with resource-name indirection
    /// resolved: a non-device name is looked up in `/ColorSpace` resources.
    fn image_colorspace(&self, dict: &Dict, chain: &[&Dict]) -> Option<Object> {
        let resolved = self.doc.resolve(dict.get("ColorSpace")?).ok()?;
        if let Object::Name(n) = &resolved {
            let device = matches!(
                n.0.as_str(),
                "DeviceGray" | "DeviceRGB" | "DeviceCMYK" | "G" | "RGB" | "CMYK"
            );
            if !device {
                if let Some(from_res) = self.find_res(chain, "ColorSpace", &n.0) {
                    return Some(from_res);
                }
            }
        }
        Some(resolved)
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    // The crate-root wrapper, exercised here so these tests keep covering the
    // exact entry point external callers use.
    use crate::render_page_with_options;
    use crate::{GlyphPainting, RenderOptions};
    use pdfboss_testkit::{doc_with_graphics, PdfBuilder};

    #[test]
    fn render_options_default_is_all_embedded() {
        assert_eq!(
            RenderOptions::default().glyph_painting,
            GlyphPainting::AllEmbedded
        );
    }

    #[test]
    fn all_glyph_tiers_match_default_render_today() {
        // The content stream is a raw filled rectangle with no font at all,
        // so no glyph loading happens at any tier -- the render is
        // tier-invariant by construction, regardless of which loaders exist.
        let bytes = small_doc("", b"1 0 0 rg 10 10 80 80 re f", |_| {});
        let doc = Document::load(bytes).expect("load");
        let page = doc.page(0).expect("page");
        let base =
            render_page_with_options(&doc, &page, 1.0, &RenderOptions::default()).expect("render");
        for tier in [
            GlyphPainting::EmbeddedTrueTypeOnly,
            GlyphPainting::AllEmbedded,
            GlyphPainting::Full,
        ] {
            let opts = RenderOptions {
                glyph_painting: tier,
                ..Default::default()
            };
            let got = render_page_with_options(&doc, &page, 1.0, &opts).expect("render");
            assert_eq!(got, base, "tier {tier:?} differs from default render");
        }
    }

    /// Renders page 0 of `bytes` at `scale`.
    fn render(bytes: Vec<u8>, scale: f32) -> Pixmap {
        let doc = Document::load(bytes).expect("load");
        let page = doc.page(0).expect("page");
        render_page_with_options(&doc, &page, scale, &RenderOptions::default()).expect("render")
    }

    fn px(pix: &Pixmap, x: u32, y: u32) -> [u8; 4] {
        let off = ((y * pix.width + x) * 4) as usize;
        pix.data[off..off + 4].try_into().unwrap()
    }

    const WHITE: [u8; 4] = [255, 255, 255, 255];
    const RED: [u8; 4] = [255, 0, 0, 255];
    const BLACK: [u8; 4] = [0, 0, 0, 255];

    /// A one-page 100x100 document with the given content and resources.
    fn small_doc(resources: &str, content: &[u8], extra: impl FnOnce(&mut PdfBuilder)) -> Vec<u8> {
        let mut b = PdfBuilder::new();
        b.object(1, "<< /Type /Catalog /Pages 2 0 R >>");
        b.object(2, "<< /Type /Pages /Kids [3 0 R] /Count 1 >>");
        b.object(
            3,
            &format!(
                "<< /Type /Page /Parent 2 0 R /MediaBox [0 0 100 100] \
                 /Resources << {resources} >> /Contents 4 0 R >>"
            ),
        );
        b.stream(4, "", content);
        extra(&mut b);
        b.build(1)
    }

    #[test]
    fn red_rect_fills_at_yflipped_device_location() {
        // 612x792 page; user rect [100,300]x[100,250] -> device rows
        // [542,692] after the y-flip.
        let pix = render(doc_with_graphics("1 0 0 rg 100 100 200 150 re f"), 1.0);
        assert_eq!((pix.width, pix.height), (612, 792));
        assert_eq!(px(&pix, 200, 600), RED, "interior");
        assert_eq!(px(&pix, 101, 543), RED, "top-left corner inside");
        assert_eq!(px(&pix, 298, 690), RED, "bottom-right corner inside");
        assert_eq!(px(&pix, 200, 530), WHITE, "above rect (device)");
        assert_eq!(px(&pix, 200, 700), WHITE, "below rect (device)");
        assert_eq!(px(&pix, 95, 600), WHITE, "left of rect");
        assert_eq!(px(&pix, 305, 600), WHITE, "right of rect");
        assert_eq!(
            px(&pix, 200, 100),
            WHITE,
            "user-space y kept would paint here"
        );
    }

    #[test]
    fn clip_limits_full_page_fill() {
        let content = "20 20 40 40 re W n 0 0 612 792 re f";
        let pix = render(doc_with_graphics(content), 1.0);
        // Clip rect [20,60]^2 user -> device rows [732,772].
        assert_eq!(px(&pix, 40, 750), BLACK, "inside clip");
        assert_eq!(px(&pix, 40, 700), WHITE, "above clip");
        assert_eq!(px(&pix, 70, 750), WHITE, "right of clip");
        assert_eq!(px(&pix, 300, 400), WHITE, "page center untouched");
    }

    #[test]
    fn cm_translate_scale_moves_rect() {
        let content = "1 0 0 rg q 2 0 0 2 50 30 cm 10 10 20 20 re f Q";
        let pix = render(doc_with_graphics(content), 1.0);
        // User rect [10,30]^2 through cm -> [70,110]x[50,90] -> device
        // rows [702,742].
        assert_eq!(px(&pix, 90, 720), RED, "transformed interior");
        assert_eq!(px(&pix, 60, 720), WHITE, "left of transformed rect");
        assert_eq!(px(&pix, 90, 750), WHITE, "below transformed rect");
        assert_eq!(px(&pix, 20, 770), WHITE, "untransformed location clear");
    }

    #[test]
    fn q_restore_resets_color_and_nonfinite_cm_is_skipped() {
        let content = "1 0 0 rg q 0 1 0 rg Q 10 10 20 20 re f";
        let pix = render(doc_with_graphics(content), 1.0);
        assert_eq!(px(&pix, 20, 770), RED, "Q restored the red fill");

        // 1e39 overflows f32 -> non-finite cm must be skipped entirely.
        let content = "1e39 0 0 1e39 0 0 cm 1 0 0 rg 10 10 20 20 re f";
        let pix = render(doc_with_graphics(content), 1.0);
        assert_eq!(px(&pix, 20, 770), RED, "rect painted with identity ctm");
    }

    #[test]
    fn extgstate_ca_blends_toward_white() {
        let bytes = small_doc(
            "/ExtGState << /G1 5 0 R >>",
            b"/G1 gs 1 0 0 rg 0 0 100 100 re f",
            |b| {
                b.object(5, "<< /Type /ExtGState /ca 0.5 >>");
            },
        );
        let pix = render(bytes, 1.0);
        let [r, g, b, a] = px(&pix, 50, 50);
        assert_eq!(r, 255);
        assert!((127..=129).contains(&g), "green {g}");
        assert!((127..=129).contains(&b), "blue {b}");
        assert_eq!(a, 255);
    }

    #[test]
    fn stroke_width_scales_with_ctm() {
        // 4x CTM scale turns a 1pt pen into a ~4px device band; the line
        // at user y=20 lands on device row 792 - 80 = 712.
        let content = "4 0 0 4 0 0 cm 1 w 10 20 m 140 20 l S";
        let pix = render(doc_with_graphics(content), 1.0);
        let dark = (700..725).filter(|&y| px(&pix, 300, y)[0] < 128).count();
        assert!((3..=5).contains(&dark), "band thickness {dark}");

        // Unscaled 1pt pen: ~1px of ink, possibly split across two rows
        // as 50% coverage each.
        let pix = render(doc_with_graphics("1 w 10 80 m 560 80 l S"), 1.0);
        let inked = (700..725).filter(|&y| px(&pix, 300, y)[0] < 200).count();
        assert!((1..=2).contains(&inked), "hairline thickness {inked}");
    }

    #[test]
    fn dashed_stroke_leaves_gaps() {
        let content = "2 w [6 6] 0 d 10 50 m 90 50 l S";
        let pix = render(small_doc("", content.as_bytes(), |_| {}), 1.0);
        assert_eq!((pix.width, pix.height), (100, 100));
        let mut runs = 0;
        let mut prev_on = false;
        for x in 0..100 {
            let on = px(&pix, x, 50)[0] < 128;
            if on && !prev_on {
                runs += 1;
            }
            prev_on = on;
        }
        assert!(runs >= 4, "expected several dash runs, got {runs}");
    }

    #[test]
    fn separation_and_devicen_initial_color_is_full_tint() {
        // ISO 32000-1 8.6.6.4/8.6.6.5: selecting a Separation or DeviceN
        // space with `cs` sets every component to 1.0, so painting before
        // any `scn` must give a full-tint (dark) mark, not white.
        for (entry, content) in [
            // Fill: broken initial color paints white-on-white.
            (
                "[/Separation /Spot /DeviceGray 5 0 R]",
                "/T cs 10 10 80 80 re f",
            ),
            (
                "[/DeviceN [/A /B] /DeviceGray 5 0 R]",
                "/T cs 10 10 80 80 re f",
            ),
            // Stroke: a thick line through the page center.
            (
                "[/Separation /Spot /DeviceGray 5 0 R]",
                "/T CS 20 w 10 50 m 90 50 l S",
            ),
        ] {
            let bytes = small_doc("/ColorSpace << /T 6 0 R >>", content.as_bytes(), |b| {
                b.object(5, "<< /FunctionType 2 /Domain [0 1] /N 1 >>");
                b.object(6, entry);
            });
            let pix = render(bytes, 1.0);
            assert_eq!(px(&pix, 50, 50), BLACK, "{entry} via `{content}`");
        }
        // An explicit `0 scn` still overrides the initial color to white.
        let bytes = small_doc(
            "/ColorSpace << /T 6 0 R >>",
            b"/T cs 0 scn 10 10 80 80 re f",
            |b| {
                b.object(5, "<< /FunctionType 2 /Domain [0 1] /N 1 >>");
                b.object(6, "[/Separation /Spot /DeviceGray 5 0 R]");
            },
        );
        assert_eq!(px(&render(bytes, 1.0), 50, 50), WHITE, "0 scn wins");
    }

    #[test]
    fn form_xobject_matrix_paints_displaced() {
        let bytes = small_doc("/XObject << /Fm1 5 0 R >>", b"/Fm1 Do", |b| {
            b.stream(
                5,
                "/Type /XObject /Subtype /Form /BBox [0 0 50 50] \
                     /Matrix [1 0 0 1 20 30]",
                b"1 0 0 rg 0 0 50 50 re f",
            );
        });
        let pix = render(bytes, 1.0);
        // Form square [0,50]^2 shifted to [20,70]x[30,80] user -> device
        // rows [20,70].
        assert_eq!(px(&pix, 40, 50), RED, "displaced interior");
        assert_eq!(px(&pix, 10, 50), WHITE, "left of form");
        assert_eq!(px(&pix, 40, 80), WHITE, "below form");
        assert_eq!(px(&pix, 40, 10), WHITE, "above form");
    }

    #[test]
    fn form_bbox_clips_its_content() {
        let bytes = small_doc("/XObject << /Fm1 5 0 R >>", b"/Fm1 Do", |b| {
            // Content paints [0,80]^2 but the BBox stops it at 40.
            b.stream(
                5,
                "/Type /XObject /Subtype /Form /BBox [0 0 40 40]",
                b"1 0 0 rg 0 0 80 80 re f",
            );
        });
        let pix = render(bytes, 1.0);
        assert_eq!(px(&pix, 20, 80), RED, "inside bbox (device)");
        assert_eq!(px(&pix, 60, 40), WHITE, "outside bbox");
    }

    #[test]
    fn inline_image_blits_quadrant_colors() {
        // 2x2 RGB hex image over the unit square [25,75]^2 (user): row 0
        // (red, green) lands on top in device space, row 1 (blue, white)
        // below.
        let content = "q 50 0 0 50 25 25 cm \
                       BI /W 2 /H 2 /CS /RGB /BPC 8 /F /AHx ID \
                       ff0000 00ff00 0000ff ffffff> EI Q";
        let pix = render(small_doc("", content.as_bytes(), |_| {}), 1.0);
        assert_eq!(px(&pix, 35, 35), RED, "top-left quadrant");
        assert_eq!(px(&pix, 65, 35), [0, 255, 0, 255], "top-right quadrant");
        assert_eq!(px(&pix, 35, 65), [0, 0, 255, 255], "bottom-left quadrant");
        assert_eq!(px(&pix, 65, 65), WHITE, "bottom-right quadrant");
        assert_eq!(px(&pix, 10, 50), WHITE, "outside image");
    }

    #[test]
    fn image_mask_stencils_fill_color() {
        // Rows: 0b01 (paint, skip) / 0b10 (skip, paint).
        let bytes = small_doc(
            "/XObject << /Im1 5 0 R >>",
            b"0 0 1 rg q 100 0 0 100 0 0 cm /Im1 Do Q",
            |b| {
                b.stream(
                    5,
                    "/Type /XObject /Subtype /Image /Width 2 /Height 2 \
                     /ImageMask true /BitsPerComponent 1",
                    &[0x40, 0x80],
                );
            },
        );
        let pix = render(bytes, 1.0);
        let blue = [0, 0, 255, 255];
        assert_eq!(px(&pix, 25, 25), blue, "row 0 sample 0 painted");
        assert_eq!(px(&pix, 75, 25), WHITE, "row 0 sample 1 clear");
        assert_eq!(px(&pix, 25, 75), WHITE, "row 1 sample 0 clear");
        assert_eq!(px(&pix, 75, 75), blue, "row 1 sample 1 painted");
    }

    #[test]
    fn image_mask_decode_inverts_stencil() {
        let bytes = small_doc(
            "/XObject << /Im1 5 0 R >>",
            b"0 0 1 rg q 100 0 0 100 0 0 cm /Im1 Do Q",
            |b| {
                b.stream(
                    5,
                    "/Type /XObject /Subtype /Image /Width 2 /Height 2 \
                     /ImageMask true /BitsPerComponent 1 /Decode [1 0]",
                    &[0x40, 0x80],
                );
            },
        );
        let pix = render(bytes, 1.0);
        let blue = [0, 0, 255, 255];
        assert_eq!(px(&pix, 25, 25), WHITE, "inverted: row 0 sample 0 clear");
        assert_eq!(px(&pix, 75, 25), blue, "inverted: row 0 sample 1 painted");
        assert_eq!(px(&pix, 25, 75), blue, "inverted: row 1 sample 0 painted");
        assert_eq!(px(&pix, 75, 75), WHITE, "inverted: row 1 sample 1 clear");
    }

    /// Wraps `raw` in a zlib stream (RFC 1950) carrying a single stored
    /// (uncompressed) deflate block (RFC 1951 §3.2.4) — genuine
    /// `/FlateDecode` input without a compressor in this crate.
    fn zlib_stored(raw: &[u8]) -> Vec<u8> {
        // CMF 0x78 (deflate, 32K window) with FLG 0x01: no preset dictionary
        // and (0x78 << 8) | 0x01 is the multiple of 31 the header check wants.
        let mut out = vec![0x78, 0x01];
        let len = raw.len() as u16;
        out.push(0x01); // BFINAL = 1, BTYPE = 00 (stored)
        out.extend_from_slice(&len.to_le_bytes());
        out.extend_from_slice(&(!len).to_le_bytes());
        out.extend_from_slice(raw);
        // Adler-32 of the uncompressed data, big-endian.
        let (mut low, mut high) = (1u32, 0u32);
        for &byte in raw {
            low = (low + u32::from(byte)) % 65521;
            high = (high + low) % 65521;
        }
        out.extend_from_slice(&((high << 16) | low).to_be_bytes());
        out
    }

    /// A one-page document whose only content is an 8x8 one-bit gray image
    /// XObject carrying `/Filter /<filter>`. `FlateDecode` gets genuinely
    /// encoded samples; any other name gets bytes that filter never reads.
    fn doc_with_image_filter(filter: &str) -> Vec<u8> {
        let samples = [0b1010_1010u8; 8];
        let data = if filter == "FlateDecode" {
            zlib_stored(&samples)
        } else {
            samples.to_vec()
        };
        small_doc(
            "/XObject << /Im0 5 0 R >>",
            b"q 100 0 0 100 0 0 cm /Im0 Do Q",
            |b| {
                b.stream(
                    5,
                    &format!(
                        "/Type /XObject /Subtype /Image /Width 8 /Height 8 \
                         /BitsPerComponent 1 /ColorSpace /DeviceGray /Filter /{filter}"
                    ),
                    &data,
                );
            },
        )
    }

    /// Renders page 0 of `bytes` with the default options, returning the
    /// pixmap and the report of everything the render had to drop.
    fn render_reporting(bytes: Vec<u8>) -> (Pixmap, RenderReport) {
        let doc = Document::load(bytes).expect("load");
        let page = doc.page(0).expect("page 0");
        render_page_reporting(&doc, &page, 1.0, &RenderOptions::default())
            .expect("render succeeds despite any dropped content")
    }

    /// The report's entries as `(kind, reason, count)` triples, the shape
    /// most of these assertions want to compare against.
    fn drops(report: &RenderReport) -> Vec<(SkippedKind, SkipReason, u64)> {
        report
            .skipped
            .iter()
            .map(|item| (item.kind, item.reason.clone(), item.count))
            .collect()
    }

    #[test]
    fn unsupported_image_filter_is_reported() {
        // The page's only content is `/Im0 Do`, where Im0 carries a filter
        // the core does not implement. The page must still render (lenient),
        // but the drop must be reported.
        let (pix, report) = render_reporting(doc_with_image_filter("JPXDecode"));

        assert!(pix.width > 0 && pix.height > 0, "page still rasterizes");
        assert_eq!(
            drops(&report),
            vec![(
                SkippedKind::Image,
                SkipReason::UnsupportedFilter("JPXDecode".to_string()),
                1,
            )],
        );
        assert!(!report.is_empty());
        assert_eq!(report.summary().as_deref(), Some("1 image skipped"));
        assert_eq!(
            report.warnings(),
            vec!["1 image skipped: unsupported filter /JPXDecode".to_string()],
        );
    }

    #[test]
    fn clean_page_reports_nothing() {
        let (pix, report) = render_reporting(doc_with_image_filter("FlateDecode"));
        // The 0b10101010 rows alternate white/black across the 8 columns the
        // image stretches over the 100pt page -- proof the image really
        // painted, so the empty report is not vacuous.
        assert_eq!(px(&pix, 6, 50), WHITE, "column 0 sample is white");
        assert_eq!(px(&pix, 18, 50), BLACK, "column 1 sample is black");
        assert!(report.is_empty(), "a decodable image reports no skips");
        assert_eq!(report.summary(), None);
        assert!(report.warnings().is_empty());
    }

    #[test]
    fn unsupported_inline_image_filter_is_reported() {
        let content = "q 100 0 0 100 0 0 cm BI /W 8 /H 8 /BPC 1 /CS /G \
                       /F /JPXDecode ID 01234567 EI Q";
        let (_, report) = render_reporting(small_doc("", content.as_bytes(), |_| {}));
        assert_eq!(
            drops(&report),
            vec![(
                SkippedKind::Image,
                SkipReason::UnsupportedFilter("JPXDecode".to_string()),
                1,
            )],
        );
    }

    #[test]
    fn image_that_decodes_but_cannot_be_interpreted_is_reported() {
        // Filters apply cleanly (there are none); `/Width 0` makes the
        // samples uninterpretable as an image.
        let bytes = small_doc(
            "/XObject << /Im0 5 0 R >>",
            b"q 100 0 0 100 0 0 cm /Im0 Do Q",
            |b| {
                b.stream(
                    5,
                    "/Type /XObject /Subtype /Image /Width 0 /Height 8 \
                     /BitsPerComponent 1 /ColorSpace /DeviceGray",
                    &[0; 8],
                );
            },
        );
        let (_, report) = render_reporting(bytes);
        assert_eq!(
            drops(&report),
            vec![(SkippedKind::Image, SkipReason::Undecodable, 1)],
        );
        assert_eq!(report.summary().as_deref(), Some("1 image skipped"));
    }

    #[test]
    fn a_repeated_drop_costs_one_entry_and_counts_up() {
        // Two draws of the same broken image are one entry with count 2 --
        // the property that keeps a page drawing a million of them from
        // growing the report a million times over.
        let content = "q 100 0 0 100 0 0 cm /Im0 Do /Im0 Do Q";
        let bytes = small_doc("/XObject << /Im0 5 0 R >>", content.as_bytes(), |b| {
            b.stream(
                5,
                "/Type /XObject /Subtype /Image /Width 8 /Height 8 \
                 /BitsPerComponent 1 /ColorSpace /DeviceGray /Filter /JPXDecode",
                &[0; 8],
            );
        });
        let (_, report) = render_reporting(bytes);
        assert_eq!(report.skipped.len(), 1, "one entry, not one per draw");
        assert_eq!(report.skipped[0].count, 2);
        assert_eq!(report.summary().as_deref(), Some("2 images skipped"));
    }

    #[test]
    fn nested_forms_repeating_a_broken_image_keep_the_report_small() {
        // Four levels of forms with a fanout of ten each draw the same
        // undecodable image, so `/Im0 Do` runs 10,000 times from a document
        // of a few hundred bytes. The report must stay one entry: an entry
        // per draw would let a page amplify a caller's memory use by the
        // fanout, on the plain `render_page` path that throws the report
        // away.
        const LEVELS: u32 = 4;
        const FANOUT: u32 = 10;
        let mut b = PdfBuilder::new();
        b.object(1, "<< /Type /Catalog /Pages 2 0 R >>");
        b.object(2, "<< /Type /Pages /Kids [3 0 R] /Count 1 >>");
        b.object(
            3,
            "<< /Type /Page /Parent 2 0 R /MediaBox [0 0 100 100] \
             /Resources << /XObject << /F0 10 0 R >> >> /Contents 4 0 R >>",
        );
        b.stream(4, "", b"/F0 Do");
        b.stream(
            5,
            "/Type /XObject /Subtype /Image /Width 8 /Height 8 \
             /BitsPerComponent 1 /ColorSpace /DeviceGray /Filter /JPXDecode",
            &[0; 8],
        );
        for level in 0..LEVELS {
            let (child, child_obj) = if level + 1 < LEVELS {
                (format!("F{}", level + 1), 11 + level)
            } else {
                ("Im0".to_string(), 5)
            };
            let content = format!("/{child} Do ").repeat(FANOUT as usize);
            b.stream(
                10 + level,
                &format!(
                    "/Type /XObject /Subtype /Form /BBox [0 0 100 100] \
                     /Resources << /XObject << /{child} {child_obj} 0 R >> >>"
                ),
                content.as_bytes(),
            );
        }
        let (_, report) = render_reporting(b.build(1));
        assert_eq!(report.skipped.len(), 1, "one entry for 10,000 draws");
        assert_eq!(report.skipped[0].count, u64::from(FANOUT.pow(LEVELS)));
        assert_eq!(report.unlisted, 0);
    }

    #[test]
    fn distinct_drops_stop_at_the_report_cap() {
        // 70 inline images, each naming a different unsupported filter, so
        // every drop is a distinct entry. The list stops at 64 and the rest
        // are counted -- an unbounded `Vec` would have taken all 70.
        let mut content = String::new();
        for i in 0..70 {
            content.push_str(&format!(
                "BI /W 8 /H 8 /BPC 1 /CS /G /F /Bogus{i}Decode ID 01234567 EI\n"
            ));
        }
        let (_, report) = render_reporting(small_doc("", content.as_bytes(), |_| {}));
        assert_eq!(report.skipped.len(), 64, "entry list is capped");
        assert_eq!(report.unlisted, 6, "the rest are counted, not described");
        assert!(report
            .warnings()
            .last()
            .expect("a warning per entry plus the overflow line")
            .starts_with("6 further drops"));
    }

    #[test]
    fn undecodable_page_contents_are_reported() {
        // The page's own `/Contents` names a filter the core cannot run:
        // the page renders blank, which must not look like a clean render.
        let mut b = PdfBuilder::new();
        b.object(1, "<< /Type /Catalog /Pages 2 0 R >>");
        b.object(2, "<< /Type /Pages /Kids [3 0 R] /Count 1 >>");
        b.object(
            3,
            "<< /Type /Page /Parent 2 0 R /MediaBox [0 0 100 100] /Contents 4 0 R >>",
        );
        b.stream(4, "/Filter /JPXDecode", b"0 0 100 100 re f");
        let (pix, report) = render_reporting(b.build(1));
        assert_eq!(px(&pix, 50, 50), WHITE, "nothing painted");
        assert_eq!(
            drops(&report),
            vec![(
                SkippedKind::PageContents,
                SkipReason::UnsupportedFilter("JPXDecode".to_string()),
                1,
            )],
        );
        assert_eq!(
            report.summary().as_deref(),
            Some("1 content stream skipped")
        );
    }

    #[test]
    fn undecodable_form_xobject_is_reported() {
        // The form's content -- and everything it would have drawn -- is
        // dropped whole, one level below where an image drop is caught.
        let bytes = small_doc("/XObject << /Fm0 5 0 R >>", b"/Fm0 Do", |b| {
            b.stream(
                5,
                "/Type /XObject /Subtype /Form /BBox [0 0 100 100] /Filter /JPXDecode",
                b"0 0 100 100 re f",
            );
        });
        let (pix, report) = render_reporting(bytes);
        assert_eq!(px(&pix, 50, 50), WHITE, "the form painted nothing");
        assert_eq!(
            drops(&report),
            vec![(
                SkippedKind::Form,
                SkipReason::UnsupportedFilter("JPXDecode".to_string()),
                1,
            )],
        );
    }

    #[test]
    fn unresolvable_and_untyped_xobjects_are_reported() {
        // `/Im0` is not in the resource dictionary at all; `/X1` is a stream
        // with no `/Subtype`, so nothing knows how to draw it.
        let bytes = small_doc("/XObject << /X1 5 0 R >>", b"/Im0 Do /X1 Do", |b| {
            b.stream(5, "/Width 8 /Height 8", &[0; 8]);
        });
        let (_, report) = render_reporting(bytes);
        assert_eq!(
            drops(&report),
            vec![
                (SkippedKind::XObject, SkipReason::Missing, 1),
                (SkippedKind::XObject, SkipReason::Unsupported, 1),
            ],
        );
    }

    #[test]
    fn jpx_image_is_reported_instead_of_painted_as_noise() {
        // Nothing here decodes a JPEG 2000 codestream, so the filter chain
        // refuses to hand one over as if it were stream data (ISO 32000-1
        // 7.4.9). Were it passed through, the 0x42 bytes below would paint
        // as gray samples and the render would claim success; instead the
        // image is dropped and named in the report.
        let bytes = small_doc(
            "/XObject << /Im0 5 0 R >>",
            b"q 100 0 0 100 0 0 cm /Im0 Do Q",
            |b| {
                b.stream(
                    5,
                    "/Type /XObject /Subtype /Image /Width 8 /Height 8 \
                     /BitsPerComponent 8 /ColorSpace /DeviceRGB /Filter /JPXDecode",
                    &[0x42; 192],
                );
            },
        );
        let (pix, report) = render_reporting(bytes);
        assert_eq!(px(&pix, 50, 50), WHITE, "no noise painted");
        assert_eq!(
            drops(&report),
            vec![(
                SkippedKind::Image,
                SkipReason::UnsupportedFilter("JPXDecode".to_string()),
                1,
            )],
        );
        assert_eq!(
            report.warnings(),
            vec!["1 image skipped: unsupported filter /JPXDecode".to_string()],
            "the caller can name what went missing",
        );
    }

    #[test]
    fn image_with_too_few_samples_is_reported() {
        // 8x8 at 8 bits gray needs 64 bytes; 4 are supplied, so 60 pixels
        // come from zero padding rather than from the image.
        let bytes = small_doc(
            "/XObject << /Im0 5 0 R >>",
            b"q 100 0 0 100 0 0 cm /Im0 Do Q",
            |b| {
                b.stream(
                    5,
                    "/Type /XObject /Subtype /Image /Width 8 /Height 8 \
                     /BitsPerComponent 8 /ColorSpace /DeviceGray",
                    &[0xFF; 4],
                );
            },
        );
        let (pix, report) = render_reporting(bytes);
        assert_eq!(px(&pix, 6, 6), [255, 255, 255, 255], "real sample painted");
        assert_eq!(px(&pix, 50, 50), BLACK, "padding painted black");
        assert_eq!(
            drops(&report),
            vec![(SkippedKind::Image, SkipReason::Truncated, 1)],
        );
    }

    #[test]
    fn indexed_image_with_undecodable_palette_is_reported() {
        // The palette stream will not decode, so the space has no colors at
        // all and every sample paints black -- a plausible-looking image
        // that is not the page's image.
        let bytes = small_doc(
            "/XObject << /Im0 5 0 R >>",
            b"q 100 0 0 100 0 0 cm /Im0 Do Q",
            |b| {
                b.stream(
                    5,
                    "/Type /XObject /Subtype /Image /Width 8 /Height 8 \
                     /BitsPerComponent 8 /ColorSpace [/Indexed /DeviceRGB 255 6 0 R]",
                    &[0; 64],
                );
                b.stream(6, "/Filter /JPXDecode", &[0; 12]);
            },
        );
        let (_, report) = render_reporting(bytes);
        assert_eq!(
            drops(&report),
            vec![(
                SkippedKind::Image,
                SkipReason::UnsupportedFilter("JPXDecode".to_string()),
                1,
            )],
        );
    }

    #[test]
    fn shading_operator_is_reported() {
        let (pix, report) = render_reporting(small_doc("", b"q /Sh0 sh Q", |_| {}));
        assert_eq!(px(&pix, 50, 50), WHITE, "shadings paint nothing");
        assert_eq!(
            drops(&report),
            vec![(SkippedKind::Shading, SkipReason::Unsupported, 1)],
        );
    }

    #[test]
    fn pattern_fill_is_reported_as_an_approximation() {
        let content = b"/Pattern cs /P0 scn 0 0 100 100 re f";
        let (pix, report) = render_reporting(small_doc("", content, |_| {}));
        assert_eq!(px(&pix, 50, 50), [128, 128, 128, 255], "stand-in gray");
        assert_eq!(
            drops(&report),
            vec![(SkippedKind::Pattern, SkipReason::Unsupported, 1)],
        );
    }

    #[test]
    fn ignored_soft_mask_and_blend_mode_are_reported() {
        let resources = "/ExtGState << /GS0 << /SMask << /S /Luminosity /G 5 0 R >> \
                         /BM /Multiply >> >>";
        let bytes = small_doc(resources, b"/GS0 gs 0 0 100 100 re f", |b| {
            b.stream(5, "/Type /XObject /Subtype /Form /BBox [0 0 8 8]", b"");
        });
        let (_, report) = render_reporting(bytes);
        assert_eq!(
            drops(&report),
            vec![
                (SkippedKind::SoftMask, SkipReason::Unsupported, 1),
                (SkippedKind::BlendMode, SkipReason::Unsupported, 1),
            ],
        );
    }

    #[test]
    fn image_soft_mask_is_reported() {
        let bytes = small_doc(
            "/XObject << /Im0 5 0 R >>",
            b"q 100 0 0 100 0 0 cm /Im0 Do Q",
            |b| {
                b.stream(
                    5,
                    "/Type /XObject /Subtype /Image /Width 8 /Height 8 \
                     /BitsPerComponent 8 /ColorSpace /DeviceGray /SMask 6 0 R",
                    &[0xFF; 64],
                );
                b.stream(
                    6,
                    "/Type /XObject /Subtype /Image /Width 8 /Height 8 \
                     /BitsPerComponent 8 /ColorSpace /DeviceGray",
                    &[0; 64],
                );
            },
        );
        let (pix, report) = render_reporting(bytes);
        assert_eq!(
            px(&pix, 50, 50),
            WHITE,
            "fully masked content painted anyway"
        );
        assert_eq!(
            drops(&report),
            vec![(SkippedKind::SoftMask, SkipReason::Unsupported, 1)],
        );
    }

    #[test]
    fn unpainted_annotation_appearance_is_reported() {
        // One annotation with an appearance stream (never painted), one
        // hidden (invisible either way) and one with no `/AP` at all.
        let mut b = PdfBuilder::new();
        b.object(1, "<< /Type /Catalog /Pages 2 0 R >>");
        b.object(2, "<< /Type /Pages /Kids [3 0 R] /Count 1 >>");
        b.object(
            3,
            "<< /Type /Page /Parent 2 0 R /MediaBox [0 0 100 100] /Contents 4 0 R \
             /Annots [5 0 R 6 0 R 7 0 R] >>",
        );
        b.stream(4, "", b"");
        b.object(
            5,
            "<< /Type /Annot /Subtype /Stamp /Rect [0 0 10 10] /AP << /N 8 0 R >> >>",
        );
        b.object(
            6,
            "<< /Type /Annot /Subtype /Stamp /Rect [0 0 10 10] /F 2 /AP << /N 8 0 R >> >>",
        );
        b.object(7, "<< /Type /Annot /Subtype /Link /Rect [0 0 10 10] >>");
        b.stream(8, "/Type /XObject /Subtype /Form /BBox [0 0 10 10]", b"");
        let (_, report) = render_reporting(b.build(1));
        assert_eq!(
            drops(&report),
            vec![(SkippedKind::Annotation, SkipReason::Unsupported, 1)],
        );
    }

    #[test]
    fn rotate_90_swaps_dimensions_and_spins_content() {
        let mut b = PdfBuilder::new();
        b.object(1, "<< /Type /Catalog /Pages 2 0 R >>");
        b.object(2, "<< /Type /Pages /Kids [3 0 R] /Count 1 >>");
        b.object(
            3,
            "<< /Type /Page /Parent 2 0 R /MediaBox [0 0 100 200] \
             /Rotate 90 /Contents 4 0 R >>",
        );
        b.stream(4, "", b"1 0 0 rg 0 0 10 10 re f");
        let pix = render(b.build(1), 1.0);
        assert_eq!((pix.width, pix.height), (200, 100));
        // The page's bottom-left corner rect appears top-left after the
        // clockwise rotation.
        assert_eq!(px(&pix, 5, 5), RED, "rotated corner");
        assert_eq!(px(&pix, 5, 94), WHITE, "old corner clear");
        assert_eq!(px(&pix, 194, 94), WHITE);
    }

    #[test]
    fn scale_doubles_pixel_size_and_coordinates() {
        let content = "1 0 0 rg 10 10 20 20 re f";
        let pix = render(small_doc("", content.as_bytes(), |_| {}), 2.0);
        assert_eq!((pix.width, pix.height), (200, 200));
        // User rect [10,30]^2 -> device [20,60]x[140,180] at 2x.
        assert_eq!(px(&pix, 40, 160), RED, "scaled interior");
        assert_eq!(px(&pix, 40, 120), WHITE, "above scaled rect");
        assert_eq!(px(&pix, 80, 160), WHITE, "right of scaled rect");
    }

    fn fixture(name: &str) -> std::path::PathBuf {
        std::path::Path::new(env!("CARGO_MANIFEST_DIR"))
            .join("../../tests/fixtures")
            .join(name)
    }

    #[test]
    fn shapes_fixture_renders_expected_colors() {
        let doc = Document::open(fixture("shapes.pdf")).expect("open");
        let page = doc.page(0).expect("page");
        let pix =
            render_page_with_options(&doc, &page, 1.0, &RenderOptions::default()).expect("render");
        assert_eq!((pix.width, pix.height), (612, 792));
        assert!(
            pix.data.chunks_exact(4).any(|p| p[0] != 255 || p[1] != 255),
            "page must contain non-white pixels"
        );
        // 1 0 0 rg 72 600 100 80 re -> device rows [112,192].
        assert_eq!(px(&pix, 100, 150), RED, "red rect");
        // 0 0.5 1 rg 200 600 120 60 re -> device rows [132,192].
        let [r, g, b, _] = px(&pix, 250, 150);
        assert_eq!((r, b), (0, 255), "blue-ish rect r/b");
        assert!((127..=129).contains(&g), "blue-ish rect g {g}");
        // 0.2 0.8 0.2 rg 340 590 90 90 re -> device rows [112,202].
        assert_eq!(px(&pix, 380, 150), [51, 204, 51, 255], "green rect");
        // q 0.5 0 0 0.5 300 100 cm 0.8 0 0.8 rg 0 0 200 200 re f Q ->
        // user [300,400]x[100,200] -> device rows [592,692].
        assert_eq!(px(&pix, 350, 650), [204, 0, 204, 255], "magenta rect");
        // Black 2pt Bezier stroke passes (200, 417) in device space.
        let dark = (410..425).any(|y| px(&pix, 200, y)[0] < 128);
        assert!(dark, "stroked curve missing");
        // Unpainted margin stays white.
        assert_eq!(px(&pix, 550, 750), WHITE);
    }

    #[test]
    fn hello_fixture_renders_all_white_without_error() {
        // Text is tracked but not painted in v0.1, so the page stays white.
        let doc = Document::open(fixture("hello.pdf")).expect("open");
        let page = doc.page(0).expect("page");
        let pix =
            render_page_with_options(&doc, &page, 1.0, &RenderOptions::default()).expect("render");
        assert_eq!((pix.width, pix.height), (612, 792));
        assert!(pix.data.iter().all(|&b| b == 255), "expected a white page");
    }

    #[test]
    fn even_odd_fill_and_close_fill_stroke() {
        // f* with two same-winding squares leaves an even-odd hole.
        let content = "1 0 0 rg 10 10 80 80 re 30 30 40 40 re f*";
        let pix = render(small_doc("", content.as_bytes(), |_| {}), 1.0);
        assert_eq!(px(&pix, 50, 50), WHITE, "even-odd hole");
        assert_eq!(px(&pix, 15, 50), RED, "ring");

        // b closes the open triangle, fills it, and strokes the closing
        // edge from (80,10) back to (20,10) -> device row ~90.
        let content = "1 0 0 rg 0 0 0 RG 2 w 20 10 m 80 10 l 50 60 l b";
        let pix = render(small_doc("", content.as_bytes(), |_| {}), 1.0);
        assert_eq!(px(&pix, 50, 70), RED, "triangle interior filled");
        assert!(px(&pix, 50, 90)[0] < 128, "closing edge stroked");
    }

    // --- Type3 glyph painting (re-entering the executor per CharProc) --------
    //
    // Geometry matches the shared box-glyph tests: a 200x200 page, 100pt font,
    // text origin (20,50), CharProc `100 0 500 700 re f` (the (100,0)-(600,700)
    // box in glyph space) under `/FontMatrix [0.001 ...]`. That lands the same
    // interior dark pixel at (55,115); an 800-glyph-unit advance puts a second
    // glyph's interior at (135,115).

    /// Renders page 0 of `bytes` at the given glyph-painting tier.
    fn render_at_tier(bytes: &[u8], tier: GlyphPainting) -> Pixmap {
        let doc = Document::load(bytes.to_vec()).expect("load");
        let page = doc.page(0).expect("page");
        let opts = RenderOptions {
            glyph_painting: tier,
            ..Default::default()
        };
        render_page_with_options(&doc, &page, 1.0, &opts).expect("render")
    }

    /// True iff the pixel at `(x, y)` is dark on all three channels.
    fn dark_at(pix: &Pixmap, x: u32, y: u32) -> bool {
        let o = ((y * pix.width + x) * 4) as usize;
        pix.data[o] < 128 && pix.data[o + 1] < 128 && pix.data[o + 2] < 128
    }

    /// Builds a one-page 200x200 doc showing a `/Type3` font (object 5) whose
    /// `/boxglyph` CharProc (object 6) is `charproc`. `font_extra` is spliced
    /// into the font dict (e.g. `/FirstChar`+`/Widths`); `char_res` optionally
    /// gives the CharProc stream its own `/Resources` (for self-reference).
    /// Code 65 maps to `/boxglyph` via `/Differences`.
    fn type3_doc(
        charproc: &str,
        font_extra: &str,
        char_res: Option<&str>,
        content: &[u8],
    ) -> Vec<u8> {
        let mut b = PdfBuilder::new().version(1, 5);
        b.object(1, "<< /Type /Catalog /Pages 2 0 R >>");
        b.object(2, "<< /Type /Pages /Kids [3 0 R] /Count 1 >>");
        b.object(
            3,
            "<< /Type /Page /Parent 2 0 R /MediaBox [0 0 200 200] \
             /Resources << /Font << /F0 5 0 R >> >> /Contents 4 0 R >>",
        );
        b.stream(4, "", content);
        b.object(
            5,
            &format!(
                "<< /Type /Font /Subtype /Type3 /FontBBox [0 0 1000 1000] \
                 /FontMatrix [0.001 0 0 0.001 0 0] \
                 /Encoding << /Differences [65 /boxglyph] >> \
                 /CharProcs << /boxglyph 6 0 R >> {font_extra} >>"
            ),
        );
        b.stream(6, char_res.unwrap_or(""), charproc.as_bytes());
        b.build(1)
    }

    /// A Type3 fixture whose `charproc` paints under `/FirstChar 65 /Widths
    /// [1000]`.
    fn type3_page_doc(charproc: &str, content: &[u8]) -> Vec<u8> {
        type3_doc(charproc, "/FirstChar 65 /Widths [1000]", None, content)
    }

    /// A Type3 fixture painting the standard box glyph with the given
    /// glyph-space `/Widths` entry for code 65.
    fn type3_page_doc_widths(width: i32, content: &[u8]) -> Vec<u8> {
        type3_doc(
            "1000 0 d0 100 0 500 700 re f",
            &format!("/FirstChar 65 /Widths [{width}]"),
            None,
            content,
        )
    }

    /// A Type3 fixture whose CharProc paints the box AND shows code 65 in the
    /// same font (via its own `/Resources /F0` pointing back at the font) --
    /// self-referential, so it must be depth-bounded.
    fn type3_recursive_doc() -> Vec<u8> {
        type3_doc(
            "1000 0 d0 100 0 500 700 re f BT /F0 100 Tf <41> Tj ET",
            "/FirstChar 65 /Widths [1000]",
            Some("/Resources << /Font << /F0 5 0 R >> >>"),
            b"BT /F0 100 Tf 20 50 Td <41> Tj ET",
        )
    }

    #[test]
    fn type3_glyph_paints_at_all_embedded_not_embedded_truetype_only() {
        let doc = type3_page_doc(
            "1000 0 d0 100 0 500 700 re f",
            b"BT /F0 100 Tf 20 50 Td <41> Tj ET", // code 65 -> /boxglyph
        );
        for tier in [GlyphPainting::AllEmbedded, GlyphPainting::Full] {
            let pix = render_at_tier(&doc, tier);
            assert!(
                dark_at(&pix, 55, 115),
                "Type3 glyph should paint at {tier:?}"
            );
        }
        let pix = render_at_tier(&doc, GlyphPainting::EmbeddedTrueTypeOnly);
        assert!(
            !dark_at(&pix, 55, 115),
            "Type3 must not paint at EmbeddedTrueTypeOnly"
        );
    }

    #[test]
    fn type3_self_referential_glyph_terminates() {
        let doc = type3_recursive_doc();
        let started = std::time::Instant::now();
        let pix = render_at_tier(&doc, GlyphPainting::AllEmbedded);
        assert!(
            started.elapsed() < std::time::Duration::from_secs(5),
            "self-referential Type3 must be depth-bounded, not hang/overflow"
        );
        assert!(dark_at(&pix, 55, 115), "the box still paints");
    }

    #[test]
    fn type3_width_governs_second_glyph_origin() {
        let doc = type3_page_doc_widths(800, b"BT /F0 100 Tf 20 50 Td <4141> Tj ET");
        let pix = render_at_tier(&doc, GlyphPainting::AllEmbedded);
        assert!(dark_at(&pix, 55, 115), "first glyph at (55,115)");
        assert!(
            dark_at(&pix, 135, 115),
            "second glyph at the /Widths-implied (135,115)"
        );
    }

    #[test]
    fn type3_d1_glyph_ignores_its_own_color_and_uses_text_fill() {
        // Page sets fill RED before the text; the d1 CharProc tries to set blue.
        // d1 is uncolored: the box must paint RED.
        let doc = type3_page_doc(
            "1000 0 0 0 1000 1000 d1 0 0 1 rg 100 0 500 700 re f",
            b"1 0 0 rg BT /F0 100 Tf 20 50 Td <41> Tj ET",
        );
        let pix = render_at_tier(&doc, GlyphPainting::AllEmbedded);
        let [r, g, b, _] = px(&pix, 55, 115);
        assert!(
            r > 200 && g < 60 && b < 60,
            "d1 glyph paints in the text fill (red), got {r},{g},{b}"
        );
    }

    #[test]
    fn type3_d0_glyph_honors_its_own_color() {
        // d0 is colored: the CharProc's blue takes effect despite red text fill.
        let doc = type3_page_doc(
            "1000 0 d0 0 0 1 rg 100 0 500 700 re f",
            b"1 0 0 rg BT /F0 100 Tf 20 50 Td <41> Tj ET",
        );
        let pix = render_at_tier(&doc, GlyphPainting::AllEmbedded);
        let [r, g, b, _] = px(&pix, 55, 115);
        assert!(
            b > 200 && r < 60 && g < 60,
            "d0 glyph paints its own color (blue), got {r},{g},{b}"
        );
    }

    #[test]
    fn type3_d0_nested_in_d1_regains_color() {
        // ISO 32000-1 9.6.5.2: a `d1` (uncolored) CharProc must not apply its
        // own color -- it paints in the inherited text fill (red here). But
        // that lock must not leak into a `d0` (colored) CharProc shown *from
        // inside* the `d1` glyph (a Type3 font showing itself, ISO 32000-1
        // 9.6.5): the nested `d0` must regain full color control and paint
        // its own color (blue), because the lock is saved/restored per
        // CharProc frame and set to `is_d1`, not hardcoded on.
        //
        // Geometry: FontMatrix [0.001 0 0 0.001 0 0], 100pt /Tf, page
        // 200x200 -- the shared box-glyph setup used throughout this module.
        // The outer `d1` box "100 0 500 700 re f" lands at device (55,115),
        // same as the other d0/d1 tests above. Its content then shows the
        // nested `d0` glyph via its own BT/Tf/Td/Tj at glyph-space offset
        // (800, 0); working through the nested glyph matrix, that glyph's
        // (deliberately larger, to stay easily samplable) box
        // "1000 0 2000 3000 re f" lands at device x in [110,130], y in
        // [120,150] -- disjoint in x from the outer box's [30,80], so the
        // two boxes cannot overlap on the device.
        let mut b = PdfBuilder::new().version(1, 5);
        b.object(1, "<< /Type /Catalog /Pages 2 0 R >>");
        b.object(2, "<< /Type /Pages /Kids [3 0 R] /Count 1 >>");
        b.object(
            3,
            "<< /Type /Page /Parent 2 0 R /MediaBox [0 0 200 200] \
             /Resources << /Font << /F0 5 0 R >> >> /Contents 4 0 R >>",
        );
        // Red text fill, then show code 65 -> the outer `d1` glyph.
        b.stream(4, "", b"1 0 0 rg BT /F0 100 Tf 20 50 Td <41> Tj ET");
        b.object(
            5,
            "<< /Type /Font /Subtype /Type3 /FontBBox [0 0 1000 1000] \
             /FontMatrix [0.001 0 0 0.001 0 0] \
             /Encoding << /Differences [65 /d1glyph 66 /d0glyph] >> \
             /CharProcs << /d1glyph 6 0 R /d0glyph 7 0 R >> \
             /FirstChar 65 /Widths [1000 1000] >>",
        );
        // d1 (uncolored): tries blue on its own box (must be suppressed and
        // paint red instead), then shows the nested d0 glyph (code 66),
        // which must regain color control for its own subtree.
        b.stream(
            6,
            "",
            b"1000 0 0 0 1000 1000 d1 0 0 1 rg 100 0 500 700 re f \
              BT /F0 100 Tf 800 0 Td <42> Tj ET",
        );
        // d0 (colored): paints its own blue, at a glyph-space box that maps
        // to a device location disjoint from the outer one.
        b.stream(7, "", b"1000 0 d0 0 0 1 rg 1000 0 2000 3000 re f");
        let pix = render_at_tier(&b.build(1), GlyphPainting::AllEmbedded);

        let [r, g, bch, _] = px(&pix, 55, 115);
        assert!(
            r > 200 && g < 60 && bch < 60,
            "outer d1 box must paint the inherited text fill (red), got {r},{g},{bch}"
        );
        let [r, g, bch, _] = px(&pix, 120, 135);
        assert!(
            bch > 200 && r < 60 && g < 60,
            "nested d0 box must regain its own color (blue), got {r},{g},{bch}"
        );
    }

    // --- Task 3 review-fix: substitution scoped to simple fonts only --------
    //
    // `GlyphFont::load` used to run `Full`-tier substitution unconditionally
    // once every embedded loader had declined, regardless of `/Subtype`. That
    // let a `/Type3` font (whose `FaceRequest::from_font_dict` resolves fine
    // -- nothing there checks `/Subtype`) reach `load_substitute`, so at
    // `Full` + a provider, `ts.font` came back `Some` and `Executor::run`'s
    // `ts.type3 = if ts.font.is_some() { None } else { ... }` never resolved
    // the Type3 font at all -- the CharProcs were silently replaced by a
    // substitute glyph. The fix chains `substitute_at_full` only onto the
    // `TrueType`/`Type1`/`MMType1` arms of `GlyphFont::load`'s match, leaving
    // `Type0` and the `Type3`/unknown `_` catch-all substitution-free.

    /// Writes `bytes` to `basename` inside a freshly created temp directory,
    /// ready to hand to `SubstituteSource::Dir`/`DirProvider` (mirrors
    /// `glyph::tests::write_temp_face`).
    fn write_temp_face(tag: &str, basename: &str, bytes: &[u8]) -> std::path::PathBuf {
        let dir = std::env::temp_dir().join(format!(
            "pdfboss-executor-{tag}-test-{}-{}",
            std::process::id(),
            std::time::SystemTime::now()
                .duration_since(std::time::UNIX_EPOCH)
                .map(|d| d.as_nanos())
                .unwrap_or(0)
        ));
        std::fs::create_dir_all(&dir).expect("create temp dir");
        std::fs::write(dir.join(basename), bytes).expect("write fixture face");
        dir
    }

    #[test]
    fn type3_at_full_with_provider_still_paints_via_charprocs() {
        // The critical guard: code 0x80 is deliberately NOT 'A' (0x41) -- the
        // only code point `truetype::tests::build_font` (used here as the
        // SUBSTITUTE face) maps to a paintable glyph. If substitution ever
        // wrongly fired for this Type3 font, gid 0 (.notdef) would leave the
        // page blank; only the real Type3 CharProc path paints the box.
        let mut b = PdfBuilder::new().version(1, 5);
        b.object(1, "<< /Type /Catalog /Pages 2 0 R >>");
        b.object(2, "<< /Type /Pages /Kids [3 0 R] /Count 1 >>");
        b.object(
            3,
            "<< /Type /Page /Parent 2 0 R /MediaBox [0 0 200 200] \
             /Resources << /Font << /F0 5 0 R >> >> /Contents 4 0 R >>",
        );
        b.stream(4, "", b"BT /F0 100 Tf 20 50 Td <80> Tj ET");
        b.object(
            5,
            "<< /Type /Font /Subtype /Type3 /FontBBox [0 0 1000 1000] \
             /FontMatrix [0.001 0 0 0.001 0 0] \
             /Encoding << /Differences [128 /boxglyph] >> \
             /CharProcs << /boxglyph 6 0 R >> /FirstChar 128 /Widths [1000] >>",
        );
        b.stream(6, "", b"1000 0 d0 100 0 500 700 re f");
        let bytes = b.build(1);

        let dir = write_temp_face(
            "type3-substitute",
            "Arimo[wght].ttf",
            &crate::truetype::tests::build_font(),
        );

        let doc = Document::load(bytes).expect("load");
        let page = doc.page(0).expect("page");
        let opts = RenderOptions {
            glyph_painting: GlyphPainting::Full,
            substitutes: SubstituteSource::Dir(dir.clone()),
        };
        let pix = render_page_with_options(&doc, &page, 1.0, &opts).expect("render");
        assert!(
            dark_at(&pix, 55, 115),
            "Type3 CharProc box must still paint at Full+provider, not be \
             clobbered by wrongly-fired substitution"
        );

        std::fs::remove_dir_all(&dir).ok();
    }

    #[test]
    fn non_embedded_type0_at_full_with_provider_stays_blank() {
        // The important guard: a /Type0 font with no embedded FontFile* at
        // all must never reach substitution -- `load_substitute` builds a
        // 1-byte-per-code table, but Type0 codes under Identity-H are two
        // bytes wide, so if substitution ever fired here, <0041> would
        // mis-split into codes 0x00 and 0x41 (the latter resolving, via
        // StandardEncoding and the substitute's cmap, to the paintable box
        // glyph) and paint stray ink instead of staying blank.
        let mut b = PdfBuilder::new().version(1, 5);
        b.object(1, "<< /Type /Catalog /Pages 2 0 R >>");
        b.object(2, "<< /Type /Pages /Kids [3 0 R] /Count 1 >>");
        b.object(
            3,
            "<< /Type /Page /Parent 2 0 R /MediaBox [0 0 200 200] \
             /Resources << /Font << /F0 5 0 R >> >> /Contents 4 0 R >>",
        );
        b.stream(4, "", b"BT /F0 100 Tf 20 50 Td <0041> Tj ET");
        b.object(
            5,
            "<< /Type /Font /Subtype /Type0 /BaseFont /Helvetica \
             /Encoding /Identity-H /DescendantFonts [6 0 R] >>",
        );
        b.object(
            6,
            "<< /Type /Font /Subtype /CIDFontType2 /BaseFont /Helvetica >>",
        );
        let bytes = b.build(1);

        let dir = write_temp_face(
            "type0-substitute",
            "Arimo[wght].ttf",
            &crate::truetype::tests::build_font(),
        );

        let doc = Document::load(bytes).expect("load");
        let page = doc.page(0).expect("page");
        let opts = RenderOptions {
            glyph_painting: GlyphPainting::Full,
            substitutes: SubstituteSource::Dir(dir.clone()),
        };
        let pix = render_page_with_options(&doc, &page, 1.0, &opts).expect("render");
        assert!(
            !dark_at(&pix, 55, 115),
            "non-embedded Type0 must not be substituted into mis-split garbage"
        );

        std::fs::remove_dir_all(&dir).ok();
    }
}