stet-pdf-reader 0.7.0

PDF parser and renderer
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
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325
4326
4327
4328
4329
4330
4331
4332
4333
4334
4335
4336
4337
4338
4339
4340
4341
4342
4343
4344
4345
4346
4347
4348
4349
4350
4351
4352
4353
4354
4355
4356
4357
4358
4359
4360
4361
4362
4363
4364
4365
4366
4367
4368
4369
4370
4371
4372
4373
4374
4375
4376
4377
4378
4379
4380
4381
4382
4383
4384
4385
4386
4387
4388
4389
4390
4391
4392
4393
4394
4395
4396
4397
4398
4399
4400
4401
4402
4403
4404
4405
4406
4407
4408
4409
4410
4411
4412
4413
4414
4415
4416
4417
4418
4419
4420
4421
4422
4423
4424
4425
4426
4427
4428
4429
4430
4431
4432
4433
4434
4435
4436
4437
4438
4439
4440
4441
4442
4443
4444
4445
4446
4447
4448
4449
4450
4451
4452
4453
4454
4455
4456
4457
4458
4459
4460
4461
4462
4463
4464
4465
4466
4467
4468
4469
4470
4471
4472
4473
4474
4475
4476
4477
4478
4479
4480
4481
4482
4483
4484
4485
4486
4487
4488
4489
4490
4491
4492
4493
4494
4495
4496
4497
4498
4499
4500
4501
4502
4503
4504
4505
4506
4507
4508
4509
4510
4511
4512
4513
4514
4515
4516
4517
4518
4519
4520
4521
4522
4523
4524
4525
4526
4527
4528
4529
4530
4531
4532
4533
4534
4535
4536
4537
4538
4539
4540
4541
4542
4543
4544
4545
4546
4547
4548
4549
4550
4551
4552
4553
4554
4555
4556
4557
4558
4559
4560
4561
4562
4563
4564
4565
4566
4567
4568
4569
4570
4571
4572
4573
4574
4575
4576
4577
4578
4579
4580
4581
4582
4583
4584
4585
4586
4587
4588
4589
4590
4591
4592
4593
4594
4595
4596
4597
4598
4599
4600
4601
4602
4603
4604
4605
4606
4607
4608
4609
4610
4611
4612
4613
4614
4615
4616
4617
4618
4619
4620
4621
4622
4623
4624
4625
4626
4627
4628
4629
4630
4631
4632
4633
4634
4635
4636
4637
4638
4639
4640
4641
4642
4643
4644
4645
4646
4647
4648
4649
4650
4651
4652
4653
4654
4655
4656
4657
4658
4659
4660
4661
4662
4663
4664
4665
4666
4667
4668
4669
4670
4671
4672
4673
4674
4675
4676
4677
4678
4679
4680
4681
4682
4683
4684
4685
4686
4687
4688
4689
4690
4691
4692
4693
4694
4695
4696
4697
4698
4699
4700
4701
4702
4703
4704
4705
4706
4707
4708
4709
4710
4711
4712
4713
4714
4715
4716
4717
4718
4719
4720
4721
4722
4723
4724
4725
4726
4727
4728
4729
4730
4731
4732
4733
4734
4735
4736
4737
4738
4739
4740
4741
4742
4743
4744
4745
4746
4747
4748
4749
4750
4751
4752
4753
4754
4755
4756
4757
4758
4759
4760
4761
4762
4763
4764
4765
4766
4767
4768
4769
4770
4771
4772
4773
4774
4775
4776
4777
4778
4779
4780
4781
4782
4783
4784
4785
4786
4787
4788
4789
4790
4791
4792
4793
4794
4795
4796
4797
4798
4799
4800
4801
4802
4803
4804
4805
4806
4807
4808
4809
4810
4811
4812
4813
4814
4815
4816
4817
4818
4819
4820
4821
4822
4823
4824
4825
4826
4827
4828
4829
4830
4831
4832
4833
4834
4835
4836
4837
4838
4839
4840
4841
4842
4843
4844
4845
4846
4847
4848
4849
4850
4851
4852
4853
4854
4855
4856
4857
4858
4859
4860
4861
4862
4863
4864
4865
4866
4867
4868
4869
4870
4871
4872
4873
4874
4875
4876
4877
4878
4879
4880
4881
4882
4883
4884
4885
4886
4887
4888
4889
4890
4891
4892
4893
4894
4895
4896
4897
4898
4899
4900
4901
4902
4903
4904
4905
4906
4907
4908
4909
4910
4911
4912
4913
4914
4915
4916
4917
4918
4919
4920
4921
4922
4923
4924
4925
4926
4927
4928
4929
4930
4931
4932
4933
4934
4935
4936
4937
4938
4939
4940
4941
4942
4943
4944
4945
4946
4947
4948
4949
4950
4951
4952
4953
4954
4955
4956
4957
4958
4959
4960
4961
4962
4963
4964
4965
4966
4967
4968
4969
4970
4971
4972
4973
4974
4975
4976
4977
4978
4979
4980
4981
4982
4983
4984
4985
4986
4987
4988
4989
4990
4991
4992
4993
4994
4995
4996
4997
4998
4999
5000
5001
5002
5003
5004
5005
5006
5007
5008
5009
5010
5011
5012
5013
5014
5015
5016
5017
5018
5019
5020
5021
5022
5023
5024
5025
5026
5027
5028
5029
5030
5031
5032
5033
5034
5035
5036
5037
5038
5039
5040
5041
5042
5043
5044
5045
5046
5047
5048
5049
5050
5051
5052
5053
5054
5055
5056
5057
5058
5059
5060
5061
5062
5063
5064
5065
5066
5067
5068
5069
5070
5071
5072
5073
5074
5075
5076
5077
5078
5079
5080
5081
5082
5083
5084
5085
5086
5087
5088
5089
5090
5091
5092
5093
5094
5095
5096
5097
5098
5099
5100
5101
5102
5103
5104
5105
5106
5107
5108
5109
5110
5111
5112
5113
5114
5115
5116
5117
5118
5119
5120
5121
5122
5123
5124
5125
5126
5127
5128
5129
5130
5131
5132
5133
5134
5135
5136
5137
5138
5139
5140
5141
5142
5143
5144
5145
5146
5147
5148
5149
5150
5151
5152
5153
5154
5155
5156
5157
5158
5159
5160
5161
5162
5163
5164
5165
5166
5167
5168
5169
5170
5171
5172
5173
5174
5175
5176
5177
5178
5179
5180
5181
5182
5183
5184
5185
5186
5187
5188
5189
5190
5191
5192
5193
5194
5195
5196
5197
5198
5199
5200
5201
5202
5203
5204
5205
5206
5207
5208
5209
5210
5211
5212
5213
5214
5215
5216
5217
5218
5219
5220
5221
5222
5223
5224
5225
5226
5227
5228
5229
5230
5231
5232
5233
5234
5235
5236
5237
5238
5239
5240
5241
5242
5243
5244
5245
5246
5247
5248
5249
5250
5251
5252
5253
5254
5255
5256
5257
5258
5259
5260
5261
5262
5263
5264
5265
5266
5267
5268
5269
5270
5271
5272
5273
5274
5275
5276
5277
5278
5279
5280
5281
5282
5283
5284
5285
5286
5287
5288
5289
5290
5291
5292
5293
5294
5295
5296
5297
5298
5299
5300
5301
5302
5303
5304
5305
5306
5307
5308
5309
5310
5311
5312
5313
5314
5315
5316
5317
5318
5319
5320
5321
5322
5323
5324
5325
5326
5327
5328
5329
5330
5331
5332
5333
5334
5335
5336
5337
5338
5339
5340
5341
5342
5343
5344
5345
5346
5347
5348
5349
5350
5351
5352
5353
5354
5355
5356
5357
5358
5359
5360
5361
5362
5363
5364
5365
5366
5367
5368
5369
5370
5371
5372
5373
5374
5375
5376
5377
5378
5379
5380
5381
5382
5383
5384
5385
5386
5387
5388
5389
5390
5391
5392
5393
5394
5395
5396
5397
5398
5399
5400
5401
5402
5403
5404
5405
5406
5407
5408
5409
5410
5411
5412
5413
5414
5415
5416
5417
5418
5419
5420
5421
5422
5423
5424
5425
5426
5427
5428
5429
5430
5431
5432
5433
5434
5435
5436
5437
5438
5439
5440
5441
5442
5443
5444
5445
5446
5447
5448
5449
5450
5451
5452
5453
5454
5455
5456
5457
5458
5459
5460
5461
5462
5463
5464
5465
5466
5467
5468
5469
5470
5471
5472
5473
5474
5475
5476
5477
5478
5479
5480
5481
5482
5483
5484
5485
5486
5487
5488
5489
5490
5491
5492
5493
5494
5495
5496
5497
5498
5499
5500
5501
5502
5503
5504
5505
5506
5507
5508
5509
5510
5511
5512
5513
5514
5515
5516
5517
5518
5519
5520
5521
5522
5523
5524
5525
5526
5527
5528
5529
5530
5531
5532
5533
5534
5535
5536
5537
5538
5539
5540
5541
5542
5543
5544
5545
5546
5547
5548
5549
5550
5551
5552
5553
5554
5555
5556
5557
5558
5559
5560
5561
5562
5563
5564
5565
5566
5567
5568
5569
5570
5571
5572
5573
5574
5575
5576
5577
5578
5579
5580
5581
5582
5583
5584
5585
5586
5587
5588
5589
5590
5591
5592
5593
5594
5595
5596
5597
5598
5599
5600
5601
5602
5603
5604
5605
5606
5607
5608
5609
5610
5611
5612
5613
5614
5615
5616
5617
5618
5619
5620
5621
5622
5623
5624
5625
5626
5627
5628
5629
5630
5631
5632
5633
5634
5635
5636
5637
5638
5639
5640
5641
5642
5643
5644
5645
5646
5647
5648
5649
5650
5651
5652
5653
5654
5655
5656
5657
5658
5659
5660
5661
5662
5663
5664
5665
5666
5667
5668
5669
5670
5671
5672
5673
5674
5675
5676
5677
5678
5679
5680
5681
5682
5683
5684
5685
5686
5687
5688
5689
5690
5691
5692
5693
5694
5695
5696
5697
5698
5699
5700
5701
5702
5703
5704
5705
5706
5707
5708
5709
5710
5711
5712
5713
5714
5715
5716
5717
5718
5719
5720
5721
5722
5723
5724
5725
5726
5727
5728
5729
5730
5731
5732
5733
5734
5735
5736
5737
5738
5739
5740
5741
5742
5743
5744
5745
5746
5747
5748
5749
5750
5751
5752
5753
5754
5755
5756
5757
5758
5759
5760
5761
5762
5763
5764
5765
5766
5767
5768
5769
5770
5771
5772
5773
5774
5775
5776
5777
5778
5779
5780
5781
5782
5783
5784
5785
5786
5787
5788
5789
5790
5791
5792
5793
5794
5795
5796
5797
5798
5799
5800
5801
5802
5803
5804
5805
5806
5807
5808
5809
5810
5811
5812
5813
5814
5815
5816
5817
5818
5819
5820
5821
5822
5823
5824
5825
5826
5827
5828
5829
5830
5831
5832
5833
5834
5835
5836
5837
5838
5839
5840
5841
5842
5843
5844
5845
5846
5847
5848
5849
5850
5851
5852
5853
5854
5855
5856
5857
5858
5859
5860
5861
5862
5863
5864
5865
5866
5867
5868
5869
5870
5871
5872
5873
5874
5875
5876
5877
5878
5879
5880
5881
5882
5883
5884
5885
5886
5887
5888
5889
5890
5891
5892
5893
5894
5895
5896
5897
5898
5899
5900
5901
5902
5903
5904
5905
5906
5907
5908
5909
5910
5911
5912
5913
5914
5915
5916
5917
5918
5919
5920
5921
5922
5923
5924
5925
5926
5927
5928
5929
5930
5931
5932
5933
5934
5935
5936
5937
5938
5939
5940
5941
5942
5943
5944
5945
5946
5947
5948
5949
5950
5951
5952
5953
5954
5955
5956
5957
5958
5959
5960
5961
5962
5963
5964
5965
5966
5967
5968
5969
5970
5971
5972
5973
5974
5975
5976
5977
5978
5979
5980
5981
5982
5983
5984
5985
5986
5987
5988
5989
5990
5991
5992
5993
5994
5995
5996
5997
5998
5999
6000
6001
6002
6003
6004
6005
6006
6007
6008
6009
6010
6011
6012
6013
6014
6015
6016
6017
6018
6019
6020
6021
6022
6023
6024
6025
6026
6027
6028
6029
6030
6031
6032
6033
6034
6035
6036
6037
6038
6039
6040
6041
6042
6043
6044
6045
6046
6047
6048
6049
6050
6051
6052
6053
6054
6055
6056
6057
6058
6059
6060
6061
6062
6063
6064
6065
6066
6067
6068
6069
6070
6071
6072
6073
6074
6075
6076
6077
6078
6079
6080
6081
6082
6083
6084
6085
6086
6087
6088
6089
6090
6091
6092
6093
6094
6095
6096
6097
6098
6099
6100
6101
6102
6103
6104
6105
6106
6107
6108
6109
6110
6111
6112
6113
6114
6115
6116
6117
6118
6119
6120
6121
6122
6123
6124
6125
6126
6127
6128
6129
6130
6131
6132
6133
6134
6135
6136
6137
6138
6139
6140
6141
6142
6143
6144
6145
6146
6147
6148
6149
6150
6151
6152
6153
6154
6155
6156
6157
6158
6159
6160
6161
6162
6163
6164
6165
6166
6167
6168
6169
6170
6171
6172
6173
6174
6175
6176
6177
6178
6179
6180
6181
6182
6183
6184
6185
6186
6187
6188
6189
6190
6191
6192
6193
6194
6195
6196
6197
6198
6199
6200
6201
6202
6203
6204
6205
6206
6207
6208
6209
6210
6211
6212
6213
6214
6215
6216
6217
6218
6219
6220
6221
6222
6223
6224
6225
6226
6227
6228
6229
6230
6231
6232
6233
6234
6235
6236
6237
6238
6239
6240
6241
6242
6243
6244
6245
6246
6247
6248
6249
6250
6251
6252
6253
6254
6255
6256
6257
6258
6259
6260
6261
6262
6263
6264
6265
6266
6267
6268
6269
6270
6271
6272
6273
6274
6275
6276
6277
6278
6279
6280
6281
6282
6283
6284
6285
6286
6287
6288
6289
6290
6291
6292
6293
6294
6295
6296
6297
6298
6299
6300
6301
6302
6303
6304
6305
6306
6307
6308
6309
6310
6311
6312
6313
6314
6315
6316
6317
6318
6319
6320
6321
6322
6323
6324
6325
6326
6327
6328
6329
6330
6331
6332
6333
6334
6335
6336
6337
6338
6339
6340
6341
6342
6343
6344
6345
6346
6347
6348
6349
6350
6351
6352
6353
6354
6355
6356
6357
6358
6359
6360
6361
6362
6363
6364
6365
6366
6367
6368
6369
6370
6371
6372
6373
6374
6375
6376
6377
6378
6379
6380
6381
6382
6383
6384
6385
6386
6387
6388
6389
6390
6391
6392
6393
6394
6395
6396
6397
6398
6399
6400
6401
6402
6403
6404
6405
6406
6407
6408
6409
6410
6411
6412
6413
6414
6415
6416
6417
6418
6419
6420
6421
6422
6423
6424
6425
6426
6427
6428
6429
6430
6431
6432
6433
6434
6435
6436
6437
6438
6439
6440
6441
6442
6443
6444
6445
6446
6447
6448
6449
6450
6451
6452
6453
6454
6455
6456
6457
6458
6459
6460
6461
6462
6463
6464
6465
6466
6467
6468
6469
6470
6471
6472
6473
6474
6475
6476
6477
6478
6479
6480
6481
6482
6483
6484
6485
6486
6487
6488
6489
6490
6491
6492
6493
6494
6495
6496
6497
6498
6499
6500
6501
6502
6503
6504
6505
6506
6507
6508
6509
6510
6511
6512
6513
6514
6515
6516
6517
6518
6519
6520
6521
6522
6523
6524
6525
6526
6527
6528
6529
6530
6531
6532
6533
6534
6535
6536
6537
6538
6539
6540
6541
6542
6543
6544
6545
6546
6547
6548
6549
6550
6551
6552
6553
6554
6555
6556
6557
6558
6559
6560
6561
6562
6563
6564
6565
6566
6567
6568
6569
6570
6571
6572
6573
6574
6575
6576
6577
6578
6579
6580
6581
6582
6583
6584
6585
6586
6587
6588
6589
6590
6591
6592
6593
6594
6595
6596
6597
6598
6599
6600
6601
6602
6603
6604
6605
6606
6607
6608
6609
6610
6611
6612
6613
6614
6615
6616
6617
6618
6619
6620
6621
6622
6623
6624
6625
6626
6627
6628
6629
6630
6631
6632
6633
6634
6635
6636
6637
6638
6639
6640
6641
6642
6643
6644
6645
6646
6647
6648
6649
6650
6651
6652
6653
6654
6655
6656
6657
6658
6659
6660
6661
6662
6663
6664
6665
6666
6667
6668
6669
6670
6671
6672
6673
6674
6675
6676
6677
6678
6679
6680
6681
6682
6683
6684
6685
6686
6687
6688
6689
6690
6691
6692
6693
6694
6695
6696
6697
6698
6699
6700
6701
6702
6703
6704
6705
6706
6707
6708
6709
6710
6711
6712
6713
6714
6715
6716
6717
6718
6719
6720
6721
6722
6723
6724
6725
6726
6727
6728
6729
6730
6731
6732
6733
6734
6735
6736
6737
6738
6739
6740
6741
6742
6743
6744
6745
6746
6747
6748
6749
6750
6751
6752
6753
6754
6755
6756
6757
6758
6759
6760
6761
6762
6763
6764
6765
6766
6767
6768
6769
6770
6771
6772
6773
6774
6775
6776
6777
6778
6779
6780
6781
6782
6783
6784
6785
6786
6787
6788
6789
6790
6791
6792
6793
6794
6795
6796
6797
6798
6799
6800
6801
6802
6803
6804
6805
6806
6807
6808
6809
6810
6811
6812
6813
6814
6815
6816
6817
6818
6819
6820
6821
6822
6823
6824
6825
6826
6827
6828
6829
6830
6831
6832
6833
6834
6835
6836
6837
6838
6839
6840
6841
6842
6843
6844
6845
6846
6847
6848
6849
6850
6851
6852
6853
6854
6855
6856
6857
6858
6859
6860
6861
6862
6863
6864
6865
6866
6867
6868
6869
6870
6871
6872
6873
6874
6875
6876
6877
6878
6879
6880
6881
6882
6883
6884
6885
6886
6887
6888
6889
6890
6891
6892
6893
6894
6895
6896
6897
6898
6899
6900
6901
6902
6903
6904
6905
6906
6907
6908
6909
6910
6911
6912
6913
6914
6915
6916
6917
6918
6919
6920
6921
6922
6923
6924
6925
6926
6927
6928
6929
6930
6931
6932
6933
6934
6935
6936
6937
6938
6939
6940
6941
6942
6943
6944
6945
6946
6947
6948
6949
6950
6951
6952
6953
6954
6955
6956
6957
6958
6959
6960
6961
6962
6963
6964
6965
6966
6967
6968
6969
6970
6971
6972
6973
6974
6975
6976
6977
6978
6979
6980
6981
6982
6983
6984
6985
6986
6987
6988
6989
6990
6991
6992
6993
6994
6995
6996
6997
6998
6999
7000
7001
7002
7003
7004
7005
7006
7007
7008
7009
7010
7011
7012
7013
7014
7015
7016
7017
7018
7019
7020
7021
7022
7023
7024
7025
7026
7027
7028
7029
7030
7031
7032
7033
7034
7035
7036
7037
7038
7039
7040
7041
7042
7043
7044
7045
7046
7047
7048
7049
7050
7051
7052
7053
7054
7055
7056
7057
7058
7059
7060
7061
7062
7063
7064
7065
7066
7067
7068
7069
7070
7071
7072
7073
7074
7075
7076
7077
7078
7079
7080
7081
7082
7083
7084
7085
7086
7087
7088
7089
7090
7091
7092
7093
7094
7095
7096
7097
7098
7099
7100
7101
7102
7103
7104
7105
7106
7107
7108
7109
7110
7111
7112
7113
7114
7115
7116
7117
7118
7119
7120
7121
7122
7123
7124
7125
7126
7127
7128
7129
7130
7131
7132
7133
7134
7135
7136
7137
7138
7139
7140
7141
7142
7143
7144
7145
7146
7147
7148
7149
7150
7151
7152
7153
7154
7155
7156
7157
7158
7159
7160
7161
7162
7163
7164
7165
7166
7167
7168
7169
7170
7171
7172
7173
7174
7175
7176
7177
7178
7179
7180
7181
7182
7183
7184
7185
7186
7187
7188
7189
7190
7191
7192
7193
7194
7195
7196
7197
7198
7199
7200
7201
7202
7203
7204
7205
7206
7207
7208
7209
7210
7211
7212
7213
7214
7215
7216
7217
7218
7219
7220
7221
7222
7223
7224
7225
7226
7227
7228
7229
7230
7231
7232
7233
7234
7235
7236
7237
7238
7239
7240
7241
7242
7243
7244
7245
7246
7247
7248
7249
7250
7251
7252
7253
7254
7255
7256
7257
7258
7259
7260
7261
7262
7263
7264
7265
7266
7267
7268
7269
7270
7271
7272
7273
7274
7275
7276
7277
7278
7279
7280
7281
7282
7283
7284
7285
7286
7287
7288
7289
7290
7291
7292
7293
7294
7295
7296
7297
7298
7299
7300
7301
7302
7303
7304
7305
7306
7307
7308
7309
7310
7311
7312
7313
7314
7315
7316
7317
7318
7319
7320
7321
7322
7323
7324
7325
7326
7327
7328
7329
7330
7331
7332
7333
7334
7335
7336
7337
7338
7339
7340
7341
7342
7343
7344
7345
7346
7347
7348
7349
7350
7351
7352
7353
7354
7355
7356
7357
7358
7359
7360
7361
7362
7363
7364
7365
7366
7367
7368
7369
7370
7371
7372
7373
7374
7375
7376
7377
7378
7379
7380
7381
7382
7383
7384
7385
7386
7387
7388
7389
7390
7391
7392
7393
7394
7395
7396
7397
7398
7399
7400
7401
7402
7403
7404
7405
7406
7407
7408
7409
7410
7411
7412
7413
7414
7415
7416
7417
7418
7419
7420
7421
7422
7423
7424
7425
7426
7427
7428
7429
7430
7431
7432
7433
7434
7435
7436
7437
7438
7439
7440
7441
7442
7443
7444
7445
7446
7447
7448
7449
7450
7451
7452
7453
7454
7455
7456
7457
7458
7459
7460
7461
7462
7463
7464
7465
7466
7467
7468
7469
7470
7471
7472
7473
7474
7475
7476
7477
7478
7479
7480
7481
7482
7483
7484
7485
7486
7487
7488
7489
7490
7491
7492
7493
7494
7495
7496
7497
7498
7499
7500
7501
7502
7503
7504
7505
7506
7507
7508
7509
7510
7511
7512
7513
7514
7515
7516
7517
7518
7519
7520
7521
7522
7523
7524
7525
7526
7527
7528
7529
7530
7531
7532
7533
7534
7535
7536
7537
7538
7539
7540
7541
7542
7543
7544
7545
7546
7547
7548
7549
7550
7551
7552
7553
7554
7555
7556
7557
7558
7559
7560
7561
// stet-pdf-reader
// Copyright (c) 2026 Scott Bowman
// SPDX-License-Identifier: Apache-2.0 OR MIT

//! PDF content stream interpreter.
//!
//! Converts PDF page content into a `DisplayList` for rendering through
//! the existing SkiaDevice pipeline.

pub mod cid_unicode;
pub mod cmap;
pub mod color_space;
pub mod font;
mod gid_maps;
pub mod graphics_state;
mod standard_fonts;

use crate::error::PdfError;
use crate::lexer::{Lexer, MAX_OBJECT_DEPTH, Token};
use crate::objects::{PdfDict, PdfObj};
use crate::resolver::Resolver;

use self::color_space::{
    ResolvedColorSpace, painted_channels_for_cs, register_icc_profile, resolve_color_space,
    resolve_color_space_obj, to_image_color_space,
};
use self::graphics_state::{ColorSpaceRef, PdfGraphicsState};

use std::sync::{Arc, Mutex};

use self::font::{FontCache, PdfFont};
use self::graphics_state::{ShadingPatternDL, TilingPattern};
use crate::FontProvider;
use stet_fonts::geometry::{Matrix, PathSegment, PsPath};
use stet_graphics::color::{DashPattern, DeviceColor, FillRule, LineCap, LineJoin};
use stet_graphics::device::{
    ClipParams, FillParams, ImageColorSpace, ImageParams, PatternFillParams, StrokeParams,
    TintLookupTable,
};
use stet_graphics::display_list::{
    DisplayElement, DisplayList, GroupParams, OcgVisibility, SoftMaskParams, SoftMaskSubtype,
};
use stet_graphics::icc::IccCache;
use stet_graphics::image_limits::{
    validate_bits_per_component, validate_image_dimension, validate_image_size,
};

/// Maximum nesting of re-entrant content streams.
///
/// Form XObjects, tiling and shading patterns, Type 3 CharProcs, and soft-mask
/// groups are all interpreted by re-entering `interpret_stream`, and each can
/// name itself either directly or through a ring of siblings. A cycle recurses
/// on the native stack, which overflows into an abort that `catch_unwind`
/// cannot contain — so every such entry point checks this cap. Legitimate
/// documents nest a handful of levels; 20 was already the Form XObject limit
/// and is kept here so the bound does not change for files that render today.
const MAX_CONTENT_NESTING: u32 = 20;

/// One entry on the marked-content stack. Pushed on every BDC/BMC, popped
/// on every EMC — so the stack stays balanced regardless of how OC and
/// non-OC blocks interleave. Only `Ocg` entries swap the display list;
/// `Other` entries carry no state but must still exist so EMC pops the
/// correct frame.
enum MarkedContentFrame {
    /// An `/OC BDC` block: parent display list was swapped out, and the
    /// matching EMC wraps the collected children in an `OcgGroup`.
    Ocg {
        parent_list: DisplayList,
        visibility: OcgVisibility,
    },
    /// Any other BDC (non-OC property reference) or BMC.
    Other,
}

/// Read a numeric array entry, following an indirect reference if needed.
///
/// PDF dict values like `/BBox`, `/Matrix`, `/MediaBox`, etc. are commonly
/// shared across multiple objects via indirect references (e.g. several form
/// XObjects may share a single `/BBox 4 0 R`). `PdfDict::get_array` returns
/// `None` for an indirect-ref value, so callers that need the numbers must
/// dereference first.
fn deref_num_array(resolver: &Resolver, dict: &PdfDict, key: &[u8]) -> Option<Vec<f64>> {
    let obj = dict.get(key)?;
    if let Some(arr) = obj.as_array() {
        return Some(arr.iter().filter_map(|o| o.as_f64()).collect());
    }
    let resolved = resolver.deref(obj).ok()?;
    resolved
        .as_array()
        .map(|a| a.iter().filter_map(|o| o.as_f64()).collect())
}

/// An operand on the content stream operand stack.
#[derive(Clone, Debug)]
pub enum Operand {
    Int(i64),
    Real(f64),
    Name(Vec<u8>),
    Str(Vec<u8>),
    Array(Vec<PdfObj>),
    Dict(PdfDict),
    Bool(bool),
}

impl Operand {
    /// Get numeric value as f64.
    fn as_f64(&self) -> Option<f64> {
        match self {
            Operand::Int(n) => Some(*n as f64),
            Operand::Real(f) => Some(*f),
            _ => None,
        }
    }

    /// Get name bytes.
    fn as_name(&self) -> Option<&[u8]> {
        match self {
            Operand::Name(n) => Some(n),
            _ => None,
        }
    }

    /// Get string bytes.
    #[allow(dead_code)]
    fn as_str(&self) -> Option<&[u8]> {
        match self {
            Operand::Str(s) => Some(s),
            _ => None,
        }
    }
}

/// Cached result of a fully-processed Image XObject.
/// Keyed by obj_num in the content interpreter's `image_cache`.
#[derive(Clone)]
struct CachedImage {
    sample_data: Arc<Vec<u8>>,
    width: u32,
    height: u32,
    color_space: ImageColorSpace,
    bits_per_component: u8,
    interpolate: bool,
    mask_color: Option<Vec<u8>>,
    /// CMYK painted channels derived from the image's own color space.
    painted_channels: u8,
    /// For soft-masked images: (mask_gray_data, mask_width, mask_height, matte).
    smask: Option<(Arc<Vec<u8>>, u32, u32, Option<Vec<f64>>)>,
    /// The image's `/Intent` (or the gstate `/RI` at first emit if absent).
    /// Cached so re-emits keep the same intent — the image-level intent is a
    /// property of the image, not of the gstate at re-use time.
    rendering_intent: u8,
}

/// Tracks the scope of an active soft mask in the display list.
struct SoftMaskScope {
    /// Index in display_list where the mask scope began.
    start_index: usize,
    /// The resolved soft mask (mask display list + params).
    mask: graphics_state::SoftMask,
}

/// PDF content stream interpreter.
pub struct ContentInterpreter<'a> {
    resolver: &'a Resolver<'a>,
    resources: PdfDict,
    gstate_stack: Vec<PdfGraphicsState>,
    gstate: PdfGraphicsState,
    current_path: PsPath,
    current_point: Option<(f64, f64)>,
    subpath_start: Option<(f64, f64)>,
    operand_stack: Vec<Operand>,
    display_list: DisplayList,
    in_text: bool,
    /// Nesting level of the content stream being interpreted: Form XObjects,
    /// tiling/shading patterns, Type 3 CharProcs, soft-mask forms, and
    /// annotation appearance streams each add one. Capped at
    /// [`MAX_CONTENT_NESTING`] — every one of those constructs can name itself
    /// (directly or through a ring), and unguarded re-entry aborts the process
    /// with a stack overflow rather than a catchable panic.
    depth: u32,
    /// True inside a Type 3 CharProc that started with `d1`. Per PDF spec 9.6.5,
    /// color operators must be ignored (glyph uses the current text color).
    d1_color_suppressed: bool,
    font_cache: FontCache,
    current_font: Option<Arc<PdfFont>>,
    /// CTM at the start of the current content stream (page or form).
    /// PDF pattern Matrix maps to the "default (initial) coordinate system
    /// of the parent content stream" — for patterns inside Form XObjects,
    /// this includes the form's matrix transform, not just the page CTM.
    content_stream_ctm: Matrix,
    /// The initial page CTM (DPI scaling + Y-flip + CropBox offset).
    /// Never modified after construction. Used by annotation rendering to
    /// position appearance streams relative to the page, not the CTM left
    /// behind by the content stream.
    initial_ctm: Matrix,
    /// ICC color profile cache for ICCBased color space conversions.
    icc_cache: IccCache,
    /// Active soft mask scope: tracks which display list elements fall under the current SMask.
    soft_mask_scope: Option<SoftMaskScope>,
    /// Counter: incremented when the Q handler flushes a gs-set SMask scope
    /// (detected via smask_gen change). Used by resolve_soft_mask to detect
    /// genuine nested mask scopes vs image-level SMasks.
    nested_mask_flush_count: u32,
    /// Optional font data provider for environments without filesystem access.
    font_provider: Option<FontProvider>,
    /// Accumulated text clip path (for text rendering modes 4-7).
    /// Built up during BT..ET, applied as clip at ET.
    text_clip_path: Option<PsPath>,
    /// When true, DeviceRGB colors are round-tripped through the system CMYK
    /// profile (RGB→CMYK→RGB) to match compositing in a DeviceCMYK page group.
    page_group_is_cmyk: bool,
    /// True only when the document declares a PDF/X-style CMYK output intent
    /// (`/OutputIntents` with a CMYK profile). Required (along with
    /// `page_group_is_cmyk`) for the DeviceGray-to-K-only promotion to fire.
    ///
    /// Plain `/Group /CS /DeviceCMYK` without an output intent (e.g.
    /// `pdf_samples/3000_5.pdf`, `pdf_samples/2495.pdf`) signals only that
    /// compositing happens in CMYK space — it does NOT opt the document into
    /// the system CMYK profile's paper white, so a `0.5 g` paint must still
    /// render at exact RGB(128, 128, 128). Documents that DO declare a CMYK
    /// output intent (PDF/X) accept the profile's paper white as their own
    /// and expect DeviceGray to map onto the K plate (GWG 23.0). The narrower
    /// gate matches the existing `cmyk_group_rgb` round-trip's expectation:
    /// that helper takes RGB and rounds it through CMYK→RGB (range-preserving
    /// on a non-PDF/X CMYK group), while this gate switches the source space
    /// from DeviceGray to DeviceCMYK — only correct when the document opts in.
    pdfx_cmyk_intent: bool,
    /// True while parsing an SMask source form's content stream. The
    /// DeviceGray-to-K-only promotion (`gray_paint_for_gstate`,
    /// `cmyk_group_promote_image`, `cmyk_group_promote_color`) must be
    /// suppressed in this context: image color conversion happens at render
    /// time, after the parse-time `suspend_default_cmyk` has been restored,
    /// so a promoted CMYK-K image emitted from an SMask source would later
    /// hit the ICC pipeline and shift the SMask's luminosity (g=255 → CMYK
    /// 0/0/0/0 → ICC RGB ≈ (241,241,241) → alpha ≈ 0.94 instead of 1.0,
    /// regressed `pdf_samples/2495.pdf`'s right-side images). Mirrors the
    /// existing `IccCache::suspend_default_cmyk` precedent at the layer where
    /// the promotion happens — needed even within PDF/X documents (the gate
    /// above doesn't help there; only the SMask context guard does).
    in_smask_form: bool,
    /// When false, PDF overprint flags (OP/op) in graphics state dicts are
    /// suppressed — the gstate overprint fields stay false regardless of PDF content.
    overprint_enabled: bool,
    /// Cache of resolved tiling patterns, keyed by PDF indirect reference (obj_num, gen).
    /// Ensures the same pattern stream is interpreted only once, with the graphics
    /// state from the first resolution (matching GhostScript behaviour).
    pattern_cache: std::collections::HashMap<(u32, u16), TilingPattern>,
    /// Object numbers of Optional Content Groups that are OFF by default.
    ocg_off: std::collections::HashSet<u32>,
    /// Stack of marked-content frames. Every BDC/BMC pushes one frame,
    /// every EMC pops one — keeping the stack balanced even when OC and
    /// non-OC sections interleave. Only `Ocg` frames actually swap the
    /// display list; `Other` frames are placeholders.
    mc_stack: Vec<MarkedContentFrame>,
    /// HashMap index of the current resource dict's ColorSpace sub-dict.
    /// Built lazily on first sc/scn access to avoid O(n) PdfDict scans.
    cs_index: Option<std::collections::HashMap<Vec<u8>, PdfObj>>,
    /// Visible Y range in form coordinates for early culling of offscreen content.
    /// Set when entering a Form XObject whose BBox is much larger than the clip area.
    /// BT/ET blocks whose Y position falls outside this range are skipped.
    form_cull_y: Option<(f64, f64)>,
    /// When true, the current BT/ET block is being skipped (offscreen).
    bt_culled: bool,
    /// Cache of fully-processed Image XObject data, keyed by obj_num.
    /// Avoids re-decompressing and re-converting the same image (e.g.,
    /// Type 3 emoji glyphs that reference the same XObject 73 times).
    image_cache: std::collections::HashMap<u32, CachedImage>,
    /// Cache of pre-sampled spot tint tables, keyed by the colorspace's
    /// canonical identity (Separation name or DeviceN colorant list). The
    /// tint function is expensive to sample (up to 256 evaluations for
    /// Separation, thousands for DeviceN), and many documents paint the same
    /// spot color hundreds of times per page; without this cache every
    /// `sc`/`scn` re-evaluates the same function from scratch.
    spot_tint_table_cache:
        std::collections::HashMap<Vec<u8>, Arc<stet_graphics::device::TintLookupTable>>,
}

impl<'a> ContentInterpreter<'a> {
    /// Create a new interpreter.
    pub fn new(
        resolver: &'a Resolver<'a>,
        resources: PdfDict,
        initial_ctm: Matrix,
        icc_cache: &IccCache,
        font_provider: Option<FontProvider>,
        overprint_enabled: bool,
        ocg_off: &std::collections::HashSet<u32>,
    ) -> Self {
        Self {
            resolver,
            resources,
            gstate_stack: Vec::new(),
            gstate: PdfGraphicsState::new(initial_ctm),
            current_path: PsPath::new(),
            current_point: None,
            subpath_start: None,
            operand_stack: Vec::new(),
            display_list: DisplayList::new(),
            content_stream_ctm: initial_ctm,
            initial_ctm,
            in_text: false,
            depth: 0,
            d1_color_suppressed: false,
            nested_mask_flush_count: 0,
            font_cache: FontCache::new(),
            current_font: None,
            icc_cache: icc_cache.clone(),
            soft_mask_scope: None,
            font_provider,
            text_clip_path: None,
            page_group_is_cmyk: false,
            pdfx_cmyk_intent: false,
            in_smask_form: false,
            overprint_enabled,
            pattern_cache: std::collections::HashMap::new(),
            ocg_off: ocg_off.clone(),
            mc_stack: Vec::new(),
            cs_index: None,
            form_cull_y: None,
            bt_culled: false,
            image_cache: std::collections::HashMap::new(),
            spot_tint_table_cache: std::collections::HashMap::new(),
        }
    }

    /// Mark this page as having a DeviceCMYK transparency group.
    /// DeviceRGB colors will be round-tripped through the ICC CMYK profile
    /// to match compositing in CMYK space (produces more muted, accurate colors).
    pub fn set_page_group_cmyk(&mut self) {
        self.page_group_is_cmyk = true;
    }

    /// Mark this document as declaring a PDF/X-style CMYK output intent. Opts
    /// the document into the DeviceGray-to-K-only promotion required by GWG
    /// 23.0. Plain `/Group /CS /DeviceCMYK` pages should not call this.
    pub fn set_pdfx_cmyk_intent(&mut self) {
        self.pdfx_cmyk_intent = true;
    }

    /// Look up a sub-dictionary in the resources, resolving indirect references.
    /// e.g., `resolve_resource_subdict(b"Font")` returns the /Font dict.
    /// Get an integer value from a dict, resolving indirect references.
    fn resolve_dict_int(&self, dict: &PdfDict, key: &[u8]) -> Option<i64> {
        let obj = dict.get(key)?;
        if let Some(n) = obj.as_int() {
            return Some(n);
        }
        // Resolve indirect reference
        let resolved = self.resolver.deref(obj).ok()?;
        resolved.as_int()
    }

    fn resolve_resource_subdict(&self, key: &[u8]) -> Option<PdfDict> {
        let obj = self.resources.get(key)?;
        // If it's already a dict, return it
        if let Some(d) = obj.as_dict() {
            return Some(d.clone());
        }
        // Otherwise try to resolve the reference
        let resolved = self.resolver.deref(obj).ok()?;
        resolved.as_dict().cloned()
    }

    /// Interpret a content stream and return the display list.
    pub fn interpret(mut self, data: &[u8]) -> Result<DisplayList, PdfError> {
        if let Err(e) = self.interpret_stream(data) {
            eprintln!("warning: content stream error: {}", e);
        }
        // Flush any active soft mask scope
        self.flush_soft_mask();
        // Return partial display list even on error — handles malformed PDFs
        // where flate decompression produces truncated content streams.
        Ok(self.display_list)
    }

    /// Interpret a content stream, keeping the interpreter alive for further use.
    pub fn interpret_stream_public(&mut self, data: &[u8]) -> Result<(), PdfError> {
        self.interpret_stream(data)
    }

    /// Consume the interpreter and return the display list.
    pub fn into_display_list(mut self) -> DisplayList {
        self.flush_soft_mask();
        // Close any unmatched marked-content blocks from unbalanced BDC/EMC
        while let Some(frame) = self.mc_stack.pop() {
            if let MarkedContentFrame::Ocg {
                parent_list,
                visibility,
            } = frame
            {
                let ocg_list = std::mem::replace(&mut self.display_list, parent_list);
                self.display_list.push(DisplayElement::OcgGroup {
                    elements: ocg_list,
                    visibility,
                });
            }
        }
        self.display_list
    }

    /// Unwind any leftover gstate stack entries from unbalanced q/Q.
    /// Some PDFs have more q's than Q's; pop each entry as if Q were called,
    /// restoring clip state at each level so display list clips are correct.
    pub fn unwind_gstate_stack(&mut self) {
        while let Some(saved) = self.gstate_stack.pop() {
            let old_clip_version = self.gstate.clip_path_version;
            self.gstate = saved;
            if self.gstate.clip_path_version != old_clip_version {
                self.restore_clip_from_stack();
            }
        }
    }

    /// Reset clip state before rendering annotations.
    /// This ensures annotations aren't affected by clip regions from the page content.
    pub fn reset_clip_for_annotations(&mut self) {
        self.display_list.push(DisplayElement::InitClip);
        self.gstate.clip_path = None;
        self.gstate.clip_stack.clear();
        self.gstate.clip_path_version += 1;
    }

    /// Render an annotation's normal appearance stream (/AP /N).
    pub fn render_annotation(&mut self, obj_num: u32, gen_num: u16) -> Result<(), PdfError> {
        let annot_obj = self.resolver.resolve(obj_num, gen_num)?;
        let annot_dict = annot_obj
            .as_dict()
            .ok_or(PdfError::Other("annotation not a dict".into()))?;

        let subtype = annot_dict.get_name(b"Subtype").unwrap_or(b"");

        // Check annotation flags (/F). PDF spec Table 165:
        // Bit 1 (0x01) = Invisible, Bit 2 (0x02) = Hidden, Bit 6 (0x20) = NoView.
        // Skip annotations that shouldn't be rendered on screen.
        let flags = annot_dict.get_int(b"F").unwrap_or(0);
        if flags & 0x02 != 0 {
            return Ok(()); // Hidden
        }

        // Get /Rect [llx, lly, urx, ury], normalizing swapped coordinates.
        // Rect may be an indirect reference — resolve before parsing.
        let rect = annot_dict
            .get(b"Rect")
            .and_then(|obj| {
                let resolved = self.resolver.deref(obj).ok().unwrap_or(obj.clone());
                let a = resolved
                    .as_array()
                    .or_else(|| annot_dict.get_array(b"Rect"))?;
                if a.len() >= 4 {
                    let r0 = a[0].as_f64()?;
                    let r1 = a[1].as_f64()?;
                    let r2 = a[2].as_f64()?;
                    let r3 = a[3].as_f64()?;
                    Some([r0.min(r2), r1.min(r3), r0.max(r2), r1.max(r3)])
                } else {
                    None
                }
            })
            .ok_or(PdfError::Other("annotation missing Rect".into()))?;

        // Get /AP dict → /N (normal appearance).
        // If no AP, synthesize appearance from annotation properties.
        let ap_obj = match annot_dict.get(b"AP") {
            Some(ap) => ap,
            None => {
                return self.synthesize_annotation(annot_dict, &rect);
            }
        };
        let ap_dict = match self.resolver.deref(ap_obj)? {
            PdfObj::Dict(d) => d,
            _ => return Err(PdfError::Other("AP not a dict".into())),
        };

        let n_ref = ap_dict.get(b"N").ok_or(PdfError::Other("no AP/N".into()))?;

        // Resolve to get the Form XObject dict + stream.
        // AP/N may be a stream (single appearance) or a dict mapping state
        // names to streams (e.g. checkboxes: << /Yes stream /Off stream >>).
        let n_obj = self.resolver.deref(n_ref)?;
        let (n_ref, form_dict) = if let Some(d) = n_obj.as_dict() {
            if d.get(b"BBox").is_some() {
                // It's a Form XObject stream dict
                (n_ref.clone(), d.clone())
            } else {
                // State-specific appearance dict: pick the entry matching /AS.
                // For Widget annotations (checkboxes/radios), /AS determines
                // which appearance to show (e.g. /Yes = checked, /Off = unchecked).
                // When /AS is absent, default to /Off (unchecked). Only fall back
                // to the first entry for non-Widget annotations.
                let as_name = annot_dict.get_name(b"AS").unwrap_or(b"Off");
                let state_ref = match d.get(as_name) {
                    Some(r) => r,
                    None if subtype == b"Widget" => {
                        // Widget with no matching state — skip rendering
                        return Ok(());
                    }
                    None => {
                        // Non-widget: try the first entry as fallback
                        match d.entries().first().map(|(_, v)| v) {
                            Some(r) => r,
                            None => return Ok(()),
                        }
                    }
                };
                let state_obj = self.resolver.deref(state_ref)?;
                let state_dict = state_obj
                    .as_dict()
                    .ok_or(PdfError::Other("AP/N state not a stream".into()))?;
                (state_ref.clone(), state_dict.clone())
            }
        } else {
            return Err(PdfError::Other("AP/N not a dict or stream".into()));
        };

        // The appearance stream is a Form XObject. Its BBox defines the
        // coordinate space, and we need to map it to the annotation Rect.
        // BBox may be an indirect reference — resolve before accessing.
        let bbox = form_dict
            .get(b"BBox")
            .and_then(|obj| {
                let resolved = self.resolver.deref(obj).ok().unwrap_or(obj.clone());
                let a = resolved.as_array()?;
                if a.len() >= 4 {
                    Some([
                        a[0].as_f64()?,
                        a[1].as_f64()?,
                        a[2].as_f64()?,
                        a[3].as_f64()?,
                    ])
                } else {
                    None
                }
            })
            .unwrap_or([rect[0], rect[1], rect[2], rect[3]]);

        // Apply form's own matrix if present
        let form_matrix = deref_num_array(self.resolver, &form_dict, b"Matrix")
            .and_then(|v| {
                if v.len() == 6 {
                    Some(Matrix::new(v[0], v[1], v[2], v[3], v[4], v[5]))
                } else {
                    None
                }
            })
            .unwrap_or_else(Matrix::identity);

        // Build transform: map the Matrix-transformed BBox → Rect.
        // Per PDF spec 12.5.5, the form's Matrix transforms the BBox into the
        // coordinate system where the appearance was authored. We need to map
        // that transformed extent to the annotation's Rect on the page.
        let (tb0x, tb0y) = form_matrix.transform_point(bbox[0], bbox[1]);
        let (tb1x, tb1y) = form_matrix.transform_point(bbox[2], bbox[3]);
        let tbbox_w = (tb1x - tb0x).abs().max(0.001);
        let tbbox_h = (tb1y - tb0y).abs().max(0.001);
        let rect_w = (rect[2] - rect[0]).abs();
        let rect_h = (rect[3] - rect[1]).abs();
        let sx = rect_w / tbbox_w;
        let sy = rect_h / tbbox_h;
        let tx = rect[0] - tb0x.min(tb1x) * sx;
        let ty = rect[1] - tb0y.min(tb1y) * sy;
        let bbox_to_rect = Matrix::new(sx, 0.0, 0.0, sy, tx, ty);

        // Render as a Form XObject with the computed transform
        let saved_gstate = self.gstate.clone();
        let saved_stack_depth = self.gstate_stack.len();
        let saved_resources = self.resources.clone();
        let saved_mc_stack = std::mem::take(&mut self.mc_stack);
        // Set up resources from the form
        if let Some(res_obj) = form_dict.get(b"Resources")
            && let Ok(PdfObj::Dict(d)) = self.resolver.deref(res_obj)
        {
            self.resources = d;
        }

        // Apply CTM: initial page CTM → bbox_to_rect → form_matrix
        // Use the initial page CTM (not the post-content-stream CTM) because
        // annotation Rects are in page coordinates, not in whatever coordinate
        // system the content stream left behind after cm operations.
        self.gstate.ctm = self.initial_ctm.concat(&bbox_to_rect).concat(&form_matrix);

        // Update content_stream_ctm so shading patterns inside the annotation
        // use the annotation's coordinate system (not the page's).
        let saved_content_stream_ctm = self.content_stream_ctm;
        self.content_stream_ctm = self.gstate.ctm;

        // Note: no BBox clip here — appearance streams do their own internal clipping.

        // Interpret the form content
        let form_data = self.resolver.stream_data_from_obj(&n_ref)?;
        self.depth += 1;
        let _ = self.interpret_stream(&form_data);
        self.depth -= 1;

        // Restore state — truncate gstate stack to handle unbalanced q/Q in stream
        self.gstate_stack.truncate(saved_stack_depth);
        self.content_stream_ctm = saved_content_stream_ctm;
        self.resources = saved_resources;
        self.mc_stack = saved_mc_stack;
        self.gstate = saved_gstate;

        // Restore clip in display list (annotation may have modified clip state)
        self.display_list.push(DisplayElement::InitClip);
        if let Some(ref clip) = self.gstate.clip_path {
            self.display_list.push(DisplayElement::Clip {
                path: clip.clone(),
                params: ClipParams {
                    fill_rule: FillRule::NonZeroWinding,
                    ctm: Matrix::identity(),
                    stroke_params: None,
                },
            });
        }

        Ok(())
    }

    /// Synthesize an appearance for annotations that lack an /AP stream.
    /// Handles Line, PolyLine, Ink, Highlight, StrikeOut, Underline, and Squiggly.
    fn synthesize_annotation(
        &mut self,
        dict: &crate::objects::PdfDict,
        rect: &[f64; 4],
    ) -> Result<(), PdfError> {
        let subtype = dict.get_name(b"Subtype").unwrap_or(b"");

        // Extract annotation color (/C array, default black)
        let color = if let Some(c) = dict.get_array(b"C") {
            let vals: Vec<f64> = c.iter().filter_map(|o| o.as_f64()).collect();
            match vals.len() {
                1 => DeviceColor::from_gray(vals[0]),
                3 => DeviceColor::from_rgb(vals[0], vals[1], vals[2]),
                4 => DeviceColor::from_cmyk(vals[0], vals[1], vals[2], vals[3]),
                _ => DeviceColor::from_gray(0.0),
            }
        } else {
            DeviceColor::from_gray(0.0)
        };

        // Opacity
        let alpha = dict.get(b"CA").and_then(|o| o.as_f64()).unwrap_or(1.0);

        // Border width: prefer /BS dict /W, then /Border array [h_radius v_radius width]
        let border_width = dict
            .get(b"BS")
            .and_then(|bs| self.resolver.deref(bs).ok())
            .and_then(|bs| bs.as_dict().and_then(|d| d.get_f64(b"W")))
            .or_else(|| {
                dict.get_array(b"Border")
                    .and_then(|arr| arr.get(2).and_then(|o| o.as_f64()))
            })
            .unwrap_or(1.0);

        // Dash pattern from /BS /D
        let dash = dict
            .get(b"BS")
            .and_then(|bs| self.resolver.deref(bs).ok())
            .and_then(|bs| {
                let d = bs.as_dict()?;
                let style = d.get_name(b"S")?;
                if style == b"D" {
                    let arr = d
                        .get_array(b"D")
                        .map(|a| a.iter().filter_map(|o| o.as_f64()).collect::<Vec<_>>())
                        .unwrap_or_else(|| vec![3.0]);
                    Some(DashPattern {
                        array: arr,
                        offset: 0.0,
                    })
                } else {
                    None
                }
            })
            .unwrap_or_default();

        let ctm = self.initial_ctm;

        match subtype {
            b"Line" => {
                // /L [x1 y1 x2 y2]
                if let Some(l) = dict.get_array(b"L") {
                    let coords: Vec<f64> = l.iter().filter_map(|o| o.as_f64()).collect();
                    if coords.len() >= 4 {
                        let (x1, y1, x2, y2) = (coords[0], coords[1], coords[2], coords[3]);
                        let path = PsPath {
                            segments: vec![
                                PathSegment::MoveTo(x1, y1),
                                PathSegment::LineTo(x2, y2),
                            ],
                        };
                        self.display_list.push(DisplayElement::Stroke {
                            path,
                            params: StrokeParams {
                                color: color.clone(),
                                line_width: border_width,
                                line_cap: LineCap::Butt,
                                line_join: LineJoin::Miter,
                                miter_limit: 10.0,
                                dash_pattern: dash.clone(),
                                ctm,
                                stroke_adjust: false,
                                is_text_glyph: false,
                                overprint: false,
                                overprint_mode: 0,
                                opm_paired: false,
                                painted_channels: 0,
                                is_device_cmyk: false,
                                spot_color: None,
                                icc_color: None,
                                rendering_intent: 0,
                                transfer: Default::default(),
                                halftone: Default::default(),
                                bg_ucr: Default::default(),
                                alpha,
                                blend_mode: 0,
                                alpha_is_shape: false,
                            },
                        });
                    }
                }
            }
            b"PolyLine" | b"Polygon" => {
                if let Some(verts) = dict.get_array(b"Vertices") {
                    let coords: Vec<f64> = verts.iter().filter_map(|o| o.as_f64()).collect();
                    if coords.len() >= 4 {
                        let mut segs = vec![PathSegment::MoveTo(coords[0], coords[1])];
                        for pair in coords[2..].chunks_exact(2) {
                            segs.push(PathSegment::LineTo(pair[0], pair[1]));
                        }
                        if subtype == b"Polygon" {
                            segs.push(PathSegment::ClosePath);
                        }
                        let path = PsPath { segments: segs };
                        self.display_list.push(DisplayElement::Stroke {
                            path,
                            params: StrokeParams {
                                color: color.clone(),
                                line_width: border_width,
                                line_cap: LineCap::Butt,
                                line_join: LineJoin::Miter,
                                miter_limit: 10.0,
                                dash_pattern: dash.clone(),
                                ctm,
                                stroke_adjust: false,
                                is_text_glyph: false,
                                overprint: false,
                                overprint_mode: 0,
                                opm_paired: false,
                                painted_channels: 0,
                                is_device_cmyk: false,
                                spot_color: None,
                                icc_color: None,
                                rendering_intent: 0,
                                transfer: Default::default(),
                                halftone: Default::default(),
                                bg_ucr: Default::default(),
                                alpha,
                                blend_mode: 0,
                                alpha_is_shape: false,
                            },
                        });
                    }
                }
            }
            b"Ink" => {
                if let Some(ink_list) = dict.get_array(b"InkList") {
                    for stroke_obj in ink_list {
                        let stroke_arr = match stroke_obj {
                            crate::objects::PdfObj::Array(a) => a,
                            _ => continue,
                        };
                        let coords: Vec<f64> =
                            stroke_arr.iter().filter_map(|o| o.as_f64()).collect();
                        if coords.len() >= 4 {
                            let mut segs = vec![PathSegment::MoveTo(coords[0], coords[1])];
                            for pair in coords[2..].chunks_exact(2) {
                                segs.push(PathSegment::LineTo(pair[0], pair[1]));
                            }
                            let path = PsPath { segments: segs };
                            self.display_list.push(DisplayElement::Stroke {
                                path,
                                params: StrokeParams {
                                    color: color.clone(),
                                    line_width: border_width,
                                    line_cap: LineCap::Round,
                                    line_join: LineJoin::Round,
                                    miter_limit: 10.0,
                                    dash_pattern: DashPattern::default(),
                                    ctm,
                                    stroke_adjust: false,
                                    is_text_glyph: false,
                                    overprint: false,
                                    overprint_mode: 0,
                                    opm_paired: false,
                                    painted_channels: 0,
                                    is_device_cmyk: false,
                                    spot_color: None,
                                    icc_color: None,
                                    rendering_intent: 0,
                                    transfer: Default::default(),
                                    halftone: Default::default(),
                                    bg_ucr: Default::default(),
                                    alpha,
                                    blend_mode: 0,
                                    alpha_is_shape: false,
                                },
                            });
                        }
                    }
                }
            }
            b"Highlight" | b"StrikeOut" | b"Underline" | b"Squiggly" => {
                if let Some(qp) = dict.get_array(b"QuadPoints") {
                    let pts: Vec<f64> = qp.iter().filter_map(|o| o.as_f64()).collect();
                    // QuadPoints: groups of 8 (x1,y1, x2,y2, x3,y3, x4,y4)
                    // Order: top-left, top-right, bottom-left, bottom-right
                    for quad in pts.chunks_exact(8) {
                        let (x1, y1) = (quad[0], quad[1]); // top-left
                        let (x2, y2) = (quad[2], quad[3]); // top-right
                        let (x3, y3) = (quad[4], quad[5]); // bottom-left
                        let (x4, y4) = (quad[6], quad[7]); // bottom-right

                        if subtype == b"Highlight" {
                            // Fill the quad with translucent color
                            let path = PsPath {
                                segments: vec![
                                    PathSegment::MoveTo(x1, y1),
                                    PathSegment::LineTo(x2, y2),
                                    PathSegment::LineTo(x4, y4),
                                    PathSegment::LineTo(x3, y3),
                                    PathSegment::ClosePath,
                                ],
                            };
                            self.display_list.push(DisplayElement::Fill {
                                path,
                                params: FillParams {
                                    color: color.clone(),
                                    fill_rule: FillRule::NonZeroWinding,
                                    ctm,
                                    is_text_glyph: false,
                                    overprint: false,
                                    overprint_mode: 0,
                                    opm_paired: false,
                                    painted_channels: 0,
                                    is_device_cmyk: false,
                                    spot_color: None,
                                    icc_color: None,
                                    rendering_intent: 0,
                                    transfer: Default::default(),
                                    halftone: Default::default(),
                                    bg_ucr: Default::default(),
                                    alpha,
                                    blend_mode: 3, // Multiply for highlight
                                    alpha_is_shape: false,
                                },
                            });
                        } else {
                            // StrikeOut/Underline/Squiggly: draw a line
                            let (lx1, ly1, lx2, ly2) = if subtype == b"StrikeOut" {
                                // Middle of the quad
                                (
                                    (x1 + x3) / 2.0,
                                    (y1 + y3) / 2.0,
                                    (x2 + x4) / 2.0,
                                    (y2 + y4) / 2.0,
                                )
                            } else {
                                // Bottom of the quad
                                (x3, y3, x4, y4)
                            };
                            let path = PsPath {
                                segments: vec![
                                    PathSegment::MoveTo(lx1, ly1),
                                    PathSegment::LineTo(lx2, ly2),
                                ],
                            };
                            self.display_list.push(DisplayElement::Stroke {
                                path,
                                params: StrokeParams {
                                    color: color.clone(),
                                    line_width: border_width,
                                    line_cap: LineCap::Butt,
                                    line_join: LineJoin::Miter,
                                    miter_limit: 10.0,
                                    dash_pattern: DashPattern::default(),
                                    ctm,
                                    stroke_adjust: false,
                                    is_text_glyph: false,
                                    overprint: false,
                                    overprint_mode: 0,
                                    opm_paired: false,
                                    painted_channels: 0,
                                    is_device_cmyk: false,
                                    spot_color: None,
                                    icc_color: None,
                                    rendering_intent: 0,
                                    transfer: Default::default(),
                                    halftone: Default::default(),
                                    bg_ucr: Default::default(),
                                    alpha,
                                    blend_mode: 0,
                                    alpha_is_shape: false,
                                },
                            });
                        }
                    }
                }
            }
            b"Square" => {
                // Skip entirely if no border and no interior color
                let has_ic = dict.get_array(b"IC").is_some();
                if border_width < 0.001 && !has_ic {
                    return Ok(());
                }
                let path = PsPath {
                    segments: vec![
                        PathSegment::MoveTo(rect[0], rect[1]),
                        PathSegment::LineTo(rect[2], rect[1]),
                        PathSegment::LineTo(rect[2], rect[3]),
                        PathSegment::LineTo(rect[0], rect[3]),
                        PathSegment::ClosePath,
                    ],
                };
                // Fill with /IC (interior color) if present
                if let Some(ic) = dict.get_array(b"IC") {
                    let vals: Vec<f64> = ic.iter().filter_map(|o| o.as_f64()).collect();
                    let ic_color = match vals.len() {
                        1 => DeviceColor::from_gray(vals[0]),
                        3 => DeviceColor::from_rgb(vals[0], vals[1], vals[2]),
                        4 => DeviceColor::from_cmyk(vals[0], vals[1], vals[2], vals[3]),
                        _ => DeviceColor::from_gray(1.0),
                    };
                    self.display_list.push(DisplayElement::Fill {
                        path: path.clone(),
                        params: FillParams {
                            color: ic_color,
                            fill_rule: FillRule::NonZeroWinding,
                            ctm,
                            is_text_glyph: false,
                            overprint: false,
                            overprint_mode: 0,
                            opm_paired: false,
                            painted_channels: 0,
                            is_device_cmyk: false,
                            spot_color: None,
                            icc_color: None,
                            rendering_intent: 0,
                            transfer: Default::default(),
                            halftone: Default::default(),
                            bg_ucr: Default::default(),
                            alpha,
                            blend_mode: 0,
                            alpha_is_shape: false,
                        },
                    });
                }
                if border_width < 0.001 {
                    return Ok(());
                }
                self.display_list.push(DisplayElement::Stroke {
                    path,
                    params: StrokeParams {
                        color,
                        line_width: border_width,
                        line_cap: LineCap::Butt,
                        line_join: LineJoin::Miter,
                        miter_limit: 10.0,
                        dash_pattern: dash,
                        ctm,
                        stroke_adjust: false,
                        is_text_glyph: false,
                        overprint: false,
                        overprint_mode: 0,
                        opm_paired: false,
                        painted_channels: 0,
                        is_device_cmyk: false,
                        spot_color: None,
                        icc_color: None,
                        rendering_intent: 0,
                        transfer: Default::default(),
                        halftone: Default::default(),
                        bg_ucr: Default::default(),
                        alpha,
                        blend_mode: 0,
                        alpha_is_shape: false,
                    },
                });
            }
            b"Circle" => {
                let has_ic = dict.get_array(b"IC").is_some();
                if border_width < 0.001 && !has_ic {
                    return Ok(());
                }
                // Approximate circle/ellipse with Bezier curves
                let cx = (rect[0] + rect[2]) / 2.0;
                let cy = (rect[1] + rect[3]) / 2.0;
                let rx = (rect[2] - rect[0]) / 2.0;
                let ry = (rect[3] - rect[1]) / 2.0;
                let k = 0.5522847498; // magic number for circular Bezier approximation
                let path = PsPath {
                    segments: vec![
                        PathSegment::MoveTo(cx + rx, cy),
                        PathSegment::CurveTo {
                            x1: cx + rx,
                            y1: cy + ry * k,
                            x2: cx + rx * k,
                            y2: cy + ry,
                            x3: cx,
                            y3: cy + ry,
                        },
                        PathSegment::CurveTo {
                            x1: cx - rx * k,
                            y1: cy + ry,
                            x2: cx - rx,
                            y2: cy + ry * k,
                            x3: cx - rx,
                            y3: cy,
                        },
                        PathSegment::CurveTo {
                            x1: cx - rx,
                            y1: cy - ry * k,
                            x2: cx - rx * k,
                            y2: cy - ry,
                            x3: cx,
                            y3: cy - ry,
                        },
                        PathSegment::CurveTo {
                            x1: cx + rx * k,
                            y1: cy - ry,
                            x2: cx + rx,
                            y2: cy - ry * k,
                            x3: cx + rx,
                            y3: cy,
                        },
                        PathSegment::ClosePath,
                    ],
                };
                if let Some(ic) = dict.get_array(b"IC") {
                    let vals: Vec<f64> = ic.iter().filter_map(|o| o.as_f64()).collect();
                    let ic_color = match vals.len() {
                        1 => DeviceColor::from_gray(vals[0]),
                        3 => DeviceColor::from_rgb(vals[0], vals[1], vals[2]),
                        4 => DeviceColor::from_cmyk(vals[0], vals[1], vals[2], vals[3]),
                        _ => DeviceColor::from_gray(1.0),
                    };
                    self.display_list.push(DisplayElement::Fill {
                        path: path.clone(),
                        params: FillParams {
                            color: ic_color,
                            fill_rule: FillRule::NonZeroWinding,
                            ctm,
                            is_text_glyph: false,
                            overprint: false,
                            overprint_mode: 0,
                            opm_paired: false,
                            painted_channels: 0,
                            is_device_cmyk: false,
                            spot_color: None,
                            icc_color: None,
                            rendering_intent: 0,
                            transfer: Default::default(),
                            halftone: Default::default(),
                            bg_ucr: Default::default(),
                            alpha,
                            blend_mode: 0,
                            alpha_is_shape: false,
                        },
                    });
                }
                if border_width < 0.001 {
                    return Ok(());
                }
                self.display_list.push(DisplayElement::Stroke {
                    path,
                    params: StrokeParams {
                        color,
                        line_width: border_width,
                        line_cap: LineCap::Butt,
                        line_join: LineJoin::Miter,
                        miter_limit: 10.0,
                        dash_pattern: dash,
                        ctm,
                        stroke_adjust: false,
                        is_text_glyph: false,
                        overprint: false,
                        overprint_mode: 0,
                        opm_paired: false,
                        painted_channels: 0,
                        is_device_cmyk: false,
                        spot_color: None,
                        icc_color: None,
                        rendering_intent: 0,
                        transfer: Default::default(),
                        halftone: Default::default(),
                        bg_ucr: Default::default(),
                        alpha,
                        blend_mode: 0,
                        alpha_is_shape: false,
                    },
                });
            }
            _ => {
                // Unsupported annotation type without AP — skip silently
            }
        }

        Ok(())
    }

    /// Interpret content stream bytes (can be called recursively for Form XObjects).
    fn interpret_stream(&mut self, data: &[u8]) -> Result<(), PdfError> {
        // Isolate the operand stack from any caller.  This matters for the
        // recursive entries (Form XObjects, tiling patterns, Type 3 glyphs,
        // soft-mask groups), which are reached via dispatch_operator while
        // the parent's operand stack still has the operator's own operand
        // (e.g. the `/F1` for `Do`) on it.  Without this, the parent operand
        // would be seen by the first operator in the nested stream and
        // (because of the operand-count guard in dispatch_operator) silently
        // drop it.  See circ_compare.pdf reproduction for the original bug.
        let saved_operand_stack = std::mem::take(&mut self.operand_stack);
        let result = self.interpret_stream_inner(data);
        self.operand_stack = saved_operand_stack;
        result
    }

    fn interpret_stream_inner(&mut self, data: &[u8]) -> Result<(), PdfError> {
        let mut lexer = Lexer::new(data);
        // Tracks whether the previous token was a number whose terminating
        // byte was *not* whitespace.  Used to detect lenient lexing of
        // sequences like `5f` (= `5 f`), where the painter is glued to a
        // preceding number with no separator.  pdf.js, GhostScript, hayro,
        // Ocular, and Firefox all interpret these as `<number> <operator>`.
        let mut prev_token_was_glued_number = false;
        loop {
            // Capture position before next_token so we can detect whether the
            // upcoming token is glued to the previous one (no whitespace
            // separator).  If the previous token was a number that ended on a
            // non-whitespace byte, this token is glued to it.
            let pos_before = lexer.pos();
            let glued_to_prev_number = prev_token_was_glued_number
                && pos_before < data.len()
                && !is_whitespace_byte(data[pos_before]);
            let tok = match lexer.next_token() {
                Ok(t) => t,
                Err(_) => {
                    prev_token_was_glued_number = false;
                    continue;
                }
            };
            // Default: clear "glued number" flag.  Set it again below for
            // numeric tokens that ended on a non-whitespace byte.
            prev_token_was_glued_number = false;
            match tok {
                Token::Eof => break,
                Token::Int(n) => {
                    self.operand_stack.push(Operand::Int(n));
                    let p = lexer.pos();
                    prev_token_was_glued_number = p < data.len() && !is_whitespace_byte(data[p]);
                }
                Token::Real(f) => {
                    self.operand_stack.push(Operand::Real(f));
                    let p = lexer.pos();
                    prev_token_was_glued_number = p < data.len() && !is_whitespace_byte(data[p]);
                }
                Token::Name(n) => self.operand_stack.push(Operand::Name(n)),
                Token::LitString(s) | Token::HexString(s) => {
                    self.operand_stack.push(Operand::Str(s));
                }
                Token::Bool(b) => self.operand_stack.push(Operand::Bool(b)),
                Token::ArrayBegin => {
                    let arr = Self::parse_inline_array(&mut lexer)?;
                    self.operand_stack.push(Operand::Array(arr));
                }
                Token::DictBegin => {
                    let dict = crate::lexer::parse_dict_body(&mut lexer)?;
                    self.operand_stack.push(Operand::Dict(dict));
                }
                Token::Keyword(kw) => {
                    // Check for operator suffixes:
                    // * suffix: f*, B*, b*, W*, T*
                    // digit suffix: d0, d1 (Type 3 glyph operators)
                    let op = if matches!(kw.as_slice(), b"f" | b"B" | b"b" | b"W" | b"T") {
                        let p = lexer.pos();
                        if p < data.len() && data[p] == b'*' {
                            lexer.set_pos(p + 1);
                            let mut combined = kw;
                            combined.push(b'*');
                            combined
                        } else {
                            kw
                        }
                    } else if kw == b"d" {
                        let p = lexer.pos();
                        if p < data.len() && (data[p] == b'0' || data[p] == b'1') {
                            lexer.set_pos(p + 1);
                            let mut combined = kw;
                            combined.push(data[p]);
                            combined
                        } else {
                            kw
                        }
                    } else {
                        kw
                    };

                    if op == b"BI" {
                        self.handle_inline_image(&mut lexer)?;
                    } else if let Err(_e) = self.dispatch_operator(&op, glued_to_prev_number) {
                    }
                    self.operand_stack.clear();
                }
                Token::DictEnd | Token::ArrayEnd => {
                    // Stray delimiters — ignore
                }
            }
        }
        Ok(())
    }

    /// Parse an inline array from the content stream.
    ///
    /// Nesting is capped at [`MAX_OBJECT_DEPTH`]: this is a recursive-descent
    /// parser, so an operand like `[[[[…` in a crafted content stream would
    /// otherwise exhaust the native stack and abort the process.
    fn parse_inline_array(lexer: &mut Lexer) -> Result<Vec<PdfObj>, PdfError> {
        Self::parse_inline_array_at_depth(lexer, 1)
    }

    /// [`Self::parse_inline_array`], entered at an explicit nesting depth.
    ///
    /// `depth` counts this array itself, matching the convention used by
    /// [`crate::lexer::parse_dict_body_at_depth`].
    fn parse_inline_array_at_depth(lexer: &mut Lexer, depth: u32) -> Result<Vec<PdfObj>, PdfError> {
        if depth > MAX_OBJECT_DEPTH {
            return Err(PdfError::NestingTooDeep {
                context: "content-stream array",
                limit: MAX_OBJECT_DEPTH,
            });
        }
        let mut elems = Vec::new();
        loop {
            let tok = lexer.next_token()?;
            match tok {
                Token::ArrayEnd | Token::Eof => break,
                Token::Int(n) => elems.push(PdfObj::Int(n)),
                Token::Real(f) => elems.push(PdfObj::Real(f)),
                Token::Name(n) => elems.push(PdfObj::Name(n)),
                Token::LitString(s) | Token::HexString(s) => elems.push(PdfObj::Str(s)),
                Token::Bool(b) => elems.push(PdfObj::Bool(b)),
                Token::ArrayBegin => {
                    // A nested array past the cap yields an error rather than
                    // another frame; skip it and keep scanning for `]` so the
                    // surrounding operand stream stays in sync.
                    match Self::parse_inline_array_at_depth(lexer, depth + 1) {
                        Ok(sub) => elems.push(PdfObj::Array(sub)),
                        Err(_) => continue,
                    }
                }
                Token::DictBegin => {
                    let d = crate::lexer::parse_dict_body_at_depth(lexer, depth + 1)
                        .unwrap_or_default();
                    elems.push(PdfObj::Dict(d));
                }
                Token::Keyword(ref kw) if kw == b"null" => {
                    elems.push(PdfObj::Null);
                }
                _ => {}
            }
        }
        Ok(elems)
    }

    /// Dispatch a PDF content stream operator.
    ///
    /// `glued_to_prev_number` is true when the operator token in the source
    /// stream was immediately preceded by a number with no whitespace
    /// separator (e.g. `5f`).  Lenient parsers (pdf.js, GhostScript, hayro,
    /// Ocular, Firefox) all interpret such sequences as `<number> <operator>`,
    /// and this flag lets us bypass the operand-count guard so the painter
    /// still runs.  Without that escape hatch, the guard would silently drop
    /// the painter, leaving the path unpainted (issue994.pdf).
    fn dispatch_operator(&mut self, op: &[u8], glued_to_prev_number: bool) -> Result<(), PdfError> {
        // Path construction and painting operators have fixed operand counts.
        // Excess operands indicate garbled content stream data (e.g. from
        // corrupt FlateDecode) — skip the operator to avoid rendering with
        // wrong coordinates.  The operand stack is cleared after every
        // dispatch, so any values present were pushed since the last operator.
        let expected_args: i32 = match op {
            b"m" | b"l" => 2,
            b"v" | b"y" | b"re" => 4,
            b"c" => 6,
            b"h" | b"S" | b"s" | b"f" | b"F" | b"f*" | b"B" | b"B*" | b"b" | b"b*" | b"n" => 0,
            _ => -1, // no check
        };
        if expected_args >= 0
            && self.operand_stack.len() > expected_args as usize
            && !glued_to_prev_number
        {
            return Ok(());
        }

        // Skip text operators inside a culled BT/ET block (offscreen in large forms)
        if self.bt_culled {
            if op == b"ET" {
                self.bt_culled = false;
                self.in_text = false;
            }
            self.operand_stack.clear();
            return Ok(());
        }

        match op {
            // Graphics state
            b"q" => self.op_q(),
            b"Q" => self.op_big_q(),
            b"cm" => self.op_cm(),
            b"w" => self.op_w(),
            b"J" => self.op_big_j(),
            b"j" => self.op_j(),
            b"M" => self.op_big_m(),
            b"d" => self.op_d(),
            b"ri" => self.op_ri(),
            b"i" => self.op_i(),
            b"gs" => self.op_gs(),

            // Path construction
            b"m" => self.op_m(),
            b"l" => self.op_l(),
            b"c" => self.op_c(),
            b"v" => self.op_v(),
            b"y" => self.op_y(),
            b"h" => self.op_h(),
            b"re" => self.op_re(),

            // Path painting
            b"S" => self.op_big_s(),
            b"s" => self.op_small_s(),
            b"f" | b"F" => self.op_f(),
            b"f*" => self.op_f_star(),
            b"B" => self.op_big_b(),
            b"B*" => self.op_big_b_star(),
            b"b" => self.op_small_b(),
            b"b*" => self.op_small_b_star(),
            b"n" => self.op_n(),

            // Clipping
            b"W" => self.op_big_w(),
            b"W*" => self.op_big_w_star(),

            // Color - device
            b"G" if !self.d1_color_suppressed => self.op_big_g(),
            b"g" if !self.d1_color_suppressed => self.op_small_g(),
            b"RG" if !self.d1_color_suppressed => self.op_big_rg(),
            b"rg" if !self.d1_color_suppressed => self.op_small_rg(),
            b"K" if !self.d1_color_suppressed => self.op_big_k(),
            b"k" if !self.d1_color_suppressed => self.op_small_k(),
            b"G" | b"g" | b"RG" | b"rg" | b"K" | b"k" => Ok(()),

            // Color - general
            b"CS" if !self.d1_color_suppressed => self.op_big_cs(),
            b"cs" if !self.d1_color_suppressed => self.op_small_cs(),
            b"SC" | b"SCN" if !self.d1_color_suppressed => self.op_sc_stroke(),
            b"sc" | b"scn" if !self.d1_color_suppressed => self.op_sc_fill(),
            b"CS" | b"cs" | b"SC" | b"SCN" | b"sc" | b"scn" => Ok(()),

            // Text operators
            b"BT" => {
                self.in_text = true;
                self.gstate.text_matrix = Matrix::identity();
                self.gstate.text_line_matrix = Matrix::identity();
                Ok(())
            }
            b"ET" => {
                self.in_text = false;
                // Apply accumulated text clip path (from rendering modes 4-7)
                if let Some(clip_path) = self.text_clip_path.take()
                    && !clip_path.is_empty()
                {
                    self.display_list.push(DisplayElement::Clip {
                        path: clip_path.clone(),
                        params: ClipParams {
                            fill_rule: FillRule::NonZeroWinding,
                            ctm: Matrix::identity(),
                            stroke_params: None,
                        },
                    });
                    // Track in graphics state so Q/grestore can undo it
                    self.gstate
                        .clip_stack
                        .push((clip_path.clone(), FillRule::NonZeroWinding));
                    self.gstate.clip_path = Some(clip_path);
                    self.gstate.clip_path_version += 1;
                }
                Ok(())
            }
            b"Tf" => self.op_tf(),
            b"Tc" => {
                self.gstate.char_spacing = self.pop_number()?;
                Ok(())
            }
            b"Tw" => {
                self.gstate.word_spacing = self.pop_number()?;
                Ok(())
            }
            b"TL" => {
                self.gstate.text_leading = self.pop_number()?;
                Ok(())
            }
            b"Tr" => {
                self.gstate.text_rendering_mode = self.pop_number()? as i32;
                Ok(())
            }
            b"Ts" => {
                self.gstate.text_rise = self.pop_number()?;
                Ok(())
            }
            b"Tz" => {
                self.gstate.horizontal_scaling = self.pop_number()? / 100.0;
                Ok(())
            }
            b"Td" => self.op_td(),
            b"TD" => self.op_big_td(),
            b"Tm" => self.op_tm(),
            b"T*" => self.op_t_star(),
            b"Tj" => self.op_tj(),
            b"TJ" => self.op_big_tj(),
            b"'" => self.op_quote(),
            b"\"" => self.op_dblquote(),

            // XObject
            b"Do" => self.op_do(),

            // Shading
            b"sh" => self.op_sh(),

            // Marked content with optional content group (OCG) support.
            // BDC/BMC open a section that must be closed by EMC; MP/DP are
            // single-shot marked points with no closing operator.
            b"BMC" => {
                self.operand_stack.pop();
                self.mc_stack.push(MarkedContentFrame::Other);
                Ok(())
            }
            b"MP" => {
                self.operand_stack.pop();
                Ok(())
            }
            b"DP" => {
                self.operand_stack.pop();
                self.operand_stack.pop();
                Ok(())
            }
            b"BDC" => self.op_bdc(),
            b"EMC" => {
                if let Some(MarkedContentFrame::Ocg {
                    parent_list,
                    visibility,
                }) = self.mc_stack.pop()
                {
                    let ocg_list = std::mem::replace(&mut self.display_list, parent_list);
                    self.display_list.push(DisplayElement::OcgGroup {
                        elements: ocg_list,
                        visibility,
                    });
                }
                Ok(())
            }

            // Type 3 glyph operators (width/cache — we use Widths array instead)
            b"d0" => Ok(()),
            b"d1" => {
                // d1: Type 3 glyph with colored content disabled. Per PDF spec
                // 9.6.5, the glyph description shall be treated as a single
                // mask whose source colour is the current colour. Color
                // operators inside the glyph are ignored, AND any path painting
                // operation (fill or stroke) inside the glyph must use the
                // single text color — which for the default text rendering
                // mode 0 is the fill color. Force the stroke color (and any
                // patterns) to match the fill color so a glyph procedure that
                // calls `S` or `b` paints with the fill color, not whatever
                // stroke color happened to be set on the page.
                self.d1_color_suppressed = true;
                self.gstate.stroke_color = self.gstate.fill_color.clone();
                self.gstate.stroke_color_space = self.gstate.fill_color_space.clone();
                self.gstate.stroke_pattern = None;
                self.gstate.stroke_shading_pattern = None;
                self.gstate.stroke_painted_channels = self.gstate.fill_painted_channels;
                self.gstate.stroke_is_device_cmyk = self.gstate.fill_is_device_cmyk;
                self.gstate.stroke_is_none = self.gstate.fill_is_none;
                Ok(())
            }

            // Compatibility (no-op)
            b"BX" | b"EX" => Ok(()),

            _ => {
                // Unknown operator — ignore
                Ok(())
            }
        }
    }

    // === Helper methods ===

    /// Pop one number from the operand stack.
    fn pop_number(&self) -> Result<f64, PdfError> {
        self.operand_stack
            .last()
            .and_then(|o| o.as_f64())
            .ok_or(PdfError::Other("expected number on operand stack".into()))
    }

    /// Get N numbers from the end of the operand stack.
    fn get_numbers(&self, n: usize) -> Result<Vec<f64>, PdfError> {
        let len = self.operand_stack.len();
        if len < n {
            return Err(PdfError::Other(format!("need {n} operands, have {len}")));
        }
        let mut nums = Vec::with_capacity(n);
        for i in (len - n)..len {
            nums.push(
                self.operand_stack[i]
                    .as_f64()
                    .ok_or(PdfError::Other("expected number".into()))?,
            );
        }
        Ok(nums)
    }

    /// Transform a point through the current CTM to device space.
    fn transform(&self, x: f64, y: f64) -> (f64, f64) {
        self.gstate.ctm.transform_point(x, y)
    }

    /// Take the current path and reset it.
    fn take_path(&mut self) -> PsPath {
        let path = std::mem::take(&mut self.current_path);
        self.current_point = None;
        self.subpath_start = None;
        path
    }

    /// Apply pending clip if set, then clear it.
    fn apply_pending_clip(&mut self) {
        if let Some((path, fill_rule)) = self.gstate.pending_clip.take() {
            // A clip path with only MoveTo segments (no lines, curves, or close)
            // has zero area — it clips everything out. Replace with an empty rect
            // so the renderer produces a zero-area clip instead of treating the
            // degenerate path as no-op.
            let has_drawing_segments = path.segments.iter().any(|s| {
                matches!(
                    s,
                    PathSegment::LineTo(..) | PathSegment::CurveTo { .. } | PathSegment::ClosePath
                )
            });
            // A path with MoveTo but no lines/curves has zero area — clip everything.
            // An empty path (no segments at all) is a no-op — skip the clip entirely.
            let has_moveto = path
                .segments
                .iter()
                .any(|s| matches!(s, PathSegment::MoveTo(..)));
            if !has_drawing_segments && has_moveto {
                // Degenerate path (only MoveTo): create a zero-area clip
                let mut empty = PsPath::new();
                empty.segments.push(PathSegment::MoveTo(0.0, 0.0));
                empty.segments.push(PathSegment::LineTo(0.0, 0.0));
                empty.segments.push(PathSegment::ClosePath);
                self.display_list.push(DisplayElement::Clip {
                    path: empty.clone(),
                    params: ClipParams {
                        fill_rule,
                        ctm: Matrix::identity(),
                        stroke_params: None,
                    },
                });
                self.gstate.clip_stack.push((empty.clone(), fill_rule));
                self.gstate.clip_path = Some(empty);
                self.gstate.clip_path_version += 1;
                return;
            }
            if !has_drawing_segments {
                // Empty path: no-op, don't change clip
                return;
            }
            let clip_path = path;
            self.display_list.push(DisplayElement::Clip {
                path: clip_path.clone(),
                params: ClipParams {
                    fill_rule,
                    ctm: Matrix::identity(),
                    stroke_params: None,
                },
            });
            // Track the clip for restoring on Q
            self.gstate.clip_stack.push((clip_path.clone(), fill_rule));
            self.gstate.clip_path = Some(clip_path);
            self.gstate.clip_path_version += 1;
        }
    }

    // === Graphics state operators ===

    fn op_q(&mut self) -> Result<(), PdfError> {
        self.gstate_stack.push(self.gstate.clone());
        Ok(())
    }

    fn op_big_q(&mut self) -> Result<(), PdfError> {
        if let Some(saved) = self.gstate_stack.pop() {
            // Flush soft mask scope if the SMask changed during this q/Q block.
            // Compare the smask_gen counter: if it changed, a new SMask was set
            // inside this block and the scope should be flushed. This correctly
            // handles nested masks inside resolve_soft_mask where both current
            // and saved gstates have a soft_mask but they're different.
            if self.soft_mask_scope.is_some() && self.gstate.smask_gen != saved.smask_gen {
                self.flush_soft_mask();
                self.nested_mask_flush_count += 1;
            }

            let old_clip_version = self.gstate.clip_path_version;
            let old_font_name = std::mem::take(&mut self.gstate.text_font_name);
            self.gstate = saved;
            // If clip changed during the q/Q block, restore it by
            // replaying the full clip stack (not just the last clip).
            if self.gstate.clip_path_version != old_clip_version {
                self.restore_clip_from_stack();
            }
            // Re-resolve current_font if the restored font name differs
            if self.gstate.text_font_name != old_font_name && !self.gstate.text_font_name.is_empty()
            {
                let name = self.gstate.text_font_name.clone();
                self.resolve_current_font(&name);
            }
        }
        Ok(())
    }

    /// Restore the clip state by pushing InitClip + replaying all clips from clip_stack.
    fn restore_clip_from_stack(&mut self) {
        self.display_list.push(DisplayElement::InitClip);
        for (clip, fill_rule) in &self.gstate.clip_stack {
            self.display_list.push(DisplayElement::Clip {
                path: clip.clone(),
                params: ClipParams {
                    fill_rule: *fill_rule,
                    ctm: Matrix::identity(),
                    stroke_params: None,
                },
            });
        }
    }

    fn op_cm(&mut self) -> Result<(), PdfError> {
        let n = self.get_numbers(6)?;
        let m = Matrix::new(n[0], n[1], n[2], n[3], n[4], n[5]);
        // PDF cm: CTM = CTM × M (pre-multiply, same as PS concat)
        self.gstate.ctm = self.gstate.ctm.concat(&m);
        Ok(())
    }

    fn op_w(&mut self) -> Result<(), PdfError> {
        self.gstate.line_width = self.pop_number()?;
        Ok(())
    }

    fn op_big_j(&mut self) -> Result<(), PdfError> {
        let cap = self.pop_number()? as i32;
        if let Some(lc) = LineCap::from_i32(cap) {
            self.gstate.line_cap = lc;
        }
        Ok(())
    }

    fn op_j(&mut self) -> Result<(), PdfError> {
        let join = self.pop_number()? as i32;
        if let Some(lj) = LineJoin::from_i32(join) {
            self.gstate.line_join = lj;
        }
        Ok(())
    }

    fn op_big_m(&mut self) -> Result<(), PdfError> {
        self.gstate.miter_limit = self.pop_number()?;
        Ok(())
    }

    fn op_d(&mut self) -> Result<(), PdfError> {
        // Operands: array offset
        let len = self.operand_stack.len();
        if len < 2 {
            return Ok(());
        }
        let offset = self.operand_stack[len - 1].as_f64().unwrap_or(0.0);
        let array = match &self.operand_stack[len - 2] {
            Operand::Array(arr) => arr.iter().filter_map(|o| o.as_f64()).collect::<Vec<_>>(),
            _ => Vec::new(),
        };
        self.gstate.dash_pattern = DashPattern { array, offset };
        Ok(())
    }

    fn op_ri(&mut self) -> Result<(), PdfError> {
        // Pop the intent name and translate to the gstate byte code used
        // by the ICC chain dispatch (matches `IccCache::intent_from_pdf_byte`).
        let Some(top) = self.operand_stack.pop() else {
            return Ok(());
        };
        let Some(name) = top.as_name() else {
            return Ok(());
        };
        self.gstate.rendering_intent = match name {
            b"Perceptual" => 0,
            b"RelativeColorimetric" => 1,
            b"Saturation" => 2,
            b"AbsoluteColorimetric" => 3,
            _ => 0,
        };
        Ok(())
    }

    fn op_i(&mut self) -> Result<(), PdfError> {
        self.gstate.flatness = self.pop_number()?;
        Ok(())
    }

    fn op_gs(&mut self) -> Result<(), PdfError> {
        let name = self
            .operand_stack
            .last()
            .and_then(|o| o.as_name())
            .ok_or(PdfError::Other("gs: expected name".into()))?
            .to_vec();
        self.apply_ext_gstate(&name)
    }

    // === Path construction operators ===

    fn op_m(&mut self) -> Result<(), PdfError> {
        let n = self.get_numbers(2)?;
        let (dx, dy) = self.transform(n[0], n[1]);
        self.current_path.segments.push(PathSegment::MoveTo(dx, dy));
        self.current_point = Some((dx, dy));
        self.subpath_start = Some((dx, dy));
        Ok(())
    }

    fn op_l(&mut self) -> Result<(), PdfError> {
        let n = self.get_numbers(2)?;
        let (dx, dy) = self.transform(n[0], n[1]);
        self.current_path.segments.push(PathSegment::LineTo(dx, dy));
        self.current_point = Some((dx, dy));
        Ok(())
    }

    fn op_c(&mut self) -> Result<(), PdfError> {
        let n = self.get_numbers(6)?;
        let (x1, y1) = self.transform(n[0], n[1]);
        let (x2, y2) = self.transform(n[2], n[3]);
        let (x3, y3) = self.transform(n[4], n[5]);
        self.current_path.segments.push(PathSegment::CurveTo {
            x1,
            y1,
            x2,
            y2,
            x3,
            y3,
        });
        self.current_point = Some((x3, y3));
        Ok(())
    }

    fn op_v(&mut self) -> Result<(), PdfError> {
        let n = self.get_numbers(4)?;
        let (x1, y1) = self.current_point.unwrap_or((0.0, 0.0));
        let (x2, y2) = self.transform(n[0], n[1]);
        let (x3, y3) = self.transform(n[2], n[3]);
        self.current_path.segments.push(PathSegment::CurveTo {
            x1,
            y1,
            x2,
            y2,
            x3,
            y3,
        });
        self.current_point = Some((x3, y3));
        Ok(())
    }

    fn op_y(&mut self) -> Result<(), PdfError> {
        let n = self.get_numbers(4)?;
        let (x1, y1) = self.transform(n[0], n[1]);
        let (x3, y3) = self.transform(n[2], n[3]);
        self.current_path.segments.push(PathSegment::CurveTo {
            x1,
            y1,
            x2: x3,
            y2: y3,
            x3,
            y3,
        });
        self.current_point = Some((x3, y3));
        Ok(())
    }

    fn op_h(&mut self) -> Result<(), PdfError> {
        self.current_path.segments.push(PathSegment::ClosePath);
        if let Some(start) = self.subpath_start {
            self.current_point = Some(start);
        }
        Ok(())
    }

    fn op_re(&mut self) -> Result<(), PdfError> {
        let n = self.get_numbers(4)?;
        let (x, y, w, h) = (n[0], n[1], n[2], n[3]);
        // re builds: m x y, l x+w y, l x+w y+h, l x y+h, h
        let p0 = self.transform(x, y);
        let p1 = self.transform(x + w, y);
        let p2 = self.transform(x + w, y + h);
        let p3 = self.transform(x, y + h);
        self.current_path
            .segments
            .push(PathSegment::MoveTo(p0.0, p0.1));
        self.current_path
            .segments
            .push(PathSegment::LineTo(p1.0, p1.1));
        self.current_path
            .segments
            .push(PathSegment::LineTo(p2.0, p2.1));
        self.current_path
            .segments
            .push(PathSegment::LineTo(p3.0, p3.1));
        self.current_path.segments.push(PathSegment::ClosePath);
        self.current_point = Some(p0);
        self.subpath_start = Some(p0);
        Ok(())
    }

    // === Path painting operators ===

    fn op_big_s(&mut self) -> Result<(), PdfError> {
        // S: stroke
        let path = self.take_path();
        if !path.is_empty() {
            self.emit_stroke(path);
        }
        self.apply_pending_clip();
        Ok(())
    }

    fn op_small_s(&mut self) -> Result<(), PdfError> {
        // s: close and stroke
        self.op_h()?;
        self.op_big_s()
    }

    fn op_f(&mut self) -> Result<(), PdfError> {
        // f/F: fill (non-zero winding)
        let path = self.take_path();
        if !path.is_empty() {
            self.emit_fill(path, FillRule::NonZeroWinding);
        }
        self.apply_pending_clip();
        Ok(())
    }

    fn op_f_star(&mut self) -> Result<(), PdfError> {
        // f*: fill (even-odd)
        let path = self.take_path();
        if !path.is_empty() {
            self.emit_fill(path, FillRule::EvenOdd);
        }
        self.apply_pending_clip();
        Ok(())
    }

    fn op_big_b(&mut self) -> Result<(), PdfError> {
        // B: fill (non-zero) + stroke
        let path = self.take_path();
        if !path.is_empty() {
            self.emit_fill_stroke(path, FillRule::NonZeroWinding);
        }
        self.apply_pending_clip();
        Ok(())
    }

    fn op_big_b_star(&mut self) -> Result<(), PdfError> {
        // B*: fill (even-odd) + stroke
        let path = self.take_path();
        if !path.is_empty() {
            self.emit_fill_stroke(path, FillRule::EvenOdd);
        }
        self.apply_pending_clip();
        Ok(())
    }

    fn op_small_b(&mut self) -> Result<(), PdfError> {
        // b: close, fill (non-zero), stroke
        self.op_h()?;
        self.op_big_b()
    }

    fn op_small_b_star(&mut self) -> Result<(), PdfError> {
        // b*: close, fill (even-odd), stroke
        self.op_h()?;
        self.op_big_b_star()
    }

    /// Emit a fill — either a pattern fill or a regular solid fill.
    fn emit_fill(&mut self, path: PsPath, fill_rule: FillRule) {
        if let Some(shading_box) = self.gstate.fill_shading_pattern.clone() {
            // PatternType 2 (shading pattern): clip to fill path, then emit shading.
            // Wrap in a Group to scope the clip — otherwise each shading fill would
            // permanently narrow the clip region, hiding subsequent fills.
            let bbox = path_device_bbox(&path);
            let mut group_dl = DisplayList::new();
            group_dl.push(DisplayElement::Clip {
                path,
                params: ClipParams {
                    fill_rule,
                    ctm: Matrix::identity(),
                    stroke_params: None,
                },
            });
            for elem in shading_box.0.elements() {
                group_dl.push(elem.clone());
            }
            self.display_list.push(DisplayElement::Group {
                elements: group_dl,
                params: GroupParams {
                    bbox,
                    isolated: true,
                    knockout: false,
                    blend_mode: self.gstate.blend_mode,
                    alpha: self.gstate.fill_alpha,
                    color_space: stet_graphics::display_list::GroupColorSpace::Inherited,
                },
            });
        } else if let Some(pattern) = self.gstate.fill_pattern.clone() {
            self.display_list.push(DisplayElement::PatternFill {
                params: PatternFillParams {
                    path,
                    fill_rule,
                    tile: pattern.tile,
                    pattern_matrix: pattern.pattern_matrix,
                    bbox: pattern.bbox,
                    xstep: pattern.x_step,
                    ystep: pattern.y_step,
                    paint_type: pattern.paint_type,
                    underlying_color: if pattern.paint_type == 2 {
                        Some(self.gstate.fill_color.clone())
                    } else {
                        None
                    },
                    pattern_id: pattern.pattern_id,
                    device_space_tile: false,
                    flip_tile_y: false,
                    stroke_params: None,
                    overprint_mode: if self.gstate.overprint {
                        self.gstate.overprint_mode
                    } else {
                        0
                    },
                },
            });
        } else {
            self.display_list.push(DisplayElement::Fill {
                path,
                params: self.gstate.fill_params(fill_rule),
            });
        }
    }

    /// Emit a stroke with proper CTM-aware line width.
    ///
    /// Paths are stored in device space, but strokes need to be applied in user
    /// space for correct anisotropic scaling (non-uniform CTMs make circles into
    /// ellipses, and the stroke width should follow that transformation).
    /// We inverse-transform the path back to user space and pass the CTM to the
    /// renderer so it can apply the stroke correctly.
    fn emit_stroke(&mut self, path: PsPath) {
        let ctm = self.gstate.ctm;
        // Inverse-transform path from device space back to user space
        let user_path = if let Some(inv) = ctm.invert() {
            path.transform(&inv)
        } else {
            path.clone()
        };

        // Tiling pattern stroke: emit PatternFill with stroke_params so the
        // renderer expands the centerline path to a stroke outline for masking.
        if let Some(pattern) = self.gstate.stroke_pattern.clone() {
            let mut sp = self.gstate.stroke_params_with_ctm();
            sp.ctm = ctm;
            self.display_list.push(DisplayElement::PatternFill {
                params: PatternFillParams {
                    path: user_path,
                    fill_rule: FillRule::NonZeroWinding,
                    tile: pattern.tile,
                    pattern_matrix: pattern.pattern_matrix,
                    bbox: pattern.bbox,
                    xstep: pattern.x_step,
                    ystep: pattern.y_step,
                    paint_type: pattern.paint_type,
                    underlying_color: if pattern.paint_type == 2 {
                        Some(self.gstate.stroke_color.clone())
                    } else {
                        None
                    },
                    pattern_id: pattern.pattern_id,
                    device_space_tile: false,
                    flip_tile_y: false,
                    stroke_params: Some(sp),
                    overprint_mode: if self.gstate.overprint {
                        self.gstate.overprint_mode
                    } else {
                        0
                    },
                },
            });
            return;
        }

        // Shading pattern stroke: clip to stroke outline, then emit shading.
        if let Some(shading_box) = self.gstate.stroke_shading_pattern.clone() {
            let mut sp = self.gstate.stroke_params_with_ctm();
            sp.ctm = ctm;
            // Expand the device-space bbox by half the stroke width to account
            // for the area the stroke outline covers beyond the centerline.
            let mut bbox = path_device_bbox(&path);
            let scale = self.gstate.ctm_scale_factor();
            let half_w = self.gstate.line_width * scale * 0.5;
            bbox[0] -= half_w;
            bbox[1] -= half_w;
            bbox[2] += half_w;
            bbox[3] += half_w;
            let mut group_dl = DisplayList::new();
            group_dl.push(DisplayElement::Clip {
                path: user_path,
                params: ClipParams {
                    fill_rule: FillRule::NonZeroWinding,
                    ctm: Matrix::identity(),
                    stroke_params: Some(sp),
                },
            });
            for elem in shading_box.0.elements() {
                group_dl.push(elem.clone());
            }
            self.display_list.push(DisplayElement::Group {
                elements: group_dl,
                params: GroupParams {
                    bbox,
                    isolated: true,
                    knockout: false,
                    blend_mode: self.gstate.blend_mode,
                    alpha: self.gstate.stroke_alpha,
                    color_space: stet_graphics::display_list::GroupColorSpace::Inherited,
                },
            });
            return;
        }

        let mut params = self.gstate.stroke_params_with_ctm();
        params.ctm = ctm;
        self.display_list.push(DisplayElement::Stroke {
            path: user_path,
            params,
        });
    }

    /// Emit fill+stroke atomically: when both are simple (no pattern/shading)
    /// and blend mode is Normal, wrap them in an isolated Group so the stroke
    /// erases the fill's AA edges inside the offscreen buffer before the
    /// combined result composites onto the page. This prevents the fill's
    /// anti-aliased edge pixels from leaking into the pixmap where a
    /// subsequent overprint knockout at a slightly different position would
    /// not fully cover them (GWG 4.0.1 swatch d).
    fn emit_fill_stroke(&mut self, path: PsPath, fill_rule: FillRule) {
        let is_simple_fill =
            self.gstate.fill_shading_pattern.is_none() && self.gstate.fill_pattern.is_none();
        let is_simple_stroke =
            self.gstate.stroke_shading_pattern.is_none() && self.gstate.stroke_pattern.is_none();

        // Group wrapping is safe when the paint's rendering doesn't depend on
        // per-channel backdrop interaction that differs between a real page
        // backdrop and an isolated group's transparent backdrop.
        //
        // - Non-overprint paints always replace the backdrop: safe to group.
        // - Overprint paints can preserve backdrop channels (spot plates,
        //   zero-valued CMYK channels under strict OPM-1). To be safe we
        //   require BOTH fill and stroke to be DeviceCMYK (no Separation /
        //   DeviceN so spot plates aren't involved), the source to be white
        //   (0,0,0,0) so OPM-0 produces a full knockout regardless of
        //   backdrop, and NOT under strict OPM-1 (which would preserve zero
        //   channels and thus depend on the actual backdrop).
        let strict_opm1 = self.gstate.overprint_mode == 1 && self.gstate.opm_paired;
        let is_white_fill = self.gstate.fill_is_device_cmyk
            && self
                .gstate
                .fill_color
                .native_cmyk
                .map(|(c, m, y, k)| c == 0.0 && m == 0.0 && y == 0.0 && k == 0.0)
                .unwrap_or(false);
        let is_white_stroke = self.gstate.stroke_is_device_cmyk
            && self
                .gstate
                .stroke_color
                .native_cmyk
                .map(|(c, m, y, k)| c == 0.0 && m == 0.0 && y == 0.0 && k == 0.0)
                .unwrap_or(false);
        let has_any_overprint = self.gstate.overprint || self.gstate.overprint_stroke;
        // When any overprint is active, require BOTH sides to be DeviceCMYK so
        // spot colorants (which depend on multiplicative backdrop interaction
        // for correct rendering) aren't involved. Mixing a DeviceCMYK overprint
        // fill with a Separation stroke (GWG 4.0.1 swatches a/b/c) would lose
        // the spot backdrop inside the group.
        let both_device_cmyk = self.gstate.fill_is_device_cmyk && self.gstate.stroke_is_device_cmyk;
        let fill_overprint_safe =
            !self.gstate.overprint || (is_white_fill && both_device_cmyk && !strict_opm1);
        let stroke_overprint_safe =
            !self.gstate.overprint_stroke || (is_white_stroke && both_device_cmyk && !strict_opm1);
        // Extra guard: even if each side's own overprint check passes, refuse
        // when *any* overprint is active and the OTHER side isn't DeviceCMYK —
        // this catches the "inherited overprint_stroke=false + Separation
        // stroke + overprint fill" case where the fill alone looks safe.
        let mixed_space_with_overprint = has_any_overprint && !both_device_cmyk;

        if is_simple_fill
            && is_simple_stroke
            && self.gstate.blend_mode == 0
            && fill_overprint_safe
            && stroke_overprint_safe
            && !mixed_space_with_overprint
        {
            let ctm = self.gstate.ctm;

            let mut bbox = path_device_bbox(&path);
            let scale = self.gstate.ctm_scale_factor();
            let half_w = self.gstate.line_width * scale * 0.5;
            bbox[0] -= half_w;
            bbox[1] -= half_w;
            bbox[2] += half_w;
            bbox[3] += half_w;

            let fill_elem = DisplayElement::Fill {
                path: path.clone(),
                params: self.gstate.fill_params(fill_rule),
            };

            let user_path = if let Some(inv) = ctm.invert() {
                path.transform(&inv)
            } else {
                path.clone()
            };
            let mut stroke_params = self.gstate.stroke_params_with_ctm();
            stroke_params.ctm = ctm;
            let stroke_elem = DisplayElement::Stroke {
                path: user_path,
                params: stroke_params,
            };

            let mut group_dl = DisplayList::new();
            group_dl.push(fill_elem);
            group_dl.push(stroke_elem);

            self.display_list.push(DisplayElement::Group {
                elements: group_dl,
                params: stet_graphics::display_list::GroupParams {
                    bbox,
                    isolated: true,
                    knockout: false,
                    blend_mode: 0,
                    alpha: 1.0,
                    color_space: stet_graphics::display_list::GroupColorSpace::Inherited,
                },
            });
        } else {
            self.emit_fill(path.clone(), fill_rule);
            self.emit_stroke(path);
        }
    }

    fn op_n(&mut self) -> Result<(), PdfError> {
        // n: end path (no paint) — used for clip-only paths
        let _path = self.take_path();
        self.apply_pending_clip();
        Ok(())
    }

    // === Clipping operators ===

    fn op_big_w(&mut self) -> Result<(), PdfError> {
        // W: clip (non-zero winding), deferred to next paint op
        self.gstate.pending_clip = Some((self.current_path.clone(), FillRule::NonZeroWinding));
        Ok(())
    }

    fn op_big_w_star(&mut self) -> Result<(), PdfError> {
        // W*: clip (even-odd), deferred to next paint op
        self.gstate.pending_clip = Some((self.current_path.clone(), FillRule::EvenOdd));
        Ok(())
    }

    // === Device color operators ===

    fn op_big_g(&mut self) -> Result<(), PdfError> {
        // G gray: set stroke color to gray
        let g = self.pop_number()?;
        let (color, painted, is_cmyk) = self.gray_paint_for_gstate(g);
        self.gstate.stroke_color = color;
        self.gstate.stroke_color_space = ColorSpaceRef::DeviceGray;
        self.gstate.stroke_painted_channels = painted;
        self.gstate.stroke_is_device_cmyk = is_cmyk;
        self.gstate.stroke_is_none = false;
        self.gstate.stroke_spot_color = None;
        self.gstate.stroke_icc_color = None;
        self.gstate.stroke_pattern = None;
        self.gstate.stroke_shading_pattern = None;
        Ok(())
    }

    fn op_small_g(&mut self) -> Result<(), PdfError> {
        // g gray: set fill color to gray
        let g = self.pop_number()?;
        let (color, painted, is_cmyk) = self.gray_paint_for_gstate(g);
        self.gstate.fill_color = color;
        self.gstate.fill_color_space = ColorSpaceRef::DeviceGray;
        self.gstate.fill_painted_channels = painted;
        self.gstate.fill_is_device_cmyk = is_cmyk;
        self.gstate.fill_is_none = false;
        self.gstate.fill_spot_color = None;
        self.gstate.fill_icc_color = None;
        self.gstate.fill_pattern = None;
        self.gstate.fill_shading_pattern = None;
        Ok(())
    }

    /// Build the gstate fields for a DeviceGray paint. In a CMYK page group
    /// the gray is promoted to a K-only DeviceCMYK paint so the rendering
    /// pipeline composites it identically to `0 0 0 (1−g) k` — matches PDF/X
    /// semantics where DeviceGray maps onto the K plate (GWG 23.0). The
    /// promoted paint still carries `painted_channels = CMYK_K` so the
    /// overprint dispatcher routes it through the K-only subset path,
    /// preserving the overprint-vs-spot behaviour the standalone gray
    /// promotion (GWG 3.0 b/h) needs.
    fn gray_paint_for_gstate(&mut self, g: f64) -> (DeviceColor, u8, bool) {
        if self.pdfx_cmyk_intent && !self.in_smask_form {
            let k = (1.0 - g).clamp(0.0, 1.0);
            let color = DeviceColor::from_cmyk_icc(0.0, 0.0, 0.0, k, &mut self.icc_cache);
            (color, stet_graphics::device::CMYK_K, true)
        } else {
            (DeviceColor::from_gray(g), 0, false)
        }
    }

    fn op_big_rg(&mut self) -> Result<(), PdfError> {
        // RG r g b: set stroke color to RGB
        let n = self.get_numbers(3)?;
        let (r, g, b) = self.cmyk_group_rgb(n[0], n[1], n[2]);
        self.gstate.stroke_color = DeviceColor::from_rgb(r, g, b);
        self.gstate.stroke_color_space = ColorSpaceRef::DeviceRGB;
        self.gstate.stroke_painted_channels = 0;
        self.gstate.stroke_is_device_cmyk = false;
        self.gstate.stroke_is_none = false;
        self.gstate.stroke_spot_color = None;
        self.gstate.stroke_icc_color = None;
        self.gstate.stroke_pattern = None;
        self.gstate.stroke_shading_pattern = None;
        Ok(())
    }

    fn op_small_rg(&mut self) -> Result<(), PdfError> {
        // rg r g b: set fill color to RGB
        let n = self.get_numbers(3)?;
        let (r, g, b) = self.cmyk_group_rgb(n[0], n[1], n[2]);
        self.gstate.fill_color = DeviceColor::from_rgb(r, g, b);
        self.gstate.fill_color_space = ColorSpaceRef::DeviceRGB;
        self.gstate.fill_painted_channels = 0;
        self.gstate.fill_is_device_cmyk = false;
        self.gstate.fill_is_none = false;
        self.gstate.fill_spot_color = None;
        self.gstate.fill_icc_color = None;
        self.gstate.fill_pattern = None;
        self.gstate.fill_shading_pattern = None;
        Ok(())
    }

    /// When the page group is DeviceCMYK, round-trip RGB through the CMYK
    /// profile to simulate compositing in CMYK space.
    fn cmyk_group_rgb(&mut self, r: f64, g: f64, b: f64) -> (f64, f64, f64) {
        if self.page_group_is_cmyk {
            if let Some(result) = self.icc_cache.round_trip_rgb_via_cmyk(r, g, b) {
                return result;
            }
        }
        (r, g, b)
    }

    /// When the page group is DeviceCMYK, route a DeviceGray-derived image
    /// (DeviceGray itself, or Separation/DeviceN whose alt is DeviceGray)
    /// through the K plate so it composites equivalently to a DeviceCMYK
    /// 0/0/0/(1−g) image. Without this, GWG 23.0's "4 different Grays" test
    /// shows the right half of an X over its DeviceCMYK BG (left half comes
    /// from the polygon overpaint, fixed by `cmyk_group_promote_color`).
    ///
    /// Returns `(color_space, sample_data)` with the alt promoted to
    /// DeviceCMYK. For DeviceGray images we expand 1-byte gray samples to
    /// 4-byte CMYK with K=255−g; for Separation/DeviceN with DeviceGray alt
    /// we rebuild the tint table to emit `(0, 0, 0, 1−g)` instead of `g`.
    fn cmyk_group_promote_image(
        &self,
        cs: ImageColorSpace,
        data: Vec<u8>,
        width: u32,
        height: u32,
    ) -> (ImageColorSpace, Vec<u8>) {
        if !self.pdfx_cmyk_intent || self.in_smask_form {
            return (cs, data);
        }
        match cs {
            ImageColorSpace::DeviceGray => {
                let npx = (width as usize) * (height as usize);
                let take = npx.min(data.len());
                let mut new_data = vec![0u8; npx * 4];
                for i in 0..take {
                    new_data[i * 4 + 3] = 255 - data[i];
                }
                (ImageColorSpace::DeviceCMYK, new_data)
            }
            ImageColorSpace::Separation {
                name,
                alt_space,
                tint_table,
            } => {
                if matches!(alt_space.as_ref(), ImageColorSpace::DeviceGray)
                    && tint_table.num_outputs == 1
                {
                    let samples = tint_table.samples_per_dim as usize;
                    let mut new_data = Vec::with_capacity(samples * 4);
                    for i in 0..samples {
                        let g = tint_table.data[i] as f64;
                        let k = (1.0 - g).clamp(0.0, 1.0) as f32;
                        new_data.push(0.0);
                        new_data.push(0.0);
                        new_data.push(0.0);
                        new_data.push(k);
                    }
                    let promoted_table = TintLookupTable {
                        num_inputs: 1,
                        num_outputs: 4,
                        samples_per_dim: tint_table.samples_per_dim,
                        data: new_data,
                    };
                    (
                        ImageColorSpace::Separation {
                            name,
                            alt_space: Box::new(ImageColorSpace::DeviceCMYK),
                            tint_table: Arc::new(promoted_table),
                        },
                        data,
                    )
                } else {
                    (
                        ImageColorSpace::Separation {
                            name,
                            alt_space,
                            tint_table,
                        },
                        data,
                    )
                }
            }
            ImageColorSpace::DeviceN {
                names,
                alt_space,
                tint_table,
            } => {
                if matches!(alt_space.as_ref(), ImageColorSpace::DeviceGray)
                    && tint_table.num_outputs == 1
                {
                    let total = tint_table.data.len();
                    let mut new_data = Vec::with_capacity(total * 4);
                    for &g in &tint_table.data {
                        let k = (1.0 - g as f64).clamp(0.0, 1.0) as f32;
                        new_data.push(0.0);
                        new_data.push(0.0);
                        new_data.push(0.0);
                        new_data.push(k);
                    }
                    let promoted_table = TintLookupTable {
                        num_inputs: tint_table.num_inputs,
                        num_outputs: 4,
                        samples_per_dim: tint_table.samples_per_dim,
                        data: new_data,
                    };
                    (
                        ImageColorSpace::DeviceN {
                            names,
                            alt_space: Box::new(ImageColorSpace::DeviceCMYK),
                            tint_table: Arc::new(promoted_table),
                        },
                        data,
                    )
                } else {
                    (
                        ImageColorSpace::DeviceN {
                            names,
                            alt_space,
                            tint_table,
                        },
                        data,
                    )
                }
            }
            other => (other, data),
        }
    }

    /// When the page group is DeviceCMYK, override a paint's RGB with the
    /// CMYK-ICC rendering of its `native_cmyk` whenever the source RGB is
    /// itself a flat gray and the CMYK is K-only — matches the PDF/X
    /// behaviour expected for Separation/DeviceN paints whose alternate space
    /// is DeviceGray (e.g. Separation /Black tinted via gray=1−tint).
    fn cmyk_group_promote_color(&mut self, color: &mut DeviceColor) {
        if !self.pdfx_cmyk_intent || self.in_smask_form {
            return;
        }
        let Some((c, m, y, k)) = color.native_cmyk else {
            return;
        };
        // Only fire for K-only CMYK whose r/g/b currently form a flat gray —
        // that's the DeviceGray-alt case. DeviceCMYK paints already have ICC-
        // converted RGB, so the override would be a no-op there; restricting
        // to flat-gray r/g/b avoids ever touching genuine colour paints.
        if !(c == 0.0 && m == 0.0 && y == 0.0) {
            return;
        }
        // Skip the all-zero CMYK case. It legitimately encodes "white" for a
        // DeviceCMYK 0/0/0/0 paint (where r/g/b is already 1/1/1, so the
        // override would be a no-op), but it also surfaces from the separation
        // handler's fallback for non-K process colorants like /All — there
        // `native_cmyk` is set to (0,0,0,0) even when the visual is the alt-
        // gray result (e.g. Separation /All at tint=1 → gray=0 → black text).
        // ICC-converting (0,0,0,0) would erase those paints to white.
        if k == 0.0 {
            return;
        }
        if (color.r - color.g).abs() > f64::EPSILON || (color.r - color.b).abs() > f64::EPSILON {
            return;
        }
        if let Some((r, g, b)) = self.icc_cache.convert_cmyk(0.0, 0.0, 0.0, k) {
            color.r = r;
            color.g = g;
            color.b = b;
        }
    }

    fn op_big_k(&mut self) -> Result<(), PdfError> {
        // K c m y k: set stroke color to CMYK
        let n = self.get_numbers(4)?;
        self.gstate.stroke_color =
            DeviceColor::from_cmyk_icc(n[0], n[1], n[2], n[3], &mut self.icc_cache);
        self.gstate.stroke_color_space = ColorSpaceRef::DeviceCMYK;
        self.gstate.stroke_painted_channels = stet_graphics::device::CMYK_ALL;
        self.gstate.stroke_is_device_cmyk = true;
        self.gstate.stroke_is_none = false;
        self.gstate.stroke_spot_color = None;
        self.gstate.stroke_icc_color = None;
        self.gstate.stroke_pattern = None;
        self.gstate.stroke_shading_pattern = None;
        Ok(())
    }

    fn op_small_k(&mut self) -> Result<(), PdfError> {
        // k c m y k: set fill color to CMYK
        let n = self.get_numbers(4)?;
        self.gstate.fill_color =
            DeviceColor::from_cmyk_icc(n[0], n[1], n[2], n[3], &mut self.icc_cache);
        self.gstate.fill_color_space = ColorSpaceRef::DeviceCMYK;
        self.gstate.fill_painted_channels = stet_graphics::device::CMYK_ALL;
        self.gstate.fill_is_device_cmyk = true;
        self.gstate.fill_is_none = false;
        self.gstate.fill_spot_color = None;
        self.gstate.fill_icc_color = None;
        self.gstate.fill_pattern = None;
        self.gstate.fill_shading_pattern = None;
        Ok(())
    }

    // === General color operators ===

    fn op_big_cs(&mut self) -> Result<(), PdfError> {
        // CS name: set stroke color space
        let name = self
            .operand_stack
            .last()
            .and_then(|o| o.as_name())
            .ok_or(PdfError::Other("CS: expected name".into()))?
            .to_vec();
        self.gstate.stroke_color_space = name_to_cs_ref(&name);
        Ok(())
    }

    fn op_small_cs(&mut self) -> Result<(), PdfError> {
        // cs name: set fill color space
        let name = self
            .operand_stack
            .last()
            .and_then(|o| o.as_name())
            .ok_or(PdfError::Other("cs: expected name".into()))?
            .to_vec();
        self.gstate.fill_color_space = name_to_cs_ref(&name);
        Ok(())
    }

    /// Resolve a color space from a ColorSpaceRef.
    /// For named color spaces, uses a HashMap index of the ColorSpace resource
    /// sub-dict to avoid O(n) linear scans on large dicts (74K+ entries).
    fn resolve_cs_cached(
        &mut self,
        cs_ref: &ColorSpaceRef,
    ) -> Result<ResolvedColorSpace, PdfError> {
        if let ColorSpaceRef::Named(name) = cs_ref {
            // Fast path for device color space names
            match name.as_slice() {
                b"DeviceGray" | b"G" => return Ok(ResolvedColorSpace::DeviceGray),
                b"DeviceRGB" | b"RGB" => return Ok(ResolvedColorSpace::DeviceRGB),
                b"DeviceCMYK" | b"CMYK" => return Ok(ResolvedColorSpace::DeviceCMYK),
                b"Pattern" => return Ok(ResolvedColorSpace::Pattern),
                _ => {}
            }
            // Build HashMap index of ColorSpace resource dict on first use
            if self.cs_index.is_none() {
                let mut index = std::collections::HashMap::new();
                if let Some(cs_dict) = self.resolve_resource_subdict(b"ColorSpace") {
                    for (k, v) in cs_dict.entries() {
                        index.insert(k.clone(), v.clone());
                    }
                }
                self.cs_index = Some(index);
            }
            if let Some(cs_obj) = self.cs_index.as_ref().unwrap().get(name.as_slice()) {
                let cs_obj = cs_obj.clone();
                resolve_color_space_obj(&cs_obj, self.resolver)
            } else {
                // Name not in cached ColorSpace dict — fall back to full resolution
                // (handles resources without a ColorSpace sub-dict, or names that
                // appear due to resource inheritance not captured by the index)
                resolve_color_space(
                    &ColorSpaceRef::Named(name.to_vec()),
                    &self.resources,
                    self.resolver,
                )
            }
        } else {
            resolve_color_space(cs_ref, &self.resources, self.resolver)
        }
    }

    fn op_sc_stroke(&mut self) -> Result<(), PdfError> {
        // SC/SCN: set stroke color in current color space.
        // Some non-conforming PDFs use `/PatternName SCN` without first doing
        // `/Pattern CS` — detect a name operand and treat it as a pattern
        // reference regardless of the current color space.
        if matches!(self.operand_stack.last(), Some(Operand::Name(_))) {
            return self.handle_pattern_stroke();
        }
        let cs = self.resolve_cs_cached(&self.gstate.stroke_color_space.clone())?;
        if matches!(cs, ResolvedColorSpace::Pattern) {
            return self.handle_pattern_stroke();
        }
        let n = cs.num_components();
        if n == 0 {
            return Ok(());
        }
        let nums = self.get_numbers(n)?;
        self.gstate.stroke_painted_channels = painted_channels_for_cs(&cs);
        self.gstate.stroke_is_none = cs.is_none_colorant();
        self.gstate.stroke_is_device_cmyk = matches!(
            cs,
            ResolvedColorSpace::DeviceCMYK | ResolvedColorSpace::ICCBased { n: 4, .. }
        );
        let intent = self.gstate.rendering_intent;
        let mut color = color_space::components_to_device_color_icc_with_intent(
            &cs,
            &nums,
            Some(&mut self.icc_cache),
            intent,
        );
        self.cmyk_group_promote_color(&mut color);
        self.gstate.stroke_color = color;
        self.gstate.stroke_spot_color =
            color_space::build_spot_color(&cs, &nums, &mut self.spot_tint_table_cache);
        self.gstate.stroke_icc_color = color_space::build_icc_color(&cs, &nums);
        self.gstate.stroke_pattern = None;
        self.gstate.stroke_shading_pattern = None;
        Ok(())
    }

    fn op_sc_fill(&mut self) -> Result<(), PdfError> {
        // sc/scn: set fill color in current color space.
        // Some non-conforming PDFs use `/PatternName scn` without first doing
        // `/Pattern cs` — detect a name operand and treat it as a pattern
        // reference regardless of the current color space (matches hayro/Firefox).
        if matches!(self.operand_stack.last(), Some(Operand::Name(_))) {
            return self.handle_pattern_fill();
        }
        let cs = self.resolve_cs_cached(&self.gstate.fill_color_space.clone())?;
        if matches!(cs, ResolvedColorSpace::Pattern) {
            return self.handle_pattern_fill();
        }
        let n = cs.num_components();
        if n == 0 {
            return Ok(());
        }
        let nums = self.get_numbers(n)?;
        self.gstate.fill_painted_channels = painted_channels_for_cs(&cs);
        self.gstate.fill_is_none = cs.is_none_colorant();
        self.gstate.fill_is_device_cmyk = matches!(
            cs,
            ResolvedColorSpace::DeviceCMYK | ResolvedColorSpace::ICCBased { n: 4, .. }
        );
        let intent = self.gstate.rendering_intent;
        let mut color = color_space::components_to_device_color_icc_with_intent(
            &cs,
            &nums,
            Some(&mut self.icc_cache),
            intent,
        );
        self.cmyk_group_promote_color(&mut color);
        self.gstate.fill_color = color;
        self.gstate.fill_spot_color =
            color_space::build_spot_color(&cs, &nums, &mut self.spot_tint_table_cache);
        self.gstate.fill_icc_color = color_space::build_icc_color(&cs, &nums);
        self.gstate.fill_pattern = None;
        self.gstate.fill_shading_pattern = None;
        Ok(())
    }

    // === Text operators (state recording, Phase C will add rendering) ===

    fn op_tf(&mut self) -> Result<(), PdfError> {
        // Tf font size
        let len = self.operand_stack.len();
        if len < 2 {
            return Ok(());
        }
        self.gstate.font_size = self.operand_stack[len - 1].as_f64().unwrap_or(12.0);
        if let Some(name) = self.operand_stack[len - 2].as_name() {
            let name = name.to_vec();
            self.gstate.text_font_name = name.clone();
            self.resolve_current_font(&name);
        }
        Ok(())
    }

    /// Resolve the current font by name from the font cache or resources.
    fn resolve_current_font(&mut self, name: &[u8]) {
        // Check cache by name first (fast path for the common case where the
        // same name maps to the same font object across resource scopes).
        if let Some(cached) = self.font_cache.get(name) {
            // Verify the cached font still matches — different resource scopes
            // (page vs annotation vs form) may map the same name to different
            // font objects (e.g. /TT1 → obj 90 on page, /TT1 → obj 407 in annot).
            let font_ref = self
                .resolve_resource_subdict(b"Font")
                .and_then(|fd| fd.get(name).cloned());
            if let Some(PdfObj::Ref(obj_num, _)) = &font_ref {
                let obj_key = obj_num.to_le_bytes().to_vec();
                if let Some(obj_cached) = self.font_cache.get(&obj_key) {
                    // The obj-keyed cache has this font — use it (handles both
                    // same-as-name and different-from-name cases).
                    self.current_font = Some(Arc::clone(obj_cached));
                    return;
                }
                // obj key not in cache → this is a NEW font object that happens
                // to share a name with a previously cached font. Fall through to
                // resolve the new font instead of using the stale name-cached entry.
            } else {
                // No obj ref — use the name-cached font
                self.current_font = Some(Arc::clone(cached));
                return;
            }
        }

        // Cache miss — look up in resources /Font dict
        let font_ref = self
            .resolve_resource_subdict(b"Font")
            .and_then(|fd| fd.get(name).cloned());
        let font_ref = match font_ref {
            Some(r) => r,
            None => {
                // Font resource missing — try loading a default substitution font
                if let Some(fallback) = font::fallback_font(self.font_provider.as_ref()) {
                    let arc = Arc::new(fallback);
                    self.font_cache.insert(name.to_vec(), Arc::clone(&arc));
                    self.current_font = Some(arc);
                } else {
                    self.current_font = None;
                }
                return;
            }
        };

        // Check if this same object was already resolved under a different name
        if let PdfObj::Ref(obj_num, _) = &font_ref {
            let obj_key = obj_num.to_le_bytes().to_vec();
            if let Some(cached) = self.font_cache.get(&obj_key) {
                let arc = Arc::clone(cached);
                self.font_cache.insert(name.to_vec(), Arc::clone(&arc));
                self.current_font = Some(arc);
                return;
            }
        }

        match font::resolve_font(self.resolver, &font_ref, self.font_provider.as_ref()) {
            Ok(font) => {
                let arc = Arc::new(font);
                // Cache under both the name and object number keys
                if let PdfObj::Ref(obj_num, _) = &font_ref {
                    self.font_cache
                        .insert(obj_num.to_le_bytes().to_vec(), Arc::clone(&arc));
                }
                self.font_cache.insert(name.to_vec(), Arc::clone(&arc));
                self.current_font = Some(arc);
            }
            Err(e) => {
                // Deduplicate warnings across pages (same font fails on every page)
                use std::sync::Mutex;
                static WARNED: Mutex<Vec<String>> = Mutex::new(Vec::new());
                let msg = format!("font /{}: {}", String::from_utf8_lossy(name), e);
                if let Ok(mut set) = WARNED.lock()
                    && !set.contains(&msg)
                {
                    eprintln!("warning: {msg}");
                    set.push(msg);
                }
                // Try fallback font on resolution failure too
                if let Some(fallback) = font::fallback_font(self.font_provider.as_ref()) {
                    let arc = Arc::new(fallback);
                    self.font_cache.insert(name.to_vec(), Arc::clone(&arc));
                    self.current_font = Some(arc);
                } else {
                    self.current_font = None;
                }
            }
        }
    }

    /// Check if the current text position is outside the visible form area.
    /// If so, mark the BT block as culled to skip remaining text ops.
    fn check_text_cull(&mut self) {
        if let Some((y_lo, y_hi)) = self.form_cull_y {
            // Text Y in form coordinates is the ty component of the text matrix
            let text_y = self.gstate.text_matrix.ty;
            if text_y < y_lo || text_y > y_hi {
                self.bt_culled = true;
            }
        }
    }

    fn op_td(&mut self) -> Result<(), PdfError> {
        let n = self.get_numbers(2)?;
        let m = Matrix::translate(n[0], n[1]);
        self.gstate.text_line_matrix = self.gstate.text_line_matrix.concat(&m);
        self.gstate.text_matrix = self.gstate.text_line_matrix;
        self.check_text_cull();
        Ok(())
    }

    fn op_big_td(&mut self) -> Result<(), PdfError> {
        let n = self.get_numbers(2)?;
        self.gstate.text_leading = -n[1];
        let m = Matrix::translate(n[0], n[1]);
        self.gstate.text_line_matrix = self.gstate.text_line_matrix.concat(&m);
        self.gstate.text_matrix = self.gstate.text_line_matrix;
        self.check_text_cull();
        Ok(())
    }

    fn op_tm(&mut self) -> Result<(), PdfError> {
        let n = self.get_numbers(6)?;
        let m = Matrix::new(n[0], n[1], n[2], n[3], n[4], n[5]);
        self.gstate.text_matrix = m;
        self.gstate.text_line_matrix = m;
        self.check_text_cull();
        Ok(())
    }

    fn op_t_star(&mut self) -> Result<(), PdfError> {
        let leading = self.gstate.text_leading;
        let m = Matrix::translate(0.0, -leading);
        self.gstate.text_line_matrix = self.gstate.text_line_matrix.concat(&m);
        self.gstate.text_matrix = self.gstate.text_line_matrix;
        Ok(())
    }

    // === Text rendering operators ===

    fn op_tj(&mut self) -> Result<(), PdfError> {
        let text = match self.operand_stack.last() {
            Some(Operand::Str(s)) => s.clone(),
            _ => return Ok(()),
        };
        self.show_text(&text);
        Ok(())
    }

    fn op_big_tj(&mut self) -> Result<(), PdfError> {
        let arr = match self.operand_stack.last() {
            Some(Operand::Array(a)) => a.clone(),
            _ => return Ok(()),
        };
        let vertical = self.current_font.as_ref().is_some_and(|f| f.wmode() == 1);
        for elem in &arr {
            match elem {
                PdfObj::Str(s) => self.show_text(s),
                PdfObj::Int(n) => {
                    let shift = -*n as f64 / 1000.0 * self.gstate.font_size;
                    let m = if vertical {
                        Matrix::translate(0.0, shift)
                    } else {
                        Matrix::translate(shift * self.gstate.horizontal_scaling, 0.0)
                    };
                    self.gstate.text_matrix = self.gstate.text_matrix.concat(&m);
                }
                PdfObj::Real(f) => {
                    let shift = -f / 1000.0 * self.gstate.font_size;
                    let m = if vertical {
                        Matrix::translate(0.0, shift)
                    } else {
                        Matrix::translate(shift * self.gstate.horizontal_scaling, 0.0)
                    };
                    self.gstate.text_matrix = self.gstate.text_matrix.concat(&m);
                }
                _ => {}
            }
        }
        Ok(())
    }

    fn op_quote(&mut self) -> Result<(), PdfError> {
        // ': T* then Tj
        self.op_t_star()?;
        self.op_tj()
    }

    fn op_dblquote(&mut self) -> Result<(), PdfError> {
        // ": set word_spacing, char_spacing, then T* + Tj
        let len = self.operand_stack.len();
        if len < 3 {
            return Ok(());
        }
        self.gstate.word_spacing = self.operand_stack[len - 3].as_f64().unwrap_or(0.0);
        self.gstate.char_spacing = self.operand_stack[len - 2].as_f64().unwrap_or(0.0);
        // The string is at len-1, which op_tj reads from last()
        self.op_t_star()?;
        self.op_tj()
    }

    /// Render a text string by emitting glyph paths as Fill display elements.
    fn show_text(&mut self, text: &[u8]) {
        let font = match &self.current_font {
            Some(f) => Arc::clone(f),
            None => return,
        };

        let font_size = self.gstate.font_size;
        let char_spacing = self.gstate.char_spacing;
        let word_spacing = self.gstate.word_spacing;
        let text_rise = self.gstate.text_rise;
        let th = self.gstate.horizontal_scaling;
        let font_matrix = font.font_matrix();
        let render_mode = self.gstate.text_rendering_mode;

        if font.is_composite() {
            // Composite (CID) font: variable-width character codes
            // (most are 2-byte, but some CMaps define 1-byte codes for space etc.)
            let mut i = 0;
            while i < text.len() {
                let code_width = font.code_width(text[i]);
                if code_width == 1 {
                    // 1-byte code. Per PDF spec 9.3.3, word spacing applies to
                    // the single-byte character code 32 (SPACE) even in a
                    // composite font.
                    let raw_code = text[i] as u32;
                    let extra = if raw_code == 0x20 { word_spacing } else { 0.0 };
                    i += 1;
                    let cid = font.resolve_code_to_cid(raw_code) as u16;
                    self.render_cid_glyph(
                        &font,
                        cid,
                        font_size,
                        char_spacing,
                        th,
                        text_rise,
                        &font_matrix,
                        render_mode,
                        extra,
                    );
                } else if i + 1 >= text.len() {
                    // Incomplete trailing byte in 2-byte font — treat as WinAnsi
                    let byte = text[i];
                    i += 1;
                    self.render_unicode_glyph(
                        byte,
                        font_size,
                        char_spacing,
                        th,
                        text_rise,
                        &font_matrix,
                        render_mode,
                    );
                } else {
                    // Multi-byte code (2, 3, or 4 bytes from codespace ranges).
                    let width = code_width.min(text.len() - i);
                    let mut raw_code = 0u32;
                    for b in &text[i..i + width] {
                        raw_code = (raw_code << 8) | (*b as u32);
                    }
                    let cid = font.resolve_code_to_cid(raw_code) as u16;
                    // If the multi-byte code resolves to CID 0 (or the raw code
                    // itself for identity), the sequence may be invalid (e.g.
                    // UTF-8 continuation bytes out of range).  Try interpreting
                    // the first byte as a 1-byte code instead.
                    let (cid, consumed) = if cid == 0 || (cid == raw_code as u16 && width > 2) {
                        let byte_cid = font.resolve_code_to_cid(text[i] as u32) as u16;
                        if byte_cid != 0 && byte_cid != text[i] as u16 {
                            (byte_cid, 1)
                        } else {
                            (cid, width)
                        }
                    } else {
                        (cid, width)
                    };
                    // Word spacing applies only to SINGLE-byte code 32.
                    let extra = if consumed == 1 && text[i] == 0x20 {
                        word_spacing
                    } else {
                        0.0
                    };
                    i += consumed;
                    if font.has_cid_glyph(cid) {
                        // CID maps to a valid GID in the font
                        self.render_cid_glyph(
                            &font,
                            cid,
                            font_size,
                            char_spacing,
                            th,
                            text_rise,
                            &font_matrix,
                            render_mode,
                            extra,
                        );
                    } else {
                        // 2-byte CID has no glyph.  Some malformed PDFs encode
                        // single-byte CIDs in 2-byte Identity-H strings with a
                        // padding high byte (e.g. 0x20).  Try the low byte alone.
                        let lo_cid = (raw_code & 0xFF) as u16;
                        if lo_cid > 0 && font.has_cid_glyph(lo_cid) {
                            self.render_cid_glyph(
                                &font,
                                lo_cid,
                                font_size,
                                char_spacing,
                                th,
                                text_rise,
                                &font_matrix,
                                render_mode,
                                extra,
                            );
                        } else if raw_code <= 0xFF {
                            // Low code point with no CID glyph — malformed PDF mixing
                            // 1-byte WinAnsi text in a CID font.  Bypass the CID
                            // machinery and map each byte through WinAnsi→Unicode→cmap.
                            self.render_unicode_glyph(
                                text[i - 2],
                                font_size,
                                char_spacing,
                                th,
                                text_rise,
                                &font_matrix,
                                render_mode,
                            );
                            self.render_unicode_glyph(
                                text[i - 1],
                                font_size,
                                char_spacing,
                                th,
                                text_rise,
                                &font_matrix,
                                render_mode,
                            );
                        } else {
                            // CID glyph not available (e.g. substitute font for CJK).
                            // Use CID width for correct advancement; try Unicode for shape.
                            self.render_cid_glyph_unicode_fallback(
                                &font,
                                cid,
                                raw_code,
                                font_size,
                                char_spacing,
                                th,
                                text_rise,
                                &font_matrix,
                                render_mode,
                                extra,
                            );
                        }
                    }
                }
            }
        } else if font.is_type3() {
            // Type 3 font: each glyph is a content stream.
            // Widths are in glyph space — scale by font matrix to get text space.
            let fm = font.font_matrix();
            let visible = (render_mode & 3) != 3; // mode 3 = invisible
            for &byte in text {
                if visible {
                    self.show_type3_glyph(&font, byte);
                }

                let w0_glyph = font.glyph_width(byte);
                let w0 = w0_glyph * fm.a;
                let mut tx = w0 * font_size + char_spacing;
                if byte == b' ' {
                    tx += word_spacing;
                }
                tx *= th;
                let advance = Matrix::translate(tx, 0.0);
                self.gstate.text_matrix = self.gstate.text_matrix.concat(&advance);
            }
        } else {
            // Simple font: 1-byte character codes
            for &byte in text {
                if let Some(glyph_path) = font.glyph_path(byte) {
                    let text_state_matrix =
                        Matrix::new(font_size * th, 0.0, 0.0, font_size, 0.0, text_rise);
                    let trm = self
                        .gstate
                        .ctm
                        .concat(&self.gstate.text_matrix)
                        .concat(&text_state_matrix)
                        .concat(&font_matrix);

                    let device_path = glyph_path.transform(&trm);
                    if !device_path.is_empty() {
                        self.emit_text_glyph(device_path, render_mode);
                    }
                }

                let w0 = font.glyph_width(byte);
                let mut tx = w0 * font_size + char_spacing;
                if byte == b' ' {
                    tx += word_spacing;
                }
                tx *= th;
                let advance = Matrix::translate(tx, 0.0);
                self.gstate.text_matrix = self.gstate.text_matrix.concat(&advance);
            }
        }
    }

    /// Render a single CID glyph and advance the text position.
    fn render_cid_glyph(
        &mut self,
        font: &PdfFont,
        cid: u16,
        font_size: f64,
        char_spacing: f64,
        th: f64,
        text_rise: f64,
        font_matrix: &Matrix,
        render_mode: i32,
        extra_advance: f64,
    ) {
        let vertical = font.wmode() == 1;
        if let Some(glyph_path) = font.glyph_path_cid(cid) {
            let text_state_matrix = if vertical {
                // Vertical mode: use per-CID metrics (w1, v_x, v_y) from W2/DW2.
                // v_x/v_y define the position vector from horizontal to vertical origin.
                let [_w1, v_x, v_y] = font.vertical_metrics_cid(cid);
                Matrix::new(
                    font_size,
                    0.0,
                    0.0,
                    font_size,
                    -v_x / 1000.0 * font_size,
                    -v_y / 1000.0 * font_size,
                )
            } else {
                Matrix::new(font_size * th, 0.0, 0.0, font_size, 0.0, text_rise)
            };
            let trm = self
                .gstate
                .ctm
                .concat(&self.gstate.text_matrix)
                .concat(&text_state_matrix)
                .concat(font_matrix);
            let device_path = glyph_path.transform(&trm);
            if !device_path.is_empty() {
                self.emit_text_glyph(device_path, render_mode);
            }
        }
        if vertical {
            let [w1, _vx, _vy] = font.vertical_metrics_cid(cid);
            let ty = w1 / 1000.0 * font_size + char_spacing + extra_advance;
            let advance = Matrix::translate(0.0, ty);
            self.gstate.text_matrix = self.gstate.text_matrix.concat(&advance);
        } else {
            let w0 = font.glyph_width_cid(cid);
            let tx = (w0 * font_size + char_spacing + extra_advance) * th;
            let advance = Matrix::translate(tx, 0.0);
            self.gstate.text_matrix = self.gstate.text_matrix.concat(&advance);
        }
    }

    /// Render a CID glyph using Unicode→cmap for the glyph shape but the CID
    /// width table for text advancement. Used for substitute fonts that don't
    /// have CID-to-GID mappings but can render via Unicode code points.
    fn render_cid_glyph_unicode_fallback(
        &mut self,
        font: &PdfFont,
        cid: u16,
        unicode: u32,
        font_size: f64,
        char_spacing: f64,
        th: f64,
        text_rise: f64,
        font_matrix: &Matrix,
        render_mode: i32,
        extra_advance: f64,
    ) {
        let vertical = font.wmode() == 1;
        // Try to render the glyph shape via Unicode mapping in the substitute font
        if let Some(glyph_path) = font.glyph_path_unicode(unicode as u16) {
            let text_state_matrix = if vertical {
                let [_w1, v_x, v_y] = font.vertical_metrics_cid(cid);
                Matrix::new(
                    font_size,
                    0.0,
                    0.0,
                    font_size,
                    -v_x / 1000.0 * font_size,
                    -v_y / 1000.0 * font_size,
                )
            } else {
                Matrix::new(font_size * th, 0.0, 0.0, font_size, 0.0, text_rise)
            };
            let trm = self
                .gstate
                .ctm
                .concat(&self.gstate.text_matrix)
                .concat(&text_state_matrix)
                .concat(font_matrix);
            let device_path = glyph_path.transform(&trm);
            if !device_path.is_empty() {
                self.emit_text_glyph(device_path, render_mode);
            }
        }
        if vertical {
            let [w1, _vx, _vy] = font.vertical_metrics_cid(cid);
            let ty = w1 / 1000.0 * font_size + char_spacing + extra_advance;
            let advance = Matrix::translate(0.0, ty);
            self.gstate.text_matrix = self.gstate.text_matrix.concat(&advance);
        } else {
            let w0 = font.glyph_width_cid(cid);
            let tx = (w0 * font_size + char_spacing + extra_advance) * th;
            let advance = Matrix::translate(tx, 0.0);
            self.gstate.text_matrix = self.gstate.text_matrix.concat(&advance);
        }
    }

    /// Render a single glyph from a WinAnsi byte via Unicode→cmap, bypassing CID.
    /// Used for malformed PDFs that embed 1-byte literal strings in CID fonts.
    fn render_unicode_glyph(
        &mut self,
        byte: u8,
        font_size: f64,
        char_spacing: f64,
        th: f64,
        text_rise: f64,
        font_matrix: &Matrix,
        render_mode: i32,
    ) {
        let unicode = font::winansi_byte_to_unicode(byte);
        if let Some(glyph_path) = self
            .current_font
            .as_ref()
            .and_then(|f| f.glyph_path_unicode(unicode))
        {
            let text_state_matrix =
                Matrix::new(font_size * th, 0.0, 0.0, font_size, 0.0, text_rise);
            let trm = self
                .gstate
                .ctm
                .concat(&self.gstate.text_matrix)
                .concat(&text_state_matrix)
                .concat(font_matrix);
            let device_path = glyph_path.transform(&trm);
            if !device_path.is_empty() {
                self.emit_text_glyph(device_path, render_mode);
            }
        }
        let w0 = self
            .current_font
            .as_ref()
            .map(|f| f.glyph_width_unicode(unicode))
            .unwrap_or(0.0);
        let tx = (w0 * font_size + char_spacing) * th;
        let advance = Matrix::translate(tx, 0.0);
        self.gstate.text_matrix = self.gstate.text_matrix.concat(&advance);
    }

    /// Render a single Type 3 glyph by interpreting its CharProc content stream.
    ///
    /// A CharProc may legitimately show text, including text in another Type 3
    /// font. Nothing stops it from showing *its own* glyph, so this path is
    /// bounded by [`MAX_CONTENT_NESTING`] like the Form XObject path: the
    /// increment around `interpret_stream` below is only load-bearing if
    /// somebody checks it.
    fn show_type3_glyph(&mut self, font: &PdfFont, char_code: u8) {
        if self.depth >= MAX_CONTENT_NESTING {
            return;
        }
        let proc_data = match font.type3_char_proc(char_code) {
            Some(data) => data.to_vec(),
            None => return,
        };
        let resources = match font.type3_resources() {
            Some(r) => r.clone(),
            None => return,
        };

        let font_size = self.gstate.font_size;
        let text_rise = self.gstate.text_rise;
        let font_matrix = font.font_matrix();

        // Build the text rendering matrix: CTM × Tm × [fontSize*Th 0 0 fontSize 0 rise] × FontMatrix
        let th = self.gstate.horizontal_scaling;
        let text_state_matrix = Matrix::new(font_size * th, 0.0, 0.0, font_size, 0.0, text_rise);
        let trm = self
            .gstate
            .ctm
            .concat(&self.gstate.text_matrix)
            .concat(&text_state_matrix)
            .concat(&font_matrix);
        // Interpret the CharProc stream with TRM as the CTM.
        // Save current state and swap in a fresh display list.
        let stack_depth_before = self.gstate_stack.len();
        self.gstate_stack.push(self.gstate.clone());
        // Merge the Type 3 font's resources with the page resources: the font's
        // own entries take priority (e.g. XObjects for emoji glyphs), but missing
        // categories fall back to the page resources (e.g. fonts referenced by
        // CharProcs that don't declare their own /Font sub-dict).
        let mut merged = self.resources.clone();
        for (key, value) in resources.entries() {
            merged.insert(key.clone(), value.clone());
        }
        let saved_resources = std::mem::replace(&mut self.resources, merged);
        let saved_display_list = std::mem::take(&mut self.display_list);
        let saved_path = std::mem::take(&mut self.current_path);
        let saved_point = self.current_point.take();
        let saved_subpath = self.subpath_start.take();
        let saved_font = self.current_font.clone();
        let saved_in_text = self.in_text;
        let saved_content_stream_ctm = self.content_stream_ctm;
        let saved_mc_stack = std::mem::take(&mut self.mc_stack);

        self.gstate.ctm = trm;
        // Pattern Matrix maps pattern space to the "default coordinate system
        // of the content stream" — for Type 3 CharProcs, that's the TRM.
        self.content_stream_ctm = trm;

        let saved_d1 = self.d1_color_suppressed;
        self.d1_color_suppressed = false;
        self.depth += 1;
        let _ = self.interpret_stream(&proc_data);
        self.depth -= 1;
        self.d1_color_suppressed = saved_d1;
        // Collect glyph display elements and append to main display list
        let glyph_elements = std::mem::replace(&mut self.display_list, saved_display_list);
        self.resources = saved_resources;
        self.current_path = saved_path;
        self.current_point = saved_point;
        self.subpath_start = saved_subpath;
        self.current_font = saved_font;
        self.in_text = saved_in_text;
        self.content_stream_ctm = saved_content_stream_ctm;
        self.mc_stack = saved_mc_stack;
        // Restore state: truncate any extra gstate_stack entries left by
        // unmatched q/Q inside the CharProc (e.g., if the EI parser consumed Q).
        self.gstate_stack.truncate(stack_depth_before + 1);
        if let Some(saved) = self.gstate_stack.pop() {
            self.gstate = saved;
        }

        // Append all glyph elements to the main display list
        for elem in glyph_elements.into_elements() {
            self.display_list.push(elem);
        }
    }

    /// Emit a text glyph to the display list based on the text rendering mode.
    ///
    /// Modes: 0=fill, 1=stroke, 2=fill+stroke, 3=invisible,
    ///        4-7=same as 0-3 but add to clipping path (clipping not yet implemented).
    fn emit_text_glyph(&mut self, device_path: PsPath, render_mode: i32) {
        let mode = render_mode & 3; // strip clip bit
        let clip = render_mode & 4 != 0; // bit 2 = add to text clip

        match mode {
            0 => {
                // Fill only
                self.emit_text_fill(device_path.clone());
            }
            1 => {
                // Stroke only
                self.emit_text_stroke(device_path.clone());
            }
            2 => {
                // Fill then stroke
                self.emit_text_fill(device_path.clone());
                self.emit_text_stroke(device_path.clone());
            }
            _ => {} // mode 3 = invisible
        }

        // Modes 4-7: accumulate glyph path into text clip
        if clip {
            let tcp = self.text_clip_path.get_or_insert_with(PsPath::new);
            tcp.segments.extend_from_slice(&device_path.segments);
        }
    }

    /// Emit a text glyph fill, handling shading patterns, tiling patterns,
    /// or solid color fills.
    fn emit_text_fill(&mut self, path: PsPath) {
        if let Some(shading_box) = self.gstate.fill_shading_pattern.clone() {
            // PatternType 2 (shading pattern): clip to glyph path, emit shading.
            // Wrap in a Group to scope the clip.
            let bbox = path_device_bbox(&path);
            let mut group_dl = DisplayList::new();
            group_dl.push(DisplayElement::Clip {
                path,
                params: ClipParams {
                    fill_rule: FillRule::NonZeroWinding,
                    ctm: Matrix::identity(),
                    stroke_params: None,
                },
            });
            for elem in shading_box.0.elements() {
                group_dl.push(elem.clone());
            }
            self.display_list.push(DisplayElement::Group {
                elements: group_dl,
                params: GroupParams {
                    bbox,
                    isolated: true,
                    knockout: false,
                    blend_mode: self.gstate.blend_mode,
                    alpha: self.gstate.fill_alpha,
                    color_space: stet_graphics::display_list::GroupColorSpace::Inherited,
                },
            });
        } else if let Some(pattern) = self.gstate.fill_pattern.clone() {
            self.display_list.push(DisplayElement::PatternFill {
                params: PatternFillParams {
                    path,
                    fill_rule: FillRule::NonZeroWinding,
                    tile: pattern.tile,
                    pattern_matrix: pattern.pattern_matrix,
                    bbox: pattern.bbox,
                    xstep: pattern.x_step,
                    ystep: pattern.y_step,
                    paint_type: pattern.paint_type,
                    underlying_color: if pattern.paint_type == 2 {
                        Some(self.gstate.fill_color.clone())
                    } else {
                        None
                    },
                    pattern_id: pattern.pattern_id,
                    device_space_tile: false,
                    flip_tile_y: false,
                    stroke_params: None,
                    overprint_mode: if self.gstate.overprint {
                        self.gstate.overprint_mode
                    } else {
                        0
                    },
                },
            });
        } else {
            let mut params = self.gstate.fill_params(FillRule::NonZeroWinding);
            params.is_text_glyph = true;
            self.display_list
                .push(DisplayElement::Fill { path, params });
        }
    }

    /// Emit a text glyph stroke, handling shading patterns, tiling patterns,
    /// or solid color strokes.
    fn emit_text_stroke(&mut self, path: PsPath) {
        // Shading pattern stroke: clip to stroked outline of glyph, emit shading.
        if let Some(shading_box) = self.gstate.stroke_shading_pattern.clone() {
            let mut sp = self.gstate.stroke_params();
            sp.is_text_glyph = true;
            // Expand bbox by half the (already device-scaled) stroke width.
            let mut bbox = path_device_bbox(&path);
            let half_w = sp.line_width * 0.5;
            bbox[0] -= half_w;
            bbox[1] -= half_w;
            bbox[2] += half_w;
            bbox[3] += half_w;
            let mut group_dl = DisplayList::new();
            group_dl.push(DisplayElement::Clip {
                path,
                params: ClipParams {
                    fill_rule: FillRule::NonZeroWinding,
                    ctm: Matrix::identity(),
                    stroke_params: Some(sp),
                },
            });
            for elem in shading_box.0.elements() {
                group_dl.push(elem.clone());
            }
            self.display_list.push(DisplayElement::Group {
                elements: group_dl,
                params: GroupParams {
                    bbox,
                    isolated: true,
                    knockout: false,
                    blend_mode: self.gstate.blend_mode,
                    alpha: self.gstate.stroke_alpha,
                    color_space: stet_graphics::display_list::GroupColorSpace::Inherited,
                },
            });
            return;
        }

        // Tiling pattern stroke: emit PatternFill with stroke_params so the
        // renderer tiles the pattern over the stroked outline of the glyph.
        if let Some(pattern) = self.gstate.stroke_pattern.clone() {
            let mut sp = self.gstate.stroke_params();
            sp.is_text_glyph = true;
            self.display_list.push(DisplayElement::PatternFill {
                params: PatternFillParams {
                    path,
                    fill_rule: FillRule::NonZeroWinding,
                    tile: pattern.tile,
                    pattern_matrix: pattern.pattern_matrix,
                    bbox: pattern.bbox,
                    xstep: pattern.x_step,
                    ystep: pattern.y_step,
                    paint_type: pattern.paint_type,
                    underlying_color: if pattern.paint_type == 2 {
                        Some(self.gstate.stroke_color.clone())
                    } else {
                        None
                    },
                    pattern_id: pattern.pattern_id,
                    device_space_tile: false,
                    flip_tile_y: false,
                    stroke_params: Some(sp),
                    overprint_mode: if self.gstate.overprint {
                        self.gstate.overprint_mode
                    } else {
                        0
                    },
                },
            });
            return;
        }

        let mut params = self.gstate.stroke_params();
        params.is_text_glyph = true;
        self.display_list
            .push(DisplayElement::Stroke { path, params });
    }

    // === Marked content operators ===

    /// Handle BDC (begin marked content with properties). Checks for Optional
    /// Content Group references and wraps content inside OCG blocks in an
    /// `OcgGroup` display list element for deferred visibility filtering at
    /// render time. Every BDC pushes a frame onto `mc_stack` — only `/OC`
    /// BDCs are `Ocg` frames; other BDCs are `Other` placeholders so the
    /// stack stays balanced with EMC.
    fn op_bdc(&mut self) -> Result<(), PdfError> {
        let props = self.operand_stack.pop();
        let tag = self.operand_stack.pop();

        let is_oc = matches!(&tag, Some(Operand::Name(n)) if n == b"OC");
        if !is_oc {
            self.mc_stack.push(MarkedContentFrame::Other);
            return Ok(());
        }

        // The properties operand is a name referencing /Properties in resources
        let mut pushed = false;
        if let Some(Operand::Name(prop_name)) = props
            && let Some(props_dict) = self.resolve_resource_subdict(b"Properties")
            && let Some(ocg_obj) = props_dict.get(&prop_name)
        {
            let visibility = self.build_visibility(ocg_obj);
            let parent_list = std::mem::replace(&mut self.display_list, DisplayList::new());
            self.mc_stack.push(MarkedContentFrame::Ocg {
                parent_list,
                visibility,
            });
            pushed = true;
        }
        if !pushed {
            // OC BDC without a resolvable properties entry still opens a
            // section that EMC must close.
            self.mc_stack.push(MarkedContentFrame::Other);
        }

        Ok(())
    }

    /// Check whether an OCG/OCMD reference is OFF.
    /// Handles both direct OCG references (`/Type /OCG`) and OCMD wrappers
    /// (`/Type /OCMD` with `/OCGs` array and optional `/P` visibility policy).
    fn is_ocg_off(&self, ocg_obj: &PdfObj) -> bool {
        // Direct OCG reference — check its object number
        if let Some((obj_num, _)) = ocg_obj.as_ref() {
            // Dereference to see if it's an OCMD wrapper
            if let Ok(resolved) = self.resolver.deref(ocg_obj) {
                if let Some(dict) = resolved.as_dict() {
                    if dict.get_name(b"Type") == Some(b"OCMD") {
                        return self.is_ocmd_off(dict);
                    }
                }
            }
            // Plain OCG reference
            return self.ocg_off.contains(&obj_num);
        }
        // Inline dict (unusual but possible)
        if let Some(dict) = ocg_obj.as_dict() {
            if dict.get_name(b"Type") == Some(b"OCMD") {
                return self.is_ocmd_off(dict);
            }
        }
        false
    }

    /// Build an [`OcgVisibility`] from an `/OC BDC` properties reference
    /// or an XObject `/OC` entry.
    ///
    /// - Direct OCG ref → [`OcgVisibility::Single`] driven by
    ///   `/OCProperties /D /OFF` membership.
    /// - OCMD with `/VE` → [`OcgVisibility::Expression`].
    /// - OCMD with `/OCGs` (and optional `/P`) →
    ///   [`OcgVisibility::Membership`] with the parsed policy.
    /// - Unparseable shape → `Single { ocg_id: 0, default_visible:
    ///   <baked> }` so the renderer falls back to the document's
    ///   static evaluation.
    fn build_visibility(&self, ocg_obj: &PdfObj) -> OcgVisibility {
        let resolved = self.resolver.deref(ocg_obj).ok();
        let dict = resolved.as_ref().and_then(|o| o.as_dict());

        if let Some(dict) = dict
            && dict.get_name(b"Type") == Some(b"OCMD")
        {
            // Default-visible for the whole OCMD = its static
            // evaluation under the document's default config. Acts as
            // the fast-path return value of `LayerSet::evaluate` when
            // no leaf has been overridden.
            let default_visible = !self.is_ocg_off(ocg_obj);
            // OCMD parsing produces Membership or Expression. We
            // don't have a `WarningSink` plumbed through the content
            // stream pipeline yet, so route warnings into a local
            // throwaway sink — `/VE` malformations are infrequent and
            // already fall back to AnyOn membership.
            let throwaway = crate::diagnostics::WarningSink::new();
            return crate::layers::ocmd::build_ocmd_visibility(
                self.resolver,
                dict,
                default_visible,
                &throwaway,
            );
        }

        if let Some((ocg_id, _)) = ocg_obj.as_ref() {
            return OcgVisibility::Single {
                ocg_id,
                default_visible: !self.ocg_off.contains(&ocg_id),
            };
        }

        // Inline OCG dict or other unparseable shape.
        OcgVisibility::Single {
            ocg_id: 0,
            default_visible: !self.is_ocg_off(ocg_obj),
        }
    }

    /// Evaluate an OCMD (Optional Content Membership Dictionary).
    /// `/P` policy: AnyOn (default) = visible if ANY listed OCG is on;
    /// AnyOff = visible if ANY is off; AllOn = visible if ALL are on;
    /// AllOff = visible if ALL are off.
    fn is_ocmd_off(&self, ocmd: &PdfDict) -> bool {
        let policy = ocmd.get_name(b"P").unwrap_or(b"AnyOn");

        // Collect OCG object numbers from /OCGs (may be a single ref or array)
        let mut ocg_nums = Vec::new();
        if let Some(ocgs_obj) = ocmd.get(b"OCGs") {
            match ocgs_obj {
                PdfObj::Ref(num, _) => ocg_nums.push(*num),
                PdfObj::Array(arr) => {
                    for item in arr {
                        if let Some((num, _)) = item.as_ref() {
                            ocg_nums.push(num);
                        }
                    }
                }
                _ => {}
            }
        }
        if ocg_nums.is_empty() {
            return false;
        }

        // Evaluate visibility based on policy, then return whether suppressed
        let visible = match policy {
            b"AllOn" => ocg_nums.iter().all(|n| !self.ocg_off.contains(n)),
            b"AnyOff" => ocg_nums.iter().any(|n| self.ocg_off.contains(n)),
            b"AllOff" => ocg_nums.iter().all(|n| self.ocg_off.contains(n)),
            _ /* AnyOn */ => ocg_nums.iter().any(|n| !self.ocg_off.contains(n)),
        };
        !visible
    }

    // === XObject operator ===

    fn op_do(&mut self) -> Result<(), PdfError> {
        let name = self
            .operand_stack
            .last()
            .and_then(|o| o.as_name())
            .ok_or(PdfError::Other("Do: expected name".into()))?
            .to_vec();

        // Look up XObject in resources (may be an indirect reference)
        let xobj_dict = self
            .resolve_resource_subdict(b"XObject")
            .ok_or(PdfError::Other("no XObject resources".into()))?;
        let xobj_ref = xobj_dict.get(&name).ok_or_else(|| {
            PdfError::Other(format!(
                "XObject /{} not found",
                String::from_utf8_lossy(&name)
            ))
        })?;
        // Keep the original ref for stream_data_from_obj (needed for encryption)
        let xobj_ref_clone = xobj_ref.clone();
        let xobj = self.resolver.deref(xobj_ref)?;
        let dict = xobj
            .as_dict()
            .ok_or(PdfError::Other("XObject is not a stream".into()))?;

        // Check Optional Content visibility on the XObject itself.
        // Instead of suppressing content, wrap it in an OcgGroup so visibility
        // can be toggled at render time.
        let xobj_visibility = dict.get(b"OC").map(|oc_obj| self.build_visibility(oc_obj));

        let mut wrapped = false;
        if let Some(visibility) = xobj_visibility {
            let parent_list = std::mem::replace(&mut self.display_list, DisplayList::new());
            self.mc_stack.push(MarkedContentFrame::Ocg {
                parent_list,
                visibility,
            });
            wrapped = true;
        }

        let subtype = dict.get_name(b"Subtype").unwrap_or(b"");
        match subtype {
            b"Image" => self.handle_image_xobject(&xobj_ref_clone, dict)?,
            b"Form" => self.handle_form_xobject(&xobj_ref_clone, dict)?,
            _ => {}
        }

        // Close the XObject OCG wrapper if one was opened.
        if wrapped {
            if let Some(MarkedContentFrame::Ocg {
                parent_list,
                visibility,
            }) = self.mc_stack.pop()
            {
                let ocg_list = std::mem::replace(&mut self.display_list, parent_list);
                self.display_list.push(DisplayElement::OcgGroup {
                    elements: ocg_list,
                    visibility,
                });
            }
        }

        Ok(())
    }

    /// Handle an Image XObject.
    fn handle_image_xobject(&mut self, obj: &PdfObj, dict: &PdfDict) -> Result<(), PdfError> {
        // Check image cache: if we've already processed this XObject, reuse the
        // decoded data with fresh graphics-state params (CTM, alpha, blend, etc.).
        if let PdfObj::Ref(obj_num, _) = obj {
            if let Some(cached) = self.image_cache.get(obj_num).cloned() {
                return self.emit_cached_image(cached);
            }
        }

        // Width/Height may be indirect references in some PDFs.
        //
        // Both are validated before the cast rather than after: every buffer
        // size and loop bound below derives from them, and an `as u32` on an
        // unchecked file integer both truncates (`/Width 4294967297` becomes
        // 1) and lets `width * height` wrap.
        let width = validate_image_dimension(self.resolve_dict_int(dict, b"Width"))
            .ok_or(PdfError::Other("image has missing or invalid Width".into()))?;
        let height = validate_image_dimension(self.resolve_dict_int(dict, b"Height")).ok_or(
            PdfError::Other("image has missing or invalid Height".into()),
        )?;
        validate_image_size(width, height)
            .ok_or(PdfError::Other("image dimensions too large".into()))?;

        // Check for image mask (1-bit stencil painted with current fill color)
        let is_image_mask = dict
            .get(b"ImageMask")
            .and_then(|o| match o {
                PdfObj::Bool(b) => Some(*b),
                _ => None,
            })
            .unwrap_or(false);

        let bpc = if is_image_mask {
            1
        } else {
            validate_bits_per_component(dict.get_int(b"BitsPerComponent"))
                .ok_or(PdfError::Other("image has invalid BitsPerComponent".into()))?
        };

        // Per ISO 32000 §11.3.4 a per-image `/Intent` overrides the gstate
        // `/RI`. GWG 17.2 (JPEG2000 + ICCBasedRGB) calibrates an Adobe RGB
        // image colour against a CMYK swatch under `/RelativeColorimetric`;
        // ignoring this override forces the proofing chain through the
        // gstate's default Perceptual intent and produces a visibly
        // different sRGB → the test's "X marker" appears.
        let gstate_intent = self.gstate.rendering_intent;
        let image_intent = match dict
            .get(b"Intent")
            .and_then(|o| self.resolver.deref(o).ok())
        {
            Some(PdfObj::Name(n)) => match n.as_slice() {
                b"Perceptual" => 0u8,
                b"RelativeColorimetric" => 1,
                b"Saturation" => 2,
                b"AbsoluteColorimetric" => 3,
                _ => gstate_intent,
            },
            _ => gstate_intent,
        };

        // Resolve color space
        let has_explicit_cs = dict.get(b"ColorSpace").is_some();
        let resolved_cs = if is_image_mask {
            None
        } else if let Some(cs_obj) = dict.get(b"ColorSpace") {
            match resolve_color_space_obj(cs_obj, self.resolver) {
                Ok(cs) => Some(cs),
                Err(_) => {
                    // Damaged PDF: color space reference is invalid (e.g. points to
                    // an XRef stream in a corrupt linearized file). Fall back to a
                    // device color space based on BPC/component count heuristics.
                    Some(match bpc {
                        1 => ResolvedColorSpace::DeviceGray,
                        _ => ResolvedColorSpace::DeviceRGB,
                    })
                }
            }
        } else {
            // No ColorSpace in dict — will be inferred from JPX data below
            Some(ResolvedColorSpace::DeviceRGB)
        };

        let polarity = if is_image_mask {
            if let Some(arr) = dict.get_array(b"Decode") {
                let vals: Vec<f64> = arr.iter().filter_map(|o| o.as_f64()).collect();
                vals.len() >= 2 && vals[0] > 0.5
            } else {
                false
            }
        } else {
            false
        };

        // SMaskInData: JPX streams can embed an alpha channel.
        // 0 (default) = no embedded mask, 1 or 2 = alpha channel present in JP2 data.
        let smask_in_data = dict.get_int(b"SMaskInData").unwrap_or(0);

        let filter_name_raw = dict.get_name(b"Filter");
        let filter_is_dct = matches!(filter_name_raw, Some(b"DCTDecode" | b"DCT"));
        // JPXDecode may be a single filter name or inside a filter array
        let filter_is_jpx = matches!(filter_name_raw, Some(b"JPXDecode" | b"JPX"))
            || dict.get_array(b"Filter").is_some_and(|arr| {
                arr.iter()
                    .any(|f| matches!(f.as_name(), Some(b"JPXDecode" | b"JPX")))
            });

        // Decode the stream data. For DCTDecode with a bogus SOF height
        // (streaming encoder placeholder like 60000), patch the JPEG header
        // to the PDF dict height before decoding to avoid wasting time on
        // excess zero-filled rows.
        let cs_is_indexed = matches!(resolved_cs, Some(ResolvedColorSpace::Indexed { .. }));
        let sample_data = if filter_is_dct {
            if let Some(raw) = self.resolver.raw_stream_bytes(obj)
                && let Some((_jw, jh)) = crate::filters::jpeg_dimensions(raw)
                && jh > height * 2
            {
                let mut patched = raw.to_vec();
                crate::filters::patch_jpeg_sof_height(&mut patched, height as u16);
                crate::filters::decode_stream(
                    &patched,
                    &[crate::filters::Filter::DCTDecode],
                    &[],
                    None,
                )?
            } else {
                self.resolver.stream_data_from_obj(obj)?
            }
        } else if filter_is_jpx && cs_is_indexed {
            // JPXDecode + PDF Indexed color space: skip JP2-internal palette
            // resolution so the PDF's own lookup table handles depalettization.
            // Some JP2 files declare wrong palette column precision (e.g. 4-bit
            // for 8-bit values), causing hayro's palette expansion to corrupt colors.
            #[cfg(feature = "jpx")]
            {
                if let Some(raw) = self.resolver.raw_stream_bytes(obj) {
                    let jp2_data = crate::filters::decode_pre_jpx(raw, dict);
                    let (mut data, bpc) = crate::filters::decode_jpx_no_palette(&jp2_data)?;
                    // hayro normalizes sub-8-bit data to 0-255 grayscale.
                    // Un-normalize back to raw palette indices using the
                    // codestream's original bit depth.
                    if bpc < 8 {
                        let max_val = ((1u32 << bpc) - 1) as f64;
                        for b in data.iter_mut() {
                            *b = (*b as f64 / 255.0 * max_val).round() as u8;
                        }
                    }
                    data
                } else {
                    self.resolver.stream_data_from_obj(obj)?
                }
            }
            #[cfg(not(feature = "jpx"))]
            {
                self.resolver.stream_data_from_obj(obj)?
            }
        } else {
            self.resolver.stream_data_from_obj(obj)?
        };

        // For DCTDecode, the JPEG's actual dimensions may differ from the PDF
        // dict's /Width and /Height.  Trust the image header when they disagree,
        // but only when the JPEG dimensions are close to the PDF dict values.
        let (width, height) = if filter_is_dct {
            if let Some(raw) = self.resolver.raw_stream_bytes(obj)
                && let Some((jw, jh)) = crate::filters::jpeg_dimensions(raw)
                && (jw != width || jh != height)
                && jw <= width * 2
                && jh <= height * 2
            {
                (jw, jh)
            } else {
                (width, height)
            }
        } else if filter_is_jpx {
            #[cfg(feature = "jpx")]
            {
                // JPXDecode: the JPEG 2000 stream may have different dimensions
                // than the PDF dict (malformed but common). Decode the filter chain
                // up to but not including JPXDecode to get the raw JP2 data.
                if let Some(raw) = self.resolver.raw_stream_bytes(obj) {
                    // Apply preceding filters (e.g. ASCIIHexDecode) to get JP2 data
                    let jp2_data = crate::filters::decode_pre_jpx(raw, dict);
                    if let Some((jw, jh)) = crate::filters::jpx_dimensions(&jp2_data)
                        && (jw != width || jh != height)
                    {
                        (jw, jh)
                    } else {
                        (width, height)
                    }
                } else {
                    (width, height)
                }
            }
            #[cfg(not(feature = "jpx"))]
            {
                (width, height)
            }
        } else {
            (width, height)
        };

        // For JPXDecode, the JP2 decoder returns all components present in the
        // codestream, which may include alpha or other channels beyond what the
        // PDF's explicit ColorSpace expects. With SMaskInData >= 1 the extra
        // alpha component is exposed as a soft mask; with SMaskInData == 0
        // (default), per ISO 32000-2 §13.5.7.2 the encoded soft-mask information
        // shall be ignored — drop the extras so the gray/RGB/CMYK pipeline
        // doesn't reinterpret interleaved alpha bytes as image samples.
        // When no explicit ColorSpace is present, infer it from the decoded
        // data length.
        let (resolved_cs, sample_data, smask_in_data_alpha) =
            if !is_image_mask && filter_is_jpx && has_explicit_cs {
                let n_cs = resolved_cs
                    .as_ref()
                    .map_or(3, |cs| cs.num_components() as usize);
                let pixels = width as usize * height as usize;
                let decoded_comps = if pixels > 0 {
                    sample_data.len() / pixels
                } else {
                    n_cs
                };
                if smask_in_data >= 1 && decoded_comps == n_cs + 1 {
                    // Extract the alpha channel (last component per pixel)
                    let mut color_data = Vec::with_capacity(pixels.saturating_mul(n_cs));
                    let mut alpha_data = Vec::with_capacity(pixels);
                    for chunk in sample_data.chunks_exact(decoded_comps) {
                        color_data.extend_from_slice(&chunk[..n_cs]);
                        alpha_data.push(chunk[n_cs]);
                    }
                    (resolved_cs, color_data, Some(alpha_data))
                } else if decoded_comps > n_cs {
                    // Drop extra components (e.g. ignored alpha) — keep only the
                    // first n_cs samples of each pixel.
                    let mut color_data = Vec::with_capacity(pixels.saturating_mul(n_cs));
                    for chunk in sample_data.chunks_exact(decoded_comps) {
                        color_data.extend_from_slice(&chunk[..n_cs]);
                    }
                    (resolved_cs, color_data, None)
                } else {
                    // Component count matches (or is unexpectedly low) — pass through
                    (resolved_cs, sample_data, None)
                }
            } else if !is_image_mask && !has_explicit_cs {
                let pixels = width as usize * height as usize;
                if pixels > 0 {
                    let n_comps = sample_data.len() / pixels;
                    // For 4-component JPX images, check JP2 metadata to distinguish
                    // RGBA (sRGB + alpha) from CMYK. Without this, RGBA images get
                    // misidentified as CMYK, producing wrong colors (e.g., orange → blue).
                    if n_comps == 4 && self.is_jpx_rgba(obj) {
                        if smask_in_data >= 1 {
                            // SMaskInData: the JP2 alpha channel is the soft mask.
                            // Premultiply alpha (tiny-skia expects premultiplied RGBA).
                            let mut rgba = sample_data;
                            for chunk in rgba.chunks_exact_mut(4) {
                                let a = chunk[3] as u16;
                                if a == 0 {
                                    chunk[0] = 0;
                                    chunk[1] = 0;
                                    chunk[2] = 0;
                                } else if a < 255 {
                                    chunk[0] = ((chunk[0] as u16 * a + 127) / 255) as u8;
                                    chunk[1] = ((chunk[1] as u16 * a + 127) / 255) as u8;
                                    chunk[2] = ((chunk[2] as u16 * a + 127) / 255) as u8;
                                }
                            }
                            (None, rgba, None)
                        } else {
                            // No embedded mask — strip alpha from RGBA → RGB.
                            let mut rgb = Vec::with_capacity(pixels * 3);
                            for chunk in sample_data.chunks_exact(4) {
                                rgb.push(chunk[0]);
                                rgb.push(chunk[1]);
                                rgb.push(chunk[2]);
                            }
                            (Some(ResolvedColorSpace::DeviceRGB), rgb, None)
                        }
                    } else {
                        let cs = match n_comps {
                            1 => ResolvedColorSpace::DeviceGray,
                            4 => ResolvedColorSpace::DeviceCMYK,
                            _ => ResolvedColorSpace::DeviceRGB,
                        };
                        (Some(cs), sample_data, None)
                    }
                } else {
                    (resolved_cs, sample_data, None)
                }
            } else {
                (resolved_cs, sample_data, None)
            };

        // Image matrix: [width 0 0 -height 0 height] maps unit square to image
        let image_matrix =
            Matrix::new(width as f64, 0.0, 0.0, -(height as f64), 0.0, height as f64);

        // Imagemask with shading pattern fill: use SoftMasked to clip shading to mask shape
        if is_image_mask && self.gstate.fill_shading_pattern.is_some() {
            let shading_box = self.gstate.fill_shading_pattern.clone().unwrap();
            let row_bytes = width.div_ceil(8);
            let mut gray = vec![0u8; (width * height) as usize];
            for y in 0..height {
                for x in 0..width {
                    let byte_idx = (y * row_bytes + x / 8) as usize;
                    let bit_idx = 7 - (x % 8);
                    let bit = if byte_idx < sample_data.len() {
                        (sample_data[byte_idx] >> bit_idx) & 1
                    } else {
                        0
                    };
                    let painted = if polarity { bit == 1 } else { bit == 0 };
                    gray[(y * width + x) as usize] = if painted { 255 } else { 0 };
                }
            }

            let mut mask_dl = DisplayList::new();
            mask_dl.push(DisplayElement::Image {
                sample_data: Arc::new(gray),
                params: ImageParams {
                    width,
                    height,
                    color_space: ImageColorSpace::DeviceGray,
                    bits_per_component: 8,
                    ctm: self.gstate.ctm,
                    image_matrix,
                    interpolate: false,
                    mask_color: None,
                    alpha: 1.0,
                    blend_mode: 0,
                    overprint: false,
                    overprint_mode: 0,
                    opm_paired: false,
                    painted_channels: 0,
                    alpha_is_shape: false,
                    rendering_intent: 0,
                },
            });

            let mut content_dl = DisplayList::new();
            for elem in shading_box.0.elements() {
                content_dl.push(elem.clone());
            }

            let corners = [
                self.gstate.ctm.transform_point(0.0, 0.0),
                self.gstate.ctm.transform_point(width as f64, 0.0),
                self.gstate.ctm.transform_point(0.0, height as f64),
                self.gstate.ctm.transform_point(width as f64, height as f64),
            ];
            let x_min = corners.iter().map(|c| c.0).fold(f64::INFINITY, f64::min);
            let y_min = corners.iter().map(|c| c.1).fold(f64::INFINITY, f64::min);
            let x_max = corners
                .iter()
                .map(|c| c.0)
                .fold(f64::NEG_INFINITY, f64::max);
            let y_max = corners
                .iter()
                .map(|c| c.1)
                .fold(f64::NEG_INFINITY, f64::max);

            let parent_clip_bbox = self.current_clip_bbox();
            self.display_list.push(DisplayElement::SoftMasked {
                mask: mask_dl,
                content: content_dl,
                params: SoftMaskParams {
                    subtype: SoftMaskSubtype::Luminosity,
                    bbox: [x_min, y_min, x_max, y_max],
                    backdrop_color: None,
                    transfer_invert: false,
                    has_nested_mask_scope: false,
                    parent_clip_bbox,
                },
                mask_cache: Arc::new(Mutex::new(None)),
            });
            return Ok(());
        }

        // OPM 1 + overprint on + CMYK all-zero fill + no pattern: "no ink" means
        // don't paint.  Skip the ImageMask so underlying content shows through.
        // When a pattern IS active, the pattern provides the real color and
        // the ImageMask acts as a text stencil — it must still render.
        // NOTE: OPM only takes effect when overprint (OP/op) is enabled.
        if is_image_mask
            && self.gstate.overprint
            && self.gstate.overprint_mode == 1
            && self.gstate.fill_pattern.is_none()
            && self.gstate.fill_shading_pattern.is_none()
            && self.gstate.fill_color.native_cmyk == Some((0.0, 0.0, 0.0, 0.0))
        {
            return Ok(());
        }

        // Imagemask with tiling pattern fill: use SoftMasked to clip pattern to mask shape.
        // The ImageMask provides the text stencil and the pattern provides the color.
        // We emit tile images directly (composing their CTM with the pattern matrix)
        // rather than using PatternFill, because the pattern tile covers the full page
        // and each strip has unique image data — the tiling renderer can't handle this
        // efficiently.
        if is_image_mask && self.gstate.fill_pattern.is_some() {
            let pattern = self.gstate.fill_pattern.clone().unwrap();
            let row_bytes = width.div_ceil(8);
            let mut gray = vec![0u8; (width * height) as usize];
            for y in 0..height {
                for x in 0..width {
                    let byte_idx = (y * row_bytes + x / 8) as usize;
                    let bit_idx = 7 - (x % 8);
                    let bit = if byte_idx < sample_data.len() {
                        (sample_data[byte_idx] >> bit_idx) & 1
                    } else {
                        0
                    };
                    let painted = if polarity { bit == 1 } else { bit == 0 };
                    gray[(y * width + x) as usize] = if painted { 255 } else { 0 };
                }
            }

            let mut mask_dl = DisplayList::new();
            mask_dl.push(DisplayElement::Image {
                sample_data: Arc::new(gray),
                params: ImageParams {
                    width,
                    height,
                    color_space: ImageColorSpace::DeviceGray,
                    bits_per_component: 8,
                    ctm: self.gstate.ctm,
                    image_matrix,
                    interpolate: false,
                    mask_color: None,
                    alpha: 1.0,
                    blend_mode: 0,
                    overprint: false,
                    overprint_mode: 0,
                    opm_paired: false,
                    painted_channels: 0,
                    alpha_is_shape: false,
                    rendering_intent: 0,
                },
            });

            let corners = [
                self.gstate.ctm.transform_point(0.0, 0.0),
                self.gstate.ctm.transform_point(width as f64, 0.0),
                self.gstate.ctm.transform_point(0.0, height as f64),
                self.gstate.ctm.transform_point(width as f64, height as f64),
            ];
            let x_min = corners.iter().map(|c| c.0).fold(f64::INFINITY, f64::min);
            let y_min = corners.iter().map(|c| c.1).fold(f64::INFINITY, f64::min);
            let x_max = corners
                .iter()
                .map(|c| c.0)
                .fold(f64::NEG_INFINITY, f64::max);
            let y_max = corners
                .iter()
                .map(|c| c.1)
                .fold(f64::NEG_INFINITY, f64::max);

            // Emit tile images directly as content, composing their CTM with
            // the pattern matrix to place them in device space.
            let pm = &pattern.pattern_matrix;
            let mut content_dl = DisplayList::new();
            for elem in pattern.tile.elements() {
                if let DisplayElement::Image {
                    sample_data: sd,
                    params: ip,
                } = elem
                {
                    let dev_ctm = pm.multiply(&ip.ctm);
                    content_dl.push(DisplayElement::Image {
                        sample_data: sd.clone(),
                        params: ImageParams {
                            ctm: dev_ctm,
                            ..ip.clone()
                        },
                    });
                }
            }

            let parent_clip_bbox = self.current_clip_bbox();
            self.display_list.push(DisplayElement::SoftMasked {
                mask: mask_dl,
                content: content_dl,
                params: SoftMaskParams {
                    subtype: SoftMaskSubtype::Luminosity,
                    bbox: [x_min, y_min, x_max, y_max],
                    backdrop_color: None,
                    transfer_invert: false,
                    has_nested_mask_scope: false,
                    parent_clip_bbox,
                },
                mask_cache: Arc::new(Mutex::new(None)),
            });
            return Ok(());
        }

        // For multi-input DeviceN images, evaluate the tinting function directly
        // per pixel to avoid lossy N-D lookup table interpolation.  A pre-sampled
        // table with spd^N entries can never faithfully represent all 256^N possible
        // 8-bit input combinations for N≥2.  Direct evaluation is exact and fast
        // enough for typical image sizes.
        let (color_space, sample_data) = if !is_image_mask
            && let Some(ResolvedColorSpace::DeviceN {
                names,
                alt,
                tint_fn: Some(func),
            }) = resolved_cs.as_ref()
            && names.len() >= 2
            && matches!(
                alt.as_ref(),
                ResolvedColorSpace::DeviceGray | ResolvedColorSpace::DeviceRGB
            ) {
            let ni = names.len();
            let npixels = width as usize * height as usize;
            let mut rgba = vec![255u8; npixels * 4];
            let mut inputs = vec![0.0f64; ni];
            for i in 0..npixels {
                let si = i * ni;
                for (c, inp) in inputs.iter_mut().enumerate() {
                    *inp = sample_data.get(si + c).copied().unwrap_or(0) as f64 / 255.0;
                }
                let out = func.evaluate(&inputs);
                let (r, g, b) = color_space::alt_comps_to_rgb_f64(&out, alt);
                let pi = i * 4;
                rgba[pi] = r;
                rgba[pi + 1] = g;
                rgba[pi + 2] = b;
            }
            (ImageColorSpace::PreconvertedRGBA, rgba)
        } else if is_image_mask {
            (
                ImageColorSpace::Mask {
                    color: self.gstate.fill_color.clone(),
                    polarity,
                    spot_color: self.gstate.fill_spot_color.clone(),
                },
                sample_data,
            )
        } else if let Some(ref rcs) = resolved_cs {
            (to_image_color_space(rcs), sample_data)
        } else {
            // resolved_cs is None for JPX RGBA with SMaskInData — already RGBA
            (ImageColorSpace::PreconvertedRGBA, sample_data)
        };

        // JPXDecode with internal palette (pclr): hayro-jpeg2000 applies the JP2 palette
        // and returns expanded data (e.g. 3-component RGB for a 1-component codestream).
        // Per PDF spec 7.4.9, the JP2 palette is applied before the PDF color space.
        // When the PDF says Indexed but the JP2 already expanded the palette,
        // switch to the base color space since the data is already depalettized.
        let color_space = if !is_image_mask {
            if let ImageColorSpace::Indexed { base, .. } = &color_space {
                let expected_1comp = (width * height) as usize;
                let base_n = base.num_components() as usize;
                if sample_data.len() == expected_1comp * base_n && base_n > 1 {
                    *base.clone()
                } else {
                    color_space
                }
            } else {
                color_space
            }
        } else {
            color_space
        };

        let interpolate = dict
            .get(b"Interpolate")
            .and_then(|o| match o {
                PdfObj::Bool(b) => Some(*b),
                _ => None,
            })
            .unwrap_or(false);

        // Mask color (for color-key masking) or explicit stencil mask (stream ref)
        let (mask_color, explicit_mask_data) = match dict.get(b"Mask") {
            Some(PdfObj::Array(arr)) => {
                // Color-key mask: array of component ranges
                let mc: Vec<u8> = arr
                    .iter()
                    .filter_map(|o| o.as_int().map(|n| n as u8))
                    .collect();
                (Some(mc), None)
            }
            Some(_mask_obj) => {
                // Explicit stencil mask: indirect reference to 1-bit ImageMask stream
                let mask_alpha = self
                    .resolve_explicit_mask(dict, width, height)
                    .unwrap_or(None);
                (None, mask_alpha)
            }
            None => (None, None),
        };

        // Convert data if BPC != 8 (but NOT for image masks — keep raw 1-bit data).
        // JPXDecode (JPEG 2000) and DCTDecode (JPEG) always produce 8-bit output
        // regardless of the /BitsPerComponent value in the PDF dict.
        let is_jpx = filter_is_jpx;
        let is_dct = filter_is_dct;
        let is_indexed = matches!(&color_space, ImageColorSpace::Indexed { .. });
        // Expand sub-byte samples (1/2/4 BPC) to 8-bit since they're packed
        // with geometry-dependent alignment. Downsample 16-bit to 8-bit (take
        // high byte) — downstream ICC and color conversion assumes 8-bit data.
        let (sample_data, display_bpc) =
            if is_image_mask || bpc == 8 || bpc == 0 || is_jpx || is_dct {
                (sample_data, if is_dct || is_jpx { 8 } else { bpc })
            } else if bpc == 16 {
                // Take high byte of each 16-bit big-endian sample
                (sample_data.chunks(2).map(|c| c[0]).collect(), 8)
            } else if bpc > 8 {
                (sample_data, bpc)
            } else {
                (
                    expand_bits_to_bytes(
                        &sample_data,
                        bpc,
                        width,
                        height,
                        color_space.num_components(),
                        is_indexed,
                    ),
                    8,
                )
            };

        // Apply /Decode array if present (maps sample values to color component values).
        // Default for most color spaces is [0 1 0 1 ...] (identity).
        // For Indexed color spaces, default is [0 2^bpc-1] and values are indices.
        // CMYK images may use [1 0 1 0 1 0 1 0] to invert values.
        let sample_data = if !is_image_mask {
            if let Some(decode) = dict.get_array(b"Decode") {
                let n_comps = color_space.num_components() as usize;
                let decode_vals: Vec<f64> = decode.iter().filter_map(|o| o.as_f64()).collect();
                if decode_vals.len() >= n_comps * 2 {
                    let effective_bpc = if is_jpx || is_dct { 8 } else { bpc };
                    let max_sample = ((1u32 << effective_bpc) - 1) as f64;
                    // Check if it's the default Decode for this color space.
                    // Indexed: default is [0 max_sample]; others: [0 1 0 1 ...].
                    let is_default = if is_indexed {
                        decode_vals.len() == 2
                            && (decode_vals[0]).abs() < 1e-6
                            && (decode_vals[1] - max_sample).abs() < 1e-6
                    } else {
                        decode_vals.chunks(2).all(|pair| {
                            pair.len() == 2
                                && (pair[0] - 0.0).abs() < 1e-6
                                && (pair[1] - 1.0).abs() < 1e-6
                        })
                    };
                    if !is_default {
                        // After expand_bits_to_bytes: indexed data keeps raw values
                        // (0 to 2^bpc-1), non-indexed data is scaled to 0-255.
                        let max_val = if is_indexed {
                            ((1u32 << effective_bpc) - 1) as f64
                        } else {
                            255.0f64
                        };
                        let mut result = Vec::with_capacity(sample_data.len());
                        if is_indexed {
                            // Indexed: Decode maps sample values to index values (integer range)
                            let d_min = decode_vals[0];
                            let d_max = decode_vals[1];
                            for &sample in sample_data.iter() {
                                let val = d_min + (sample as f64 / max_val) * (d_max - d_min);
                                result.push(val.round().clamp(0.0, 255.0) as u8);
                            }
                        } else {
                            // Non-indexed: Decode maps to normalized [0,1] component values
                            for (i, &sample) in sample_data.iter().enumerate() {
                                let comp = i % n_comps;
                                let d_min = decode_vals[comp * 2];
                                let d_max = decode_vals[comp * 2 + 1];
                                let val = d_min + (sample as f64 / max_val) * (d_max - d_min);
                                result.push((val.clamp(0.0, 1.0) * 255.0 + 0.5) as u8);
                            }
                        }
                        result
                    } else {
                        sample_data
                    }
                } else {
                    sample_data
                }
            } else {
                sample_data
            }
        } else {
            sample_data
        };

        // In CMYK page groups, route DeviceGray-derived images (DeviceGray
        // itself, Separation with gray alt, DeviceN with gray alt) through
        // the K plate so they composite equivalently to DeviceCMYK 0/0/0/(1−g).
        // Required by GWG 17.3 (JBIG2 compression) and GWG 23.0's "4 different
        // Grays" test.
        let (sample_data, color_space, resolved_cs) = if !is_image_mask {
            let was_device_gray = matches!(color_space, ImageColorSpace::DeviceGray);
            let (new_cs, new_data) =
                self.cmyk_group_promote_image(color_space, sample_data, width, height);
            let new_resolved = if was_device_gray && matches!(new_cs, ImageColorSpace::DeviceCMYK) {
                Some(ResolvedColorSpace::DeviceCMYK)
            } else {
                resolved_cs
            };
            (new_data, new_cs, new_resolved)
        } else {
            (sample_data, color_space, resolved_cs)
        };

        // Register the ICC profile with the cache so the rasterizer can find
        // it by hash.  Conversion itself is deferred to samples_to_rgba() so
        // only pixels that actually land on screen pay the color-transform cost.
        if !is_image_mask {
            if let Some(ref rcs) = resolved_cs {
                register_icc_profile(rcs, &mut self.icc_cache);
            }
        }

        // Handle SMask (soft mask / alpha channel).
        // Emit the image and its SMask as a SoftMasked display element so the
        // renderer scales them independently, preserving visible edges at hard
        // alpha boundaries (e.g. text outlines on transparent backgrounds).
        // When the mask is larger than the image (e.g., 1-bit text mask on a 2×2
        // color image), upscale the image to the mask dimensions to preserve detail.
        let smask_result = if !is_image_mask {
            let dict_smask = self.resolve_smask(dict, width, height)?;
            // Use SMaskInData alpha when no explicit /SMask entry exists
            if dict_smask.is_none() {
                if let Some(alpha) = smask_in_data_alpha {
                    Some((alpha, width, height, None))
                } else {
                    None
                }
            } else {
                dict_smask
            }
        } else {
            None
        };

        // Handle explicit stencil mask (/Mask pointing to 1-bit ImageMask stream).
        // When the mask is larger than the image (MRC scanned PDFs), upscale the
        // image to the mask dimensions so the high-res edge detail is preserved.
        let (sample_data, color_space, width, height) =
            if let Some((mask_alpha, mw, mh)) = explicit_mask_data {
                // Expand Indexed data to the base color space before upscaling,
                // so bilinear interpolation blends actual colors, not indices.
                let (up_data, up_cs) = if let ImageColorSpace::Indexed {
                    base,
                    hival,
                    lookup,
                } = &color_space
                {
                    let n_base = base.num_components() as usize;
                    let n_pixels = (width * height) as usize;
                    // `n_pixels` can be up to MAX_IMAGE_PIXELS, so multiplying
                    // by the component count leaves the u32 range and, on a
                    // 32-bit `usize` target, the usize range too.
                    let mut expanded = vec![0u8; n_pixels.saturating_mul(n_base)];
                    for i in 0..n_pixels {
                        let idx = sample_data.get(i).copied().unwrap_or(0) as usize;
                        let idx = idx.min(*hival as usize);
                        let offset = idx * n_base;
                        for c in 0..n_base {
                            expanded[i * n_base + c] = lookup.get(offset + c).copied().unwrap_or(0);
                        }
                    }
                    (expanded, *base.clone())
                } else {
                    (sample_data, color_space)
                };
                let (img_data, img_w, img_h) = if mw > width || mh > height {
                    // Upscale image to mask dimensions using bilinear interpolation
                    let upscaled = bilinear_upsample_image(&up_data, width, height, mw, mh, &up_cs);
                    (upscaled, mw, mh)
                } else {
                    (up_data, width, height)
                };
                let rgba = merge_rgb_with_smask(
                    &img_data,
                    &mask_alpha,
                    &up_cs,
                    img_w,
                    img_h,
                    Some(&self.icc_cache),
                );
                (rgba, ImageColorSpace::PreconvertedRGBA, img_w, img_h)
            } else {
                (sample_data, color_space, width, height)
            };

        // Apply transfer functions to image pixel data (colorizes grayscale charts etc.)
        let sample_data = if !is_image_mask && self.gstate.transfer.has_functions() {
            let n_comps = color_space.num_components() as usize;
            if n_comps >= 3 {
                let mut data = sample_data;
                apply_transfer_to_image(&mut data, &self.gstate.transfer, n_comps);
                data
            } else {
                sample_data
            }
        } else {
            sample_data
        };

        // Recompute image_matrix if dimensions changed (e.g. upscaled to match mask)
        let image_matrix =
            Matrix::new(width as f64, 0.0, 0.0, -(height as f64), 0.0, height as f64);

        // For K-only Indexed/DeviceCMYK palettes (grayscale images encoded as
        // CMYK), narrow painted_channels to CMYK_K so the overprint renderer
        // only paints the K channel.  This preserves spot-color contributions
        // on C/M/Y underneath — required by GWG 3.1 (Gray Image Overprint).
        // Non-K palettes keep CMYK_ALL so all channels are painted, matching
        // the PDF spec rule that OPM 1 per-channel zeroing does not apply to
        // Indexed color spaces (required by GWG 1.0 h/i).
        let painted_channels_override = if let ImageColorSpace::Indexed {
            base,
            hival,
            lookup,
        } = &color_space
        {
            if matches!(
                base.as_ref(),
                ImageColorSpace::DeviceCMYK | ImageColorSpace::ICCBased { n: 4, .. }
            ) {
                let n_entries = (*hival as usize + 1).min(lookup.len() / 4);
                let is_k_only = n_entries > 0
                    && (0..n_entries).all(|i| {
                        let off = i * 4;
                        lookup.get(off).copied().unwrap_or(0) == 0
                            && lookup.get(off + 1).copied().unwrap_or(0) == 0
                            && lookup.get(off + 2).copied().unwrap_or(0) == 0
                    });
                if is_k_only {
                    stet_graphics::device::CMYK_K
                } else {
                    stet_graphics::device::CMYK_ALL
                }
            } else {
                resolved_cs
                    .as_ref()
                    .map(painted_channels_for_cs)
                    .unwrap_or(self.gstate.fill_painted_channels)
            }
        } else {
            resolved_cs
                .as_ref()
                .map(painted_channels_for_cs)
                .unwrap_or(self.gstate.fill_painted_channels)
        };

        let image_params = ImageParams {
            width,
            height,
            color_space,
            bits_per_component: display_bpc as u8,
            ctm: self.gstate.ctm,
            image_matrix,
            interpolate,
            mask_color,
            alpha: self.gstate.fill_alpha,
            blend_mode: self.gstate.blend_mode,
            overprint: self.gstate.overprint,
            overprint_mode: self.gstate.overprint_mode,
            opm_paired: self.gstate.opm_paired,
            painted_channels: painted_channels_override,
            alpha_is_shape: self.gstate.alpha_is_shape,
            rendering_intent: image_intent,
        };

        // When an SMask is present, emit as SoftMasked so the renderer scales
        // image and mask independently, preserving edge detail at hard alpha
        // boundaries that premultiplied-alpha averaging would make invisible.
        if let Some((smask_data, mw, mh, matte)) = smask_result {
            // Upscale image to mask dimensions if the mask is larger — this
            // preserves sharp mask edges (e.g. MRC text masks on low-res images).
            // Cap the target pixel count to avoid allocating enormous buffers
            // when the mask is vastly larger than the image (e.g. 34862×4332
            // mask on a 2×2 image in issue16263.pdf). The limit is generous
            // enough for high-DPI and zoomed rendering but prevents pathological
            // cases from consuming gigabytes of memory.
            const MAX_PIXELS: u64 = 16_000_000; // ~4096×4096
            let mut target_w = mw.max(width);
            let mut target_h = mh.max(height);
            if (target_w as u64) * (target_h as u64) > MAX_PIXELS {
                let scale = (MAX_PIXELS as f64 / (target_w as f64 * target_h as f64)).sqrt();
                target_w = (target_w as f64 * scale).ceil() as u32;
                target_h = (target_h as f64 * scale).ceil() as u32;
            }
            let (sample_data, width, height) = if target_w > width || target_h > height {
                let upscaled = bilinear_upsample_image(
                    &sample_data,
                    width,
                    height,
                    target_w,
                    target_h,
                    &image_params.color_space,
                );
                (upscaled, target_w, target_h)
            } else {
                (sample_data, width, height)
            };

            // Resample SMask to image dimensions if they differ
            let smask_data = if mw != width || mh != height {
                let mut resampled = vec![0u8; (width * height) as usize];
                for y in 0..height {
                    let sy = (y as u64 * mh as u64 / height as u64) as u32;
                    for x in 0..width {
                        let sx = (x as u64 * mw as u64 / width as u64) as u32;
                        resampled[(y * width + x) as usize] = smask_data
                            .get((sy * mw + sx) as usize)
                            .copied()
                            .unwrap_or(0);
                    }
                }
                resampled
            } else {
                smask_data
            };

            // Un-premultiply image colors when Matte is specified (PDF spec 11.6.5.3).
            // The image data was pre-composited against the Matte color; reverse this
            // to recover the original colors before alpha compositing.
            let sample_data = if let Some(ref mc) = matte {
                let n_comps = image_params.color_space.num_components() as usize;
                if mc.len() >= n_comps && n_comps >= 3 {
                    let mut out = sample_data;
                    let pixels = (width * height) as usize;
                    for i in 0..pixels {
                        let a = smask_data[i] as f64 / 255.0;
                        if a > 0.0 && a < 1.0 {
                            for c in 0..n_comps.min(3) {
                                let m = (mc[c] * 255.0).clamp(0.0, 255.0);
                                let premul = out[i * n_comps + c] as f64;
                                let orig = m + (premul - m) / a;
                                out[i * n_comps + c] = orig.round().clamp(0.0, 255.0) as u8;
                            }
                        }
                    }
                    out
                } else {
                    sample_data
                }
            } else {
                sample_data
            };

            // Cache the fully-processed image data for reuse (Arc for cheap cloning).
            let sample_arc = Arc::new(sample_data);
            let smask_arc = Arc::new(smask_data);
            if let PdfObj::Ref(obj_num, _) = obj {
                self.image_cache.insert(
                    *obj_num,
                    CachedImage {
                        sample_data: Arc::clone(&sample_arc),
                        width,
                        height,
                        color_space: image_params.color_space.clone(),
                        bits_per_component: image_params.bits_per_component,
                        interpolate,
                        mask_color: image_params.mask_color.clone(),
                        painted_channels: image_params.painted_channels,
                        smask: Some((Arc::clone(&smask_arc), width, height, matte.clone())),
                        rendering_intent: image_params.rendering_intent,
                    },
                );
            }

            let image_matrix =
                Matrix::new(width as f64, 0.0, 0.0, -(height as f64), 0.0, height as f64);

            let mut mask_dl = DisplayList::new();
            mask_dl.push(DisplayElement::Image {
                sample_data: smask_arc,
                params: ImageParams {
                    width,
                    height,
                    color_space: ImageColorSpace::DeviceGray,
                    bits_per_component: 8,
                    ctm: self.gstate.ctm,
                    image_matrix,
                    interpolate,
                    mask_color: None,
                    alpha: 1.0,
                    blend_mode: 0,
                    overprint: false,
                    overprint_mode: 0,
                    opm_paired: false,
                    painted_channels: 0,
                    alpha_is_shape: false,
                    rendering_intent: 0,
                },
            });

            let mut content_dl = DisplayList::new();
            content_dl.push(DisplayElement::Image {
                sample_data: sample_arc,
                params: ImageParams {
                    width,
                    height,
                    image_matrix,
                    ..image_params
                },
            });

            let corners = [
                self.gstate.ctm.transform_point(0.0, 0.0),
                self.gstate.ctm.transform_point(1.0, 0.0),
                self.gstate.ctm.transform_point(0.0, 1.0),
                self.gstate.ctm.transform_point(1.0, 1.0),
            ];
            let x_min = corners.iter().map(|c| c.0).fold(f64::INFINITY, f64::min);
            let y_min = corners.iter().map(|c| c.1).fold(f64::INFINITY, f64::min);
            let x_max = corners
                .iter()
                .map(|c| c.0)
                .fold(f64::NEG_INFINITY, f64::max);
            let y_max = corners
                .iter()
                .map(|c| c.1)
                .fold(f64::NEG_INFINITY, f64::max);

            let parent_clip_bbox = self.current_clip_bbox();
            self.display_list.push(DisplayElement::SoftMasked {
                mask: mask_dl,
                content: content_dl,
                params: SoftMaskParams {
                    subtype: SoftMaskSubtype::Luminosity,
                    bbox: [x_min, y_min, x_max, y_max],
                    backdrop_color: None,
                    transfer_invert: false,
                    has_nested_mask_scope: false,
                    parent_clip_bbox,
                },
                mask_cache: Arc::new(Mutex::new(None)),
            });
        } else {
            // Cache plain image for reuse (Arc for cheap cloning).
            let sample_arc = Arc::new(sample_data);
            if let PdfObj::Ref(obj_num, _) = obj {
                self.image_cache.insert(
                    *obj_num,
                    CachedImage {
                        sample_data: Arc::clone(&sample_arc),
                        width,
                        height,
                        color_space: image_params.color_space.clone(),
                        bits_per_component: image_params.bits_per_component,
                        interpolate,
                        mask_color: image_params.mask_color.clone(),
                        painted_channels: image_params.painted_channels,
                        smask: None,
                        rendering_intent: image_params.rendering_intent,
                    },
                );
            }

            self.display_list.push(DisplayElement::Image {
                sample_data: sample_arc,
                params: image_params,
            });
        }
        Ok(())
    }

    /// Build a CachedImage, pre-downscaling if the image is much larger than
    /// its device-pixel target size (detected from the current CTM).
    #[allow(clippy::too_many_arguments)]
    /// Emit a display element from a cached image, applying current graphics state.
    /// The cache already contains pre-downscaled data when applicable.
    fn emit_cached_image(&mut self, cached: CachedImage) -> Result<(), PdfError> {
        let (sample_data, smask, width, height) = (
            cached.sample_data,
            cached.smask,
            cached.width,
            cached.height,
        );

        let image_matrix =
            Matrix::new(width as f64, 0.0, 0.0, -(height as f64), 0.0, height as f64);
        let image_params = ImageParams {
            width,
            height,
            color_space: cached.color_space,
            bits_per_component: cached.bits_per_component,
            ctm: self.gstate.ctm,
            image_matrix,
            interpolate: cached.interpolate,
            mask_color: cached.mask_color,
            alpha: self.gstate.fill_alpha,
            blend_mode: self.gstate.blend_mode,
            overprint: self.gstate.overprint,
            overprint_mode: self.gstate.overprint_mode,
            opm_paired: self.gstate.opm_paired,
            painted_channels: cached.painted_channels,
            alpha_is_shape: self.gstate.alpha_is_shape,
            rendering_intent: cached.rendering_intent,
        };

        if let Some((smask_data, sw, sh, _matte)) = smask {
            let mut mask_dl = DisplayList::new();
            mask_dl.push(DisplayElement::Image {
                sample_data: smask_data,
                params: ImageParams {
                    width: sw,
                    height: sh,
                    color_space: ImageColorSpace::DeviceGray,
                    bits_per_component: 8,
                    ctm: self.gstate.ctm,
                    image_matrix,
                    interpolate: cached.interpolate,
                    mask_color: None,
                    alpha: 1.0,
                    blend_mode: 0,
                    overprint: false,
                    overprint_mode: 0,
                    opm_paired: false,
                    painted_channels: 0,
                    alpha_is_shape: false,
                    rendering_intent: 0,
                },
            });

            let mut content_dl = DisplayList::new();
            content_dl.push(DisplayElement::Image {
                sample_data,
                params: ImageParams {
                    width,
                    height,
                    image_matrix,
                    ..image_params
                },
            });

            let corners = [
                self.gstate.ctm.transform_point(0.0, 0.0),
                self.gstate.ctm.transform_point(1.0, 0.0),
                self.gstate.ctm.transform_point(0.0, 1.0),
                self.gstate.ctm.transform_point(1.0, 1.0),
            ];
            let x_min = corners.iter().map(|c| c.0).fold(f64::INFINITY, f64::min);
            let y_min = corners.iter().map(|c| c.1).fold(f64::INFINITY, f64::min);
            let x_max = corners
                .iter()
                .map(|c| c.0)
                .fold(f64::NEG_INFINITY, f64::max);
            let y_max = corners
                .iter()
                .map(|c| c.1)
                .fold(f64::NEG_INFINITY, f64::max);

            let parent_clip_bbox = self.current_clip_bbox();
            self.display_list.push(DisplayElement::SoftMasked {
                mask: mask_dl,
                content: content_dl,
                params: SoftMaskParams {
                    subtype: SoftMaskSubtype::Luminosity,
                    bbox: [x_min, y_min, x_max, y_max],
                    backdrop_color: None,
                    transfer_invert: false,
                    has_nested_mask_scope: false,
                    parent_clip_bbox,
                },
                mask_cache: Arc::new(Mutex::new(None)),
            });
        } else {
            self.display_list.push(DisplayElement::Image {
                sample_data,
                params: image_params,
            });
        }
        Ok(())
    }

    /// Resolve an SMask (soft mask) from an image dict.
    /// Returns `(alpha_data, mask_width, mask_height, matte)` at the mask's native
    /// resolution so the caller can upscale the image if the mask is larger.
    /// The optional Matte array contains the pre-multiplication color (PDF spec 11.6.5.3).
    fn resolve_smask(
        &self,
        dict: &PdfDict,
        image_w: u32,
        image_h: u32,
    ) -> Result<Option<(Vec<u8>, u32, u32, Option<Vec<f64>>)>, PdfError> {
        let smask_ref = match dict.get(b"SMask") {
            Some(obj) => obj.clone(),
            None => return Ok(None),
        };
        let smask_obj = self.resolver.deref(&smask_ref)?;
        let smask_dict = match smask_obj.as_dict() {
            Some(d) => d,
            None => return Ok(None),
        };
        // Fall back to parent image dimensions when the SMask dict is
        // malformed (e.g. /Height missing — issue19611.pdf).
        let sw =
            validate_image_dimension(smask_dict.get_int(b"Width").or(Some(i64::from(image_w))));
        let sh =
            validate_image_dimension(smask_dict.get_int(b"Height").or(Some(i64::from(image_h))));
        let (Some(sw), Some(sh)) = (sw, sh) else {
            return Ok(None);
        };
        if validate_image_size(sw, sh).is_none() {
            return Ok(None);
        }
        let Some(bpc) = validate_bits_per_component(smask_dict.get_int(b"BitsPerComponent")) else {
            return Ok(None);
        };
        let data = self.resolver.stream_data_from_obj(&smask_ref)?;

        // Expand non-8-bit BPC: sub-byte (1/2/4) are packed bits;
        // 16-bit needs downsampling to 8-bit for alpha channel use.
        let mut data = if bpc == 8 {
            data
        } else if bpc == 16 {
            // Take high byte of each 16-bit sample
            data.chunks(2).map(|c| c[0]).collect()
        } else if bpc < 8 {
            expand_bits_to_bytes(&data, bpc, sw, sh, 1, false)
        } else {
            data
        };

        // Apply /Decode array if present (e.g. [1 0] inverts the mask)
        if let Some(decode) = smask_dict.get_array(b"Decode")
            && decode.len() >= 2
        {
            let d0 = decode[0].as_f64().unwrap_or(0.0);
            let d1 = decode[1].as_f64().unwrap_or(1.0);
            if (d0 - 1.0).abs() < 1e-6 && d1.abs() < 1e-6 {
                // /Decode [1 0] — invert all bytes
                for b in data.iter_mut() {
                    *b = 255 - *b;
                }
            } else if (d0).abs() > 1e-6 || (d1 - 1.0).abs() > 1e-6 {
                // General linear mapping: output = d0 + (d1-d0) * input/255
                for b in data.iter_mut() {
                    let v = d0 + (d1 - d0) * (*b as f64 / 255.0);
                    *b = (v * 255.0).round().clamp(0.0, 255.0) as u8;
                }
            }
        }

        // Parse /Matte array (pre-multiplication color, PDF spec 11.6.5.3)
        let matte = smask_dict
            .get_array(b"Matte")
            .map(|arr| arr.iter().filter_map(|o| o.as_f64()).collect::<Vec<_>>());

        Ok(Some((data, sw, sh, matte)))
    }

    /// Resolve an explicit stencil mask (/Mask stream ref) from an image dict.
    /// Returns (alpha_data, mask_width, mask_height).
    /// When the mask is larger than the image, returns the mask at its native
    /// resolution so the caller can upscale the image to match (preserving the
    /// high-resolution edge detail from MRC scanned PDFs).
    fn resolve_explicit_mask(
        &self,
        dict: &PdfDict,
        image_w: u32,
        image_h: u32,
    ) -> Result<Option<(Vec<u8>, u32, u32)>, PdfError> {
        let mask_ref = match dict.get(b"Mask") {
            Some(obj) => obj.clone(),
            None => return Ok(None),
        };
        let mask_obj = self.resolver.deref(&mask_ref)?;
        let mask_dict = match mask_obj.as_dict() {
            Some(d) => d,
            None => return Ok(None),
        };
        let (Some(mw), Some(mh)) = (
            validate_image_dimension(mask_dict.get_int(b"Width")),
            validate_image_dimension(mask_dict.get_int(b"Height")),
        ) else {
            return Ok(None);
        };
        if validate_image_size(mw, mh).is_none() {
            return Ok(None);
        }
        let mask_data = self.resolver.stream_data_from_obj(&mask_ref)?;

        // Determine mask polarity from /Decode (default [0 1]: 0=painted=opaque)
        let invert = if let Some(decode) = mask_dict.get_array(b"Decode") {
            if decode.len() >= 2 {
                let d0 = decode[0].as_f64().unwrap_or(0.0);
                // [1 0] means 1=painted (invert normal polarity)
                d0 > 0.5
            } else {
                false
            }
        } else {
            false
        };

        // Expand 1-bit mask data to 8-bit alpha
        let row_bytes = mw.div_ceil(8);
        let mut alpha = vec![0u8; (mw * mh) as usize];
        for y in 0..mh {
            for x in 0..mw {
                let byte_idx = (y * row_bytes + x / 8) as usize;
                let bit_idx = 7 - (x % 8);
                let bit = if byte_idx < mask_data.len() {
                    (mask_data[byte_idx] >> bit_idx) & 1
                } else {
                    0
                };
                // In PDF, /ImageMask true with default Decode [0 1]:
                // bit=0 → painted (opaque), bit=1 → not painted (transparent)
                let opaque = if invert { bit == 1 } else { bit == 0 };
                alpha[(y * mw + x) as usize] = if opaque { 255 } else { 0 };
            }
        }

        // When mask is larger than the image, return it at native resolution.
        // The caller will upscale the image to match, preserving the mask's
        // high-resolution edge detail (critical for MRC scanned PDFs).
        // When mask is smaller, area-average downsample to image dimensions.
        if mw == image_w && mh == image_h {
            Ok(Some((alpha, mw, mh)))
        } else if mw >= image_w && mh >= image_h {
            // Mask is larger — return at native resolution
            Ok(Some((alpha, mw, mh)))
        } else {
            // Mask is smaller — area-average resample to image dimensions
            let mut resampled = vec![0u8; (image_w * image_h) as usize];
            let ratio_x = mw as f32 / image_w as f32;
            let ratio_y = mh as f32 / image_h as f32;
            for y in 0..image_h {
                let top_f = y as f32 * ratio_y;
                let bottom_f = (y + 1) as f32 * ratio_y;
                let top = (top_f as u32).min(mh - 1);
                let bottom = (bottom_f.ceil() as u32).min(mh);
                for x in 0..image_w {
                    let left_f = x as f32 * ratio_x;
                    let right_f = (x + 1) as f32 * ratio_x;
                    let left = (left_f as u32).min(mw - 1);
                    let right = (right_f.ceil() as u32).min(mw);
                    let mut sum = 0.0f32;
                    let mut weight = 0.0f32;
                    for sy in top..bottom {
                        let py_top = sy as f32;
                        let py_bot = (sy + 1) as f32;
                        let wy = py_bot.min(bottom_f) - py_top.max(top_f);
                        for sx in left..right {
                            let px_left = sx as f32;
                            let px_right = (sx + 1) as f32;
                            let wx = px_right.min(right_f) - px_left.max(left_f);
                            let w = wx * wy;
                            sum += alpha[(sy * mw + sx) as usize] as f32 * w;
                            weight += w;
                        }
                    }
                    resampled[(y * image_w + x) as usize] = if weight > 0.0 {
                        (sum / weight + 0.5).min(255.0) as u8
                    } else {
                        0
                    };
                }
            }
            Ok(Some((resampled, image_w, image_h)))
        }
    }

    /// Check if a JPXDecode image stream contains RGB+alpha (not CMYK).
    /// Peeks at the JP2 header metadata without re-decoding.
    fn is_jpx_rgba(&self, obj: &PdfObj) -> bool {
        #[cfg(feature = "jpx")]
        {
            if let Ok((raw, filters)) = self.resolver.raw_stream_and_filters(obj) {
                if filters
                    .iter()
                    .any(|f| matches!(f, crate::filters::Filter::JPXDecode))
                {
                    if let Some((color_channels, has_alpha)) = crate::filters::jpx_color_info(&raw)
                    {
                        return color_channels == 3 && has_alpha;
                    }
                }
            }
        }
        false
    }

    /// Handle a Form XObject (recursive content stream).
    fn handle_form_xobject(&mut self, obj: &PdfObj, dict: &PdfDict) -> Result<(), PdfError> {
        if self.depth >= MAX_CONTENT_NESTING {
            return Err(PdfError::Other("Form XObject nesting too deep".into()));
        }

        // Get form's own resources (or inherit from page)
        let form_resources = if let Some(res_obj) = dict.get(b"Resources") {
            match self.resolver.deref(res_obj)? {
                PdfObj::Dict(d) => d,
                _ => self.resources.clone(),
            }
        } else {
            self.resources.clone()
        };

        // Form matrix
        let form_matrix = if let Some(vals) = deref_num_array(self.resolver, dict, b"Matrix") {
            if vals.len() == 6 {
                Matrix::new(vals[0], vals[1], vals[2], vals[3], vals[4], vals[5])
            } else {
                Matrix::identity()
            }
        } else {
            Matrix::identity()
        };

        // BBox clipping
        let bbox = if let Some(vals) = deref_num_array(self.resolver, dict, b"BBox") {
            if vals.len() == 4 {
                Some((vals[0], vals[1], vals[2], vals[3]))
            } else {
                None
            }
        } else {
            None
        };

        // Check for transparency group
        let is_transparency_group = self.is_transparency_group(dict);

        // Decompress form content stream
        let form_data = self.resolver.stream_data_from_obj(obj)?;

        // Save state (including font cache — form XObjects may have different
        // font resources with different encodings for the same resource name)
        self.gstate_stack.push(self.gstate.clone());
        let saved_stack_depth = self.gstate_stack.len();
        let saved_resources = std::mem::replace(&mut self.resources, form_resources);
        let saved_font_cache = std::mem::take(&mut self.font_cache);
        let saved_current_font = self.current_font.take();
        let saved_cs_index = self.cs_index.take(); // invalidate — form has its own resources
        let saved_content_stream_ctm = self.content_stream_ctm;
        let saved_mc_stack = std::mem::take(&mut self.mc_stack);
        // Save and clear current path — forms start with an empty path per PDF spec.
        // Without this, an unconsumed path from the parent content stream leaks into
        // the form and gets painted by the first paint operator inside the form.
        let saved_path = std::mem::take(&mut self.current_path);
        let saved_point = self.current_point.take();
        let saved_subpath = self.subpath_start.take();

        // Apply form matrix
        self.gstate.ctm = self.gstate.ctm.concat(&form_matrix);

        // Update content stream CTM — patterns inside this form map to
        // the form's initial coordinate system (CTM after form matrix).
        self.content_stream_ctm = self.gstate.ctm;

        if is_transparency_group {
            // Capture compositing parameters from the current state BEFORE
            // resetting alpha for the group's internal rendering.
            let group_blend_mode = self.gstate.blend_mode;
            let group_alpha = self.gstate.fill_alpha;

            // Reset alpha and soft mask inside the group: elements render at
            // full opacity. The inherited alpha is applied when compositing
            // the group as a whole, avoiding double-application of alpha.
            // Clearing soft_mask prevents the parent's SMask from leaking
            // into q/Q flush detection inside the group — without this,
            // inner Q restores see the parent SMask in the saved state and
            // skip flushing inner SMask scopes.
            self.gstate.fill_alpha = 1.0;
            self.gstate.stroke_alpha = 1.0;
            self.gstate.soft_mask = None;

            // Render group contents into a separate sub-DisplayList
            let mut group_list = DisplayList::new();
            std::mem::swap(&mut self.display_list, &mut group_list);

            // Save and clear soft mask scope — it belongs to the parent display list
            let saved_scope = self.soft_mask_scope.take();

            // Compute device-space bbox now, before interpret_stream modifies
            // the CTM via `cm` operators inside the form content.
            let device_bbox = self.compute_device_bbox(bbox);

            // Clip to BBox inside the group's display list
            if let Some((x0, y0, x1, y1)) = bbox {
                self.push_bbox_clip(x0, y0, x1, y1);
            }

            // Interpret form content into group_list (now in self.display_list)
            self.depth += 1;
            self.interpret_stream(&form_data)?;
            self.depth -= 1;

            // Flush any soft mask scope opened inside the group
            self.flush_soft_mask();

            // Swap back — group_list now contains the group's elements
            std::mem::swap(&mut self.display_list, &mut group_list);

            // Restore parent's soft mask scope
            self.soft_mask_scope = saved_scope;

            // Extract isolated and knockout flags from Group dict
            let isolated = self.get_group_isolated(dict);
            let knockout = self.get_group_knockout(dict);
            let color_space = self.get_group_color_space(dict);

            // Push Group element to parent display list
            self.display_list.push(DisplayElement::Group {
                elements: group_list,
                params: GroupParams {
                    bbox: device_bbox,
                    isolated,
                    knockout,
                    blend_mode: group_blend_mode,
                    alpha: group_alpha,
                    color_space,
                },
            });
        } else {
            // Non-transparency-group Form XObject: render inline (existing behavior)
            if let Some((x0, y0, x1, y1)) = bbox {
                self.push_bbox_clip(x0, y0, x1, y1);
            }

            // Compute visible Y range in form coordinates for early culling.
            // If the form is much taller than the visible area, skip offscreen
            // BT/ET blocks during interpretation (avoids font resolution and
            // glyph measurement for content that will never be rendered).
            let saved_cull = self.form_cull_y.take();
            if let Some((_x0, y0, _x1, y1)) = bbox {
                let form_height = (y1 - y0).abs();
                // Only cull if form is significantly larger than the page
                if form_height > 5000.0 {
                    // Compute visible Y range by inverse-transforming the page
                    // clip through the CTM. CTM maps form coords to device space.
                    let ctm = &self.gstate.ctm;
                    // For a simple scale+translate CTM (common case), inverse Y is:
                    // form_y = (device_y - ty) / d
                    if ctm.b.abs() < 1e-6 && ctm.c.abs() < 1e-6 && ctm.d.abs() > 1e-6 {
                        // device Y range is [0, page_height_px]
                        let page_h = self.initial_ctm.ty.abs();
                        let fy0 = (0.0 - ctm.ty) / ctm.d;
                        let fy1 = (page_h - ctm.ty) / ctm.d;
                        let (lo, hi) = if fy0 < fy1 { (fy0, fy1) } else { (fy1, fy0) };
                        // Add margin for text that extends above/below baseline
                        self.form_cull_y = Some((lo - 100.0, hi + 100.0));
                    }
                }
            }

            self.depth += 1;
            self.interpret_stream(&form_data)?;
            self.depth -= 1;

            self.form_cull_y = saved_cull;
        }

        // Unwind any unbalanced q's the form content left on the stack.
        // Form content streams often have q without matching Q (the end of
        // the stream implicitly unwinds).  Without this, the extra stack
        // entries cause our own pop below to restore the wrong gstate,
        // leaking state (e.g. alpha from ExtGState) into the parent scope.
        while self.gstate_stack.len() > saved_stack_depth {
            self.gstate_stack.pop();
        }

        // Restore state — check if clip needs resetting
        self.resources = saved_resources;
        self.font_cache = saved_font_cache;
        self.current_font = saved_current_font;
        self.cs_index = saved_cs_index;
        self.content_stream_ctm = saved_content_stream_ctm;
        self.current_path = saved_path;
        self.current_point = saved_point;
        self.subpath_start = saved_subpath;
        self.mc_stack = saved_mc_stack;
        if let Some(saved) = self.gstate_stack.pop() {
            let old_clip_version = self.gstate.clip_path_version;
            self.gstate = saved;
            // For non-group forms, restore clip if it changed
            if !is_transparency_group && self.gstate.clip_path_version != old_clip_version {
                self.restore_clip_from_stack();
            }
        }

        Ok(())
    }

    /// Check if a Form XObject dict has a /Group dict with /S /Transparency.
    fn is_transparency_group(&self, dict: &PdfDict) -> bool {
        let Some(group_obj) = dict.get(b"Group") else {
            return false;
        };
        let group_dict = match self.resolver.deref(group_obj) {
            Ok(PdfObj::Dict(d)) => d,
            _ => return false,
        };
        group_dict.get_name(b"S") == Some(b"Transparency")
    }

    /// Extract the /I (isolated) flag from a Form XObject's /Group dict.
    fn get_group_isolated(&self, dict: &PdfDict) -> bool {
        let Some(group_obj) = dict.get(b"Group") else {
            return false;
        };
        let group_dict = match self.resolver.deref(group_obj) {
            Ok(PdfObj::Dict(d)) => d,
            _ => return false,
        };
        match group_dict.get(b"I") {
            Some(PdfObj::Bool(b)) => *b,
            _ => false,
        }
    }

    /// Extract the /K (knockout) flag from a Form XObject's /Group dict.
    fn get_group_knockout(&self, dict: &PdfDict) -> bool {
        let Some(group_obj) = dict.get(b"Group") else {
            return false;
        };
        let group_dict = match self.resolver.deref(group_obj) {
            Ok(PdfObj::Dict(d)) => d,
            _ => return false,
        };
        match group_dict.get(b"K") {
            Some(PdfObj::Bool(b)) => *b,
            _ => false,
        }
    }

    /// Extract the `/CS` color space from a Form XObject's `/Group` dict and
    /// classify it for rendering purposes. Returns `Inherited` when the entry
    /// is missing or refers to a color space we don't categorise here.
    fn get_group_color_space(
        &self,
        dict: &PdfDict,
    ) -> stet_graphics::display_list::GroupColorSpace {
        use stet_graphics::display_list::GroupColorSpace;
        let Some(group_obj) = dict.get(b"Group") else {
            return GroupColorSpace::Inherited;
        };
        let group_dict = match self.resolver.deref(group_obj) {
            Ok(PdfObj::Dict(d)) => d,
            _ => return GroupColorSpace::Inherited,
        };
        let Some(cs_obj) = group_dict.get(b"CS") else {
            return GroupColorSpace::Inherited;
        };
        let cs_obj = match self.resolver.deref(cs_obj) {
            Ok(o) => o,
            Err(_) => return GroupColorSpace::Inherited,
        };
        match cs_obj {
            PdfObj::Name(n) => match n.as_slice() {
                b"DeviceGray" | b"CalGray" | b"G" => GroupColorSpace::DeviceGray,
                b"DeviceRGB" | b"CalRGB" | b"RGB" => GroupColorSpace::DeviceRGB,
                b"DeviceCMYK" | b"CMYK" => GroupColorSpace::DeviceCMYK,
                _ => GroupColorSpace::Inherited,
            },
            PdfObj::Array(arr) => {
                // [/ICCBased <<stream>>] — classify by N component count.
                if let Some(PdfObj::Name(name)) = arr.first()
                    && name.as_slice() == b"ICCBased"
                    && let Some(stream_obj) = arr.get(1)
                {
                    let stream_obj = match self.resolver.deref(stream_obj) {
                        Ok(o) => o,
                        Err(_) => return GroupColorSpace::Inherited,
                    };
                    if let PdfObj::Stream {
                        dict: stream_dict, ..
                    } = stream_obj
                        && let Some(n_obj) = stream_dict.get(b"N")
                        && let Some(n_val) = n_obj.as_int()
                    {
                        return match n_val {
                            1 => GroupColorSpace::DeviceGray,
                            3 => GroupColorSpace::DeviceRGB,
                            4 => GroupColorSpace::DeviceCMYK,
                            _ => GroupColorSpace::Inherited,
                        };
                    }
                }
                GroupColorSpace::Inherited
            }
            _ => GroupColorSpace::Inherited,
        }
    }

    /// Push a BBox clip path to the current display list.
    fn push_bbox_clip(&mut self, x0: f64, y0: f64, x1: f64, y1: f64) {
        let p0 = self.gstate.ctm.transform_point(x0, y0);
        let p1 = self.gstate.ctm.transform_point(x1, y0);
        let p2 = self.gstate.ctm.transform_point(x1, y1);
        let p3 = self.gstate.ctm.transform_point(x0, y1);
        let mut clip_path = PsPath::new();
        clip_path.segments.push(PathSegment::MoveTo(p0.0, p0.1));
        clip_path.segments.push(PathSegment::LineTo(p1.0, p1.1));
        clip_path.segments.push(PathSegment::LineTo(p2.0, p2.1));
        clip_path.segments.push(PathSegment::LineTo(p3.0, p3.1));
        clip_path.segments.push(PathSegment::ClosePath);
        self.display_list.push(DisplayElement::Clip {
            path: clip_path.clone(),
            params: ClipParams {
                fill_rule: FillRule::NonZeroWinding,
                ctm: Matrix::identity(),
                stroke_params: None,
            },
        });
        self.gstate
            .clip_stack
            .push((clip_path.clone(), FillRule::NonZeroWinding));
        self.gstate.clip_path = Some(clip_path);
        self.gstate.clip_path_version += 1;
    }

    /// Compute device-space bounding box from form BBox + current CTM.
    /// Compute the device-space bounding box of the current gstate's
    /// clip path. Clip paths are stored in device coordinates, so this
    /// is just `path_bbox(clip_path)`. Returns `None` when no clip path
    /// is active.
    fn current_clip_bbox(&self) -> Option<[f64; 4]> {
        let path = self.gstate.clip_path.as_ref()?;
        let mut x_min = f64::INFINITY;
        let mut y_min = f64::INFINITY;
        let mut x_max = f64::NEG_INFINITY;
        let mut y_max = f64::NEG_INFINITY;
        for seg in &path.segments {
            let pts: &[(f64, f64)] = match seg {
                PathSegment::MoveTo(x, y) | PathSegment::LineTo(x, y) => &[(*x, *y)],
                PathSegment::CurveTo {
                    x1,
                    y1,
                    x2,
                    y2,
                    x3,
                    y3,
                } => &[(*x1, *y1), (*x2, *y2), (*x3, *y3)][..],
                PathSegment::ClosePath => &[],
            };
            for (x, y) in pts {
                x_min = x_min.min(*x);
                y_min = y_min.min(*y);
                x_max = x_max.max(*x);
                y_max = y_max.max(*y);
            }
        }
        if x_min.is_finite() && x_min < x_max && y_min < y_max {
            Some([x_min, y_min, x_max, y_max])
        } else {
            None
        }
    }

    fn compute_device_bbox(&self, bbox: Option<(f64, f64, f64, f64)>) -> [f64; 4] {
        let Some((x0, y0, x1, y1)) = bbox else {
            // No BBox — use large sentinel
            return [0.0, 0.0, 1e9, 1e9];
        };
        let corners = [
            self.gstate.ctm.transform_point(x0, y0),
            self.gstate.ctm.transform_point(x1, y0),
            self.gstate.ctm.transform_point(x0, y1),
            self.gstate.ctm.transform_point(x1, y1),
        ];
        let mut min_x = f64::INFINITY;
        let mut min_y = f64::INFINITY;
        let mut max_x = f64::NEG_INFINITY;
        let mut max_y = f64::NEG_INFINITY;
        for (cx, cy) in &corners {
            min_x = min_x.min(*cx);
            min_y = min_y.min(*cy);
            max_x = max_x.max(*cx);
            max_y = max_y.max(*cy);
        }
        [min_x, min_y, max_x, max_y]
    }

    /// Handle inline image (BI ... ID ... EI).
    fn handle_inline_image(&mut self, lexer: &mut Lexer) -> Result<(), PdfError> {
        // Parse image dict (abbreviated keys)
        let mut dict = PdfDict::new();
        loop {
            let tok = lexer.next_token()?;
            match tok {
                Token::Keyword(ref kw) if kw == b"ID" => break,
                Token::Eof => return Ok(()),
                Token::Name(key) => {
                    let expanded_key = expand_inline_key(&key);
                    let val_tok = lexer.next_token()?;
                    let val = match val_tok {
                        Token::Int(n) => PdfObj::Int(n),
                        Token::Real(f) => PdfObj::Real(f),
                        Token::Name(n) => PdfObj::Name(expand_inline_value(&n)),
                        Token::Bool(b) => PdfObj::Bool(b),
                        Token::LitString(s) | Token::HexString(s) => PdfObj::Str(s),
                        Token::ArrayBegin => {
                            let arr = Self::parse_inline_array(lexer)?;
                            PdfObj::Array(arr)
                        }
                        Token::DictBegin => crate::lexer::parse_dict_body(lexer)
                            .map(PdfObj::Dict)
                            .unwrap_or(PdfObj::Null),
                        _ => PdfObj::Null,
                    };
                    // First occurrence wins: when both abbreviated (/W) and full
                    // (/Width) forms are present, the first one takes precedence.
                    if dict.get(&expanded_key).is_none() {
                        dict.insert(expanded_key, val);
                    }
                }
                _ => {}
            }
        }

        // Skip single whitespace byte after ID.
        // Treat \r\n as a single EOL delimiter (many PDF generators emit
        // ID\r\n before the image data).
        let data = lexer.data();
        let mut pos = lexer.pos();
        if pos < data.len() {
            if data[pos] == b'\r' {
                pos += 1;
                if pos < data.len() && data[pos] == b'\n' {
                    pos += 1;
                }
            } else if data[pos] == b' ' || data[pos] == b'\n' {
                pos += 1;
            }
        }

        // Read image data until EI
        let width = validate_image_dimension(dict.get_int(b"Width")).unwrap_or(0);
        let height = validate_image_dimension(dict.get_int(b"Height")).unwrap_or(0);
        // A rejected dimension lands as 0 here, which the existing
        // zero-dimension paths below already treat as "no image".
        let (width, height) = match validate_image_size(width, height) {
            Some(_) => (width, height),
            None => (0, 0),
        };
        let is_image_mask = matches!(dict.get(b"ImageMask"), Some(PdfObj::Bool(true)));
        let bpc = if is_image_mask {
            1
        } else {
            validate_bits_per_component(dict.get_int(b"BitsPerComponent")).unwrap_or(8)
        };

        let has_filter = dict.get(b"Filter").is_some() || dict.get(b"F").is_some();

        // Check if the outermost filter is ASCII85 — its data ends with `~>`,
        // which is a reliable boundary marker (unlike scanning for `\nEI` which
        // can match false positives inside ASCII85-encoded binary data).
        let outermost_is_ascii85 = dict
            .get(b"Filter")
            .or_else(|| dict.get(b"F"))
            .map(|f| match f {
                PdfObj::Name(n) => n == b"ASCII85Decode" || n == b"A85",
                PdfObj::Array(arr) => arr
                    .first()
                    .and_then(|o| o.as_name())
                    .map(|n| n == b"ASCII85Decode" || n == b"A85")
                    .unwrap_or(false),
                _ => false,
            })
            .unwrap_or(false);

        let resolved_cs = if is_image_mask {
            None
        } else if let Some(cs_obj) = dict.get(b"ColorSpace") {
            // For inline images, the CS value may be a resource name (e.g. /R35)
            // that needs lookup in the page's ColorSpace resources.
            let cs_resolved = if let PdfObj::Name(name) = cs_obj {
                // Try the cached index first, then fall back to resolving the
                // ColorSpace resource sub-dict directly.
                let from_cache = self
                    .cs_index
                    .as_ref()
                    .and_then(|idx| idx.get(name.as_slice()).cloned());
                let res_obj = from_cache.or_else(|| {
                    self.resolve_resource_subdict(b"ColorSpace")
                        .and_then(|d| d.get(name).cloned())
                });
                if let Some(ref obj) = res_obj {
                    resolve_color_space_obj(obj, self.resolver)
                } else {
                    resolve_color_space_obj(cs_obj, self.resolver)
                }
            } else {
                resolve_color_space_obj(cs_obj, self.resolver)
            };
            match cs_resolved {
                Ok(resolved) => Some(resolved),
                Err(_) => Some(ResolvedColorSpace::DeviceGray),
            }
        } else {
            Some(ResolvedColorSpace::DeviceGray)
        };
        let n_components = resolved_cs
            .as_ref()
            .map(|cs| cs.num_components() as u32)
            .unwrap_or(1);

        // Calculate expected uncompressed data length (for EI boundary search)
        let row_bits = width * n_components.max(1) * bpc;
        let row_bytes = row_bits.div_ceil(8);
        let expected_len = (row_bytes * height) as usize;

        // Find EI boundary — look for whitespace + "EI" + delimiter/EOF.
        // For compressed data (CCITT, Flate, etc.), the compressed data is smaller
        // than the uncompressed size, so we must search from the start of data.
        let start = pos;
        let search_from = if has_filter {
            start
        } else {
            start + expected_len
        };
        // First try: check for "EI" at/near the expected position (some PDFs omit
        // the whitespace before EI that the spec requires).
        let mut end = search_from;
        let mut found_no_ws = false;
        if !has_filter {
            // Check at expected_len-2, expected_len-1, and expected_len for "EI" without leading ws
            for offset in [
                expected_len.saturating_sub(2),
                expected_len.saturating_sub(1),
                expected_len,
            ] {
                let p = start + offset;
                if p + 1 < data.len()
                    && data[p] == b'E'
                    && data[p + 1] == b'I'
                    && (p + 2 >= data.len() || is_delimiter_or_ws(data[p + 2]))
                {
                    end = p;
                    found_no_ws = true;
                    break;
                }
            }
        }
        if !found_no_ws {
            if outermost_is_ascii85 {
                // ASCII85 data ends with `~>`. Search for that first, then find EI after it.
                // This avoids false-positive `\nEI` matches inside the ASCII85 data.
                let mut found_a85_end = false;
                let mut scan = search_from;
                while scan + 1 < data.len() {
                    if data[scan] == b'~' {
                        if data[scan + 1] == b'>' {
                            // Standard `~>` end-of-data marker
                            end = scan + 2;
                        } else if is_whitespace_byte(data[scan + 1]) {
                            // Malformed: `~` followed by whitespace (missing `>`)
                            // Accept if `EI` follows shortly after.
                            let mut probe = scan + 1;
                            while probe < data.len() && is_whitespace_byte(data[probe]) {
                                probe += 1;
                            }
                            if probe + 1 < data.len()
                                && data[probe] == b'E'
                                && data[probe + 1] == b'I'
                            {
                                end = scan + 1;
                            } else {
                                scan += 1;
                                continue;
                            }
                        } else {
                            scan += 1;
                            continue;
                        }
                        while end < data.len() && is_whitespace_byte(data[end]) {
                            end += 1;
                        }
                        // `end` should now point at 'E' of "EI"
                        found_a85_end = true;
                        found_no_ws = true;
                        break;
                    }
                    scan += 1;
                }
                if !found_a85_end {
                    // No `~>` found — fall back to standard search
                    while end + 2 < data.len() {
                        if is_whitespace_byte(data[end])
                            && data[end + 1] == b'E'
                            && data[end + 2] == b'I'
                            && (end + 3 >= data.len() || is_delimiter_or_ws(data[end + 3]))
                        {
                            break;
                        }
                        end += 1;
                    }
                }
            } else {
                while end + 2 < data.len() {
                    if is_whitespace_byte(data[end])
                        && data[end + 1] == b'E'
                        && data[end + 2] == b'I'
                        && (end + 3 >= data.len() || is_delimiter_or_ws(data[end + 3]))
                    {
                        break;
                    }
                    end += 1;
                }
            }
        }

        let sample_data = data[start..end.min(data.len())].to_vec();
        // Skip past EI: "EI" is 2 bytes, plus trailing whitespace/delimiter
        let skip_past = if found_no_ws {
            // EI at `end`, skip "EI" + 1 trailing byte
            (end + 3).min(data.len())
        } else {
            // ws+EI at `end`, skip ws+"EI" + 1 trailing byte
            (end + 4).min(data.len())
        };
        lexer.set_pos(skip_past);

        // Apply filters if present
        let sample_data = if has_filter {
            match crate::filters::parse_filters(&dict, Some(self.resolver)) {
                Ok((filters, parms)) if !filters.is_empty() => {
                    crate::filters::decode_stream(&sample_data, &filters, &parms, None)
                        .unwrap_or(sample_data)
                }
                _ => sample_data,
            }
        } else {
            sample_data
        };

        // Build color space for display list
        let polarity = if is_image_mask {
            if let Some(arr) = dict.get_array(b"Decode") {
                let vals: Vec<f64> = arr.iter().filter_map(|o| o.as_f64()).collect();
                vals.len() >= 2 && vals[0] > 0.5
            } else {
                false
            }
        } else {
            false
        };

        let image_matrix =
            Matrix::new(width as f64, 0.0, 0.0, -(height as f64), 0.0, height as f64);

        // Imagemask with shading pattern fill: use SoftMasked to clip shading to mask shape
        if is_image_mask && self.gstate.fill_shading_pattern.is_some() {
            let shading_box = self.gstate.fill_shading_pattern.clone().unwrap();

            // Convert 1-bit imagemask to 8-bit grayscale for luminosity soft mask
            // (white=opaque where painted, black=transparent)
            let row_bytes = width.div_ceil(8);
            let mut gray = vec![0u8; (width * height) as usize];
            for y in 0..height {
                for x in 0..width {
                    let byte_idx = (y * row_bytes + x / 8) as usize;
                    let bit_idx = 7 - (x % 8);
                    let bit = if byte_idx < sample_data.len() {
                        (sample_data[byte_idx] >> bit_idx) & 1
                    } else {
                        0
                    };
                    // Default Decode [0 1]: bit=0 → painted (opaque=255)
                    // Inverted [1 0]:      bit=1 → painted (opaque=255)
                    let painted = if polarity { bit == 1 } else { bit == 0 };
                    gray[(y * width + x) as usize] = if painted { 255 } else { 0 };
                }
            }

            // Mask display list: the imagemask as a grayscale image
            let mut mask_dl = DisplayList::new();
            mask_dl.push(DisplayElement::Image {
                sample_data: Arc::new(gray),
                params: ImageParams {
                    width,
                    height,
                    color_space: ImageColorSpace::DeviceGray,
                    bits_per_component: 8,
                    ctm: self.gstate.ctm,
                    image_matrix,
                    interpolate: false,
                    mask_color: None,
                    alpha: 1.0,
                    blend_mode: 0,
                    overprint: false,
                    overprint_mode: 0,
                    opm_paired: false,
                    painted_channels: 0,
                    alpha_is_shape: false,
                    rendering_intent: 0,
                },
            });

            // Content display list: the shading pattern
            let mut content_dl = DisplayList::new();
            for elem in shading_box.0.elements() {
                content_dl.push(elem.clone());
            }

            // Compute device-space bbox of the image
            let corners = [
                self.gstate.ctm.transform_point(0.0, 0.0),
                self.gstate.ctm.transform_point(width as f64, 0.0),
                self.gstate.ctm.transform_point(0.0, height as f64),
                self.gstate.ctm.transform_point(width as f64, height as f64),
            ];
            let x_min = corners.iter().map(|c| c.0).fold(f64::INFINITY, f64::min);
            let y_min = corners.iter().map(|c| c.1).fold(f64::INFINITY, f64::min);
            let x_max = corners
                .iter()
                .map(|c| c.0)
                .fold(f64::NEG_INFINITY, f64::max);
            let y_max = corners
                .iter()
                .map(|c| c.1)
                .fold(f64::NEG_INFINITY, f64::max);

            let parent_clip_bbox = self.current_clip_bbox();
            self.display_list.push(DisplayElement::SoftMasked {
                mask: mask_dl,
                content: content_dl,
                params: SoftMaskParams {
                    subtype: SoftMaskSubtype::Luminosity,
                    bbox: [x_min, y_min, x_max, y_max],
                    backdrop_color: None,
                    transfer_invert: false,
                    has_nested_mask_scope: false,
                    parent_clip_bbox,
                },
                mask_cache: Arc::new(Mutex::new(None)),
            });
            return Ok(());
        }

        let color_space = if is_image_mask {
            ImageColorSpace::Mask {
                color: self.gstate.fill_color.clone(),
                polarity,
                spot_color: self.gstate.fill_spot_color.clone(),
            }
        } else {
            to_image_color_space(resolved_cs.as_ref().unwrap())
        };

        // Expand bits if needed (but NOT for image masks — keep raw 1-bit packed data)
        let is_indexed = matches!(&color_space, ImageColorSpace::Indexed { .. });
        let sample_data = if !is_image_mask && bpc != 8 && bpc != 0 {
            expand_bits_to_bytes(&sample_data, bpc, width, height, n_components, is_indexed)
        } else {
            sample_data
        };

        // PDF/X CMYK group: route DeviceGray / Separation-with-gray-alt /
        // DeviceN-with-gray-alt images through the K plate so they composite
        // equivalently to DeviceCMYK 0/0/0/(1−g).
        let (color_space, sample_data) = if !is_image_mask {
            self.cmyk_group_promote_image(color_space, sample_data, width, height)
        } else {
            (color_space, sample_data)
        };

        // Register ICC profile with the cache so the rasterizer can find it
        // by hash.  Color conversion itself is deferred to samples_to_rgba().
        if !is_image_mask {
            if let Some(ref rcs) = resolved_cs {
                register_icc_profile(rcs, &mut self.icc_cache);
            }
        }

        self.display_list.push(DisplayElement::Image {
            sample_data: Arc::new(sample_data),
            params: ImageParams {
                width,
                height,
                color_space,
                bits_per_component: 8,
                ctm: self.gstate.ctm,
                image_matrix,
                interpolate: false,
                mask_color: None,
                alpha: self.gstate.fill_alpha,
                blend_mode: self.gstate.blend_mode,
                overprint: self.gstate.overprint,
                overprint_mode: self.gstate.overprint_mode,
                opm_paired: self.gstate.opm_paired,
                painted_channels: resolved_cs
                    .as_ref()
                    .map(painted_channels_for_cs)
                    .unwrap_or(self.gstate.fill_painted_channels),
                alpha_is_shape: self.gstate.alpha_is_shape,
                rendering_intent: 0,
            },
        });

        Ok(())
    }

    /// Apply ExtGState dictionary entries.
    fn apply_ext_gstate(&mut self, name: &[u8]) -> Result<(), PdfError> {
        let ext_dict = self
            .resolve_resource_subdict(b"ExtGState")
            .ok_or(PdfError::Other("no ExtGState resources".into()))?;
        let gs_ref = ext_dict.get(name).ok_or_else(|| {
            PdfError::Other(format!(
                "ExtGState /{} not found",
                String::from_utf8_lossy(name)
            ))
        })?;
        let gs_obj = self.resolver.deref(gs_ref)?;
        let gs_dict = gs_obj
            .as_dict()
            .ok_or(PdfError::Other("ExtGState is not a dict".into()))?;

        // Apply known keys
        if let Some(lw) = gs_dict.get_f64(b"LW") {
            self.gstate.line_width = lw;
        }
        if let Some(lc) = gs_dict.get_int(b"LC")
            && let Some(cap) = LineCap::from_i32(lc as i32)
        {
            self.gstate.line_cap = cap;
        }
        if let Some(lj) = gs_dict.get_int(b"LJ")
            && let Some(join) = LineJoin::from_i32(lj as i32)
        {
            self.gstate.line_join = join;
        }
        if let Some(ml) = gs_dict.get_f64(b"ML") {
            self.gstate.miter_limit = ml;
        }
        if let Some(fl) = gs_dict.get_f64(b"FL") {
            self.gstate.flatness = fl;
        }
        if let Some(PdfObj::Bool(sa)) = gs_dict.get(b"SA") {
            self.gstate.stroke_adjust = *sa;
        }
        // Always parse OPM — it affects whether CMYK all-zero is transparent,
        // which is needed even without full overprint simulation.
        let has_opm = gs_dict.get(b"OPM").is_some();
        if let Some(opm) = gs_dict.get_int(b"OPM") {
            self.gstate.overprint_mode = opm as i32;
        }
        let has_op_flag = gs_dict.get(b"OP").is_some() || gs_dict.get(b"op").is_some();
        if self.overprint_enabled {
            if let Some(PdfObj::Bool(op)) = gs_dict.get(b"OP") {
                self.gstate.overprint = *op;
                // OP also sets stroke overprint
                self.gstate.overprint_stroke = *op;
            }
            if let Some(PdfObj::Bool(op)) = gs_dict.get(b"op") {
                self.gstate.overprint = *op;
            }
        }
        // Track whether the current ExtGState signals "strict overprint",
        // meaning the strict OPM-1 "zero-source preserves backdrop" rule
        // applies. Two patterns count as a strict signal:
        //   1. /OPM together with /op|/OP in the same dict (Adobe Illustrator
        //      asserts both when emitting overprint).
        //   2. /OP and /op together in the same dict — legacy "old-style"
        //      overprint that drove both stroke and fill, used by GWG 12.0
        //      White Overprint where /GS6 sets `/OP true /op true`.
        // An /op set in isolation, with OPM merely inherited (e.g. 2495.pdf
        // page 5 page-icon: /R11 sets /OPM 1, /R20 sets only /op), falls
        // back to legacy "zero = knockout" semantics so `0 0 0 0 k` paints
        // still act as a white knockout.
        let has_op_upper = gs_dict.get(b"OP").is_some();
        let has_op_lower = gs_dict.get(b"op").is_some();
        let strict_signal = (has_opm && has_op_flag) || (has_op_upper && has_op_lower);
        if strict_signal {
            self.gstate.opm_paired = true;
        } else if has_opm || has_op_flag {
            self.gstate.opm_paired = false;
        }
        if let Some(ca) = gs_dict.get_f64(b"CA") {
            self.gstate.stroke_alpha = ca;
        }
        if let Some(ca) = gs_dict.get_f64(b"ca") {
            self.gstate.fill_alpha = ca;
        }
        if let Some(b) = gs_dict.get_bool(b"AIS") {
            self.gstate.alpha_is_shape = b;
        }
        if let Some(b) = gs_dict.get_bool(b"TK") {
            self.gstate.text_knockout = b;
        }
        // Rendering intent — feeds into the per-intent ICC chain dispatch.
        if let Some(PdfObj::Name(ri)) = gs_dict.get(b"RI") {
            self.gstate.rendering_intent = match ri.as_slice() {
                b"Perceptual" => 0,
                b"RelativeColorimetric" => 1,
                b"Saturation" => 2,
                b"AbsoluteColorimetric" => 3,
                _ => 0,
            };
        }

        // Blend mode
        if let Some(bm) = gs_dict.get(b"BM") {
            let bm = self.resolver.deref(bm).unwrap_or_else(|_| bm.clone());
            match &bm {
                PdfObj::Name(name) => {
                    self.gstate.blend_mode = blend_mode_from_name(name);
                }
                PdfObj::Array(arr) => {
                    for obj in arr {
                        if let PdfObj::Name(name) = obj {
                            let mode = blend_mode_from_name(name);
                            if mode != 0 || name.as_slice() == b"Normal" {
                                self.gstate.blend_mode = mode;
                                break;
                            }
                        }
                    }
                }
                _ => {}
            }
        }

        // Dash pattern
        if let Some(d_arr) = gs_dict.get_array(b"D")
            && d_arr.len() == 2
            && let (Some(arr), Some(offset)) = (d_arr[0].as_array(), d_arr[1].as_f64())
        {
            let array: Vec<f64> = arr.iter().filter_map(|o| o.as_f64()).collect();
            self.gstate.dash_pattern = DashPattern { array, offset };
        }

        // Font — array [font_ref size] sets both font and size
        if let Some(font_arr) = gs_dict.get_array(b"Font")
            && font_arr.len() == 2
            && let Some(size) = font_arr[1].as_f64()
        {
            self.gstate.font_size = size;
            // Resolve the font object from the first array element
            let font_ref = &font_arr[0];
            // Use object number as cache key, or a fallback synthetic name
            let cache_key = if let PdfObj::Ref(obj_num, _) = font_ref {
                format!("__gs_font_{obj_num}").into_bytes()
            } else {
                b"__gs_font_inline".to_vec()
            };
            if let Some(cached) = self.font_cache.get(&cache_key) {
                self.current_font = Some(Arc::clone(cached));
            } else {
                match font::resolve_font(self.resolver, font_ref, self.font_provider.as_ref()) {
                    Ok(font) => {
                        let arc = Arc::new(font);
                        self.font_cache.insert(cache_key, Arc::clone(&arc));
                        self.current_font = Some(arc);
                    }
                    Err(e) => {
                        eprintln!("warning: ExtGState Font: {e}");
                    }
                }
            }
        }

        // Transfer function: TR2 takes priority over TR
        if let Some(tr_obj) = gs_dict.get(b"TR2").or_else(|| gs_dict.get(b"TR")) {
            self.gstate.transfer = self.parse_transfer_function(tr_obj)?;
        }

        // Soft mask
        if let Some(smask_obj) = gs_dict.get(b"SMask") {
            let smask_obj = self.resolver.deref(smask_obj)?;
            match &smask_obj {
                PdfObj::Name(n) if n.as_slice() == b"None" => {
                    self.flush_soft_mask();
                    self.gstate.soft_mask = None;
                }
                PdfObj::Dict(d) => {
                    self.flush_soft_mask();
                    match self.resolve_soft_mask(d) {
                        Ok(sm) => {
                            let start_index = self.display_list.len();
                            self.gstate.soft_mask = Some(sm.clone());
                            self.gstate.smask_gen += 1;
                            self.soft_mask_scope = Some(SoftMaskScope {
                                start_index,
                                mask: sm,
                            });
                        }
                        Err(e) => {
                            eprintln!("warning: SMask resolve error: {}", e);
                        }
                    }
                }
                _ => {}
            }
        }

        Ok(())
    }

    /// Flush the current soft mask scope: wrap accumulated elements in SoftMasked.
    fn flush_soft_mask(&mut self) {
        if let Some(scope) = self.soft_mask_scope.take()
            && self.display_list.len() > scope.start_index
        {
            let content = self.display_list.split_off(scope.start_index);

            // Skip conditions:
            //
            // 1. The mask display list is empty: there is no mask raster
            //    to compute, so the SoftMasked element would have nothing
            //    to do — emit content directly.
            //
            // 2. (5795.pdf-style escape hatch) The mask form's bbox does
            //    not have *substantial* overlap with the content's painted
            //    area AND the backdrop is black. In this case the mask, if
            //    honored literally, would multiply most content pixels by
            //    0 (the BC fallback) and effectively erase the content.
            //    Both Ghostscript and Poppler short-circuit this and render
            //    the content as if no mask were present. We match that for:
            //
            //    - 5795.pdf: botanical background image. The mask `/G` form
            //      bbox sits at PDF x=[-767.7, 0.29] (essentially all
            //      negative-x). The content image is at PDF x=[0, 768].
            //      The bboxes touch only in the [0, 0.29 pt] sliver — no
            //      substantial overlap.
            //    - 907.pdf p24: gradient callout arrows. The SMask `/G`
            //      form bbox is at PDF y=[-155.6, -52.4] (negative-y, off
            //      the bottom of the page). The content image is at PDF
            //      y=[423, 501] — disjoint from the mask form bbox.
            //
            //    The CRITICAL distinction from 5296.pdf's /GS29 + /Fm30
            //    bug is that in 5296 the mask form's bbox at PDF
            //    x=[-519, -8] overlaps the content rectangle's bbox at
            //    PDF x=[-390, 121] across ~382 pt of x. The mask is
            //    *meant* to apply to the content — the visible portion of
            //    the content (x=[0, 121]) just falls outside the mask's
            //    spatial extent and should be erased by the BC=0 fallback.
            //
            //    The threshold of 2 device pt in both dimensions matches
            //    the original `mask_has_meaningful_overlap` threshold but
            //    measures against the content bbox (not the parent clip
            //    bbox), which is what actually distinguishes the two
            //    cases.
            let content_bbox = self.content_paint_bbox(&content);
            let drop_shadow_skip = scope.mask.backdrop_color == Some([0.0, 0.0, 0.0])
                && content_bbox
                    .map(|c| !bboxes_overlap_substantially(&c, &scope.mask.bbox, 2.0))
                    .unwrap_or(false);
            let skip = scope.mask.mask_list.is_empty() || drop_shadow_skip;
            if skip {
                for elem in content.into_elements() {
                    self.display_list.push(elem);
                }
            } else {
                // Collect Clip/InitClip elements to replay after SoftMasked.
                // The mask scope may capture clip operations that were established
                // in gsave levels that extend beyond the scope — these must remain
                // in the main display list to affect subsequent rendering.
                let clip_replay: Vec<DisplayElement> = content
                    .elements()
                    .iter()
                    .filter(|e| matches!(e, DisplayElement::Clip { .. } | DisplayElement::InitClip))
                    .cloned()
                    .collect();
                let parent_clip_bbox = self.current_clip_bbox();
                self.display_list.push(DisplayElement::SoftMasked {
                    mask: scope.mask.mask_list,
                    content,
                    params: SoftMaskParams {
                        subtype: scope.mask.subtype,
                        bbox: scope.mask.bbox,
                        backdrop_color: scope.mask.backdrop_color,
                        transfer_invert: scope.mask.transfer_invert,
                        has_nested_mask_scope: scope.mask.has_nested_mask_scope,
                        parent_clip_bbox,
                    },
                    mask_cache: Arc::new(Mutex::new(None)),
                });
                for elem in clip_replay {
                    self.display_list.push(elem);
                }
            }
        }
    }

    /// Resolve the number of color components from a form XObject's /Group/CS.
    /// Both /Group and /CS may be indirect references.
    fn resolve_group_cs_comps(&self, form_dict: &PdfDict) -> usize {
        let cs_name_to_comps = |cs: &[u8]| -> usize {
            match cs {
                b"DeviceGray" => 1,
                b"DeviceRGB" => 3,
                b"DeviceCMYK" => 4,
                _ => 0,
            }
        };

        let grp_obj = match form_dict.get(b"Group") {
            Some(obj) => obj,
            None => return 0,
        };

        // Get the Group dict — may be inline or indirect
        let resolved_grp;
        let grp = if let Some(d) = grp_obj.as_dict() {
            d
        } else if let Ok(r) = self.resolver.deref(grp_obj) {
            resolved_grp = r;
            match resolved_grp.as_dict() {
                Some(d) => d,
                None => return 0,
            }
        } else {
            return 0;
        };

        // Get CS — may be inline name or indirect
        if let Some(cs) = grp.get_name(b"CS") {
            return cs_name_to_comps(cs);
        }
        if let Some(cs_obj) = grp.get(b"CS") {
            if let Ok(cs_resolved) = self.resolver.deref(cs_obj) {
                if let Some(cs) = cs_resolved.as_name() {
                    return cs_name_to_comps(cs);
                }
            }
        }
        0
    }

    /// Compute the union of paint bounds for the elements in `content`.
    /// Returns `None` if no element contributes a bounded paint extent.
    ///
    /// This is a coarse estimate used by `flush_soft_mask` to decide
    /// whether the mask form's bbox overlaps the content. Only the most
    /// common element kinds are inspected (Fill, Stroke, Image, Group,
    /// SoftMasked, PatternFill); shading elements and text are treated
    /// as contributing no bound (we conservatively skip them, which
    /// for the drop-shadow-skip heuristic means we'll trust the result
    /// from the other elements present).
    fn content_paint_bbox(&self, content: &DisplayList) -> Option<[f64; 4]> {
        let mut x_min = f64::INFINITY;
        let mut y_min = f64::INFINITY;
        let mut x_max = f64::NEG_INFINITY;
        let mut y_max = f64::NEG_INFINITY;
        let mut grow = |bx: [f64; 4]| {
            x_min = x_min.min(bx[0].min(bx[2]));
            y_min = y_min.min(bx[1].min(bx[3]));
            x_max = x_max.max(bx[0].max(bx[2]));
            y_max = y_max.max(bx[1].max(bx[3]));
        };
        for elem in content.elements() {
            match elem {
                DisplayElement::Fill { path, .. }
                | DisplayElement::Stroke { path, .. }
                | DisplayElement::Clip { path, .. } => {
                    let mut px_min = f64::INFINITY;
                    let mut py_min = f64::INFINITY;
                    let mut px_max = f64::NEG_INFINITY;
                    let mut py_max = f64::NEG_INFINITY;
                    for seg in &path.segments {
                        let pts: &[(f64, f64)] = match seg {
                            PathSegment::MoveTo(x, y) | PathSegment::LineTo(x, y) => &[(*x, *y)],
                            PathSegment::CurveTo {
                                x1,
                                y1,
                                x2,
                                y2,
                                x3,
                                y3,
                            } => &[(*x1, *y1), (*x2, *y2), (*x3, *y3)][..],
                            PathSegment::ClosePath => &[],
                        };
                        for (x, y) in pts {
                            px_min = px_min.min(*x);
                            py_min = py_min.min(*y);
                            px_max = px_max.max(*x);
                            py_max = py_max.max(*y);
                        }
                    }
                    if px_min.is_finite() && px_min < px_max && py_min < py_max {
                        grow([px_min, py_min, px_max, py_max]);
                    }
                }
                DisplayElement::Image { params, .. } => {
                    // Image is drawn into the unit square mapped through
                    // params.ctm. Compute the four corner positions.
                    let ctm = &params.ctm;
                    let corners = [
                        ctm.transform_point(0.0, 0.0),
                        ctm.transform_point(1.0, 0.0),
                        ctm.transform_point(0.0, 1.0),
                        ctm.transform_point(1.0, 1.0),
                    ];
                    let mut ix_min = f64::INFINITY;
                    let mut iy_min = f64::INFINITY;
                    let mut ix_max = f64::NEG_INFINITY;
                    let mut iy_max = f64::NEG_INFINITY;
                    for (cx, cy) in &corners {
                        ix_min = ix_min.min(*cx);
                        iy_min = iy_min.min(*cy);
                        ix_max = ix_max.max(*cx);
                        iy_max = iy_max.max(*cy);
                    }
                    grow([ix_min, iy_min, ix_max, iy_max]);
                }
                DisplayElement::Group { params, .. } => {
                    grow(params.bbox);
                }
                DisplayElement::SoftMasked { params, .. } => {
                    grow(params.bbox);
                }
                _ => {} // Shadings, patterns, text — coarse estimate skips them.
            }
        }
        if x_min.is_finite() && x_min < x_max && y_min < y_max {
            Some([x_min, y_min, x_max, y_max])
        } else {
            None
        }
    }

    /// Resolve a soft mask dictionary into a SoftMask.
    fn resolve_soft_mask(&mut self, dict: &PdfDict) -> Result<graphics_state::SoftMask, PdfError> {
        // The mask group's form is interpreted directly below rather than
        // through `handle_form_xobject`, so it does not inherit that path's
        // guard. A form whose content re-selects the ExtGState naming this
        // same mask would otherwise recurse until the stack is exhausted.
        if self.depth >= MAX_CONTENT_NESTING {
            return Err(PdfError::Other("soft mask nesting too deep".into()));
        }

        // Parse /S (subtype): Alpha or Luminosity (default Luminosity)
        let subtype = match dict.get_name(b"S") {
            Some(b"Alpha") => SoftMaskSubtype::Alpha,
            _ => SoftMaskSubtype::Luminosity,
        };

        // Parse /G (Form XObject) — required
        let g_ref = dict
            .get(b"G")
            .ok_or_else(|| PdfError::Other("SMask missing /G".into()))?;
        let g_obj = self.resolver.deref(g_ref)?;
        let g_dict = g_obj
            .as_dict()
            .ok_or_else(|| PdfError::Other("SMask /G is not a dict".into()))?;

        // Get form BBox
        let bbox_tuple = if let Some(vals) = deref_num_array(self.resolver, g_dict, b"BBox") {
            if vals.len() == 4 {
                Some((vals[0], vals[1], vals[2], vals[3]))
            } else {
                None
            }
        } else {
            None
        };

        // Form matrix
        let form_matrix = if let Some(vals) = deref_num_array(self.resolver, g_dict, b"Matrix") {
            if vals.len() == 6 {
                Matrix::new(vals[0], vals[1], vals[2], vals[3], vals[4], vals[5])
            } else {
                Matrix::identity()
            }
        } else {
            Matrix::identity()
        };

        // Get form resources
        let form_resources = if let Some(res_obj) = g_dict.get(b"Resources") {
            match self.resolver.deref(res_obj)? {
                PdfObj::Dict(d) => d,
                _ => self.resources.clone(),
            }
        } else {
            self.resources.clone()
        };

        // Render the form into a display list
        let form_data = self.resolver.stream_data_from_obj(g_ref)?;

        // Save state and render (clear font cache — the mask form may have
        // different font resources with the same resource names as the parent)
        self.gstate_stack.push(self.gstate.clone());
        let saved_resources = std::mem::replace(&mut self.resources, form_resources);
        let saved_font_cache = std::mem::take(&mut self.font_cache);
        let saved_current_font2 = self.current_font.take();
        let saved_cs_index2 = self.cs_index.take();
        let saved_display_list = std::mem::replace(&mut self.display_list, DisplayList::new());
        let saved_scope = self.soft_mask_scope.take();
        let saved_content_stream_ctm = self.content_stream_ctm;
        let saved_mc_stack = std::mem::take(&mut self.mc_stack);

        // Apply form matrix to CTM
        self.gstate.ctm = self.gstate.ctm.concat(&form_matrix);
        // Update content_stream_ctm so shading patterns inside the mask form
        // use the form's coordinate system, not the parent's.
        self.content_stream_ctm = self.gstate.ctm;

        // Reset alpha and soft mask: the mask form is an independent rendering
        // context. Without this, the parent's ca/CA leak into the mask form
        // (e.g. ca=0.9 making mask form elements semi-transparent).
        self.gstate.fill_alpha = 1.0;
        self.gstate.stroke_alpha = 1.0;
        self.gstate.soft_mask = None;

        // Compute device-space bbox now, before interpret_stream modifies the
        // CTM via `cm` operators. The form BBox is in the form's coordinate
        // system (after form matrix), not the content's rotated space.
        let device_bbox = self.compute_device_bbox(bbox_tuple);

        // Clip to BBox
        if let Some((x0, y0, x1, y1)) = bbox_tuple {
            self.push_bbox_clip(x0, y0, x1, y1);
        }

        // Disable ICC CMYK conversion inside soft mask forms. ICC profiles
        // map 100% K to non-zero RGB (e.g. (44,41,42)), giving non-zero
        // luminosity where the mask should be opaque black. PLRM formulas
        // produce exact (0,0,0) for CMYK (0,0,0,1), yielding correct
        // luminosity = 0 for the mask.
        let saved_cmyk_hash = self.icc_cache.suspend_default_cmyk();
        // Suppress the DeviceGray-to-K-only promotion while parsing the SMask
        // form. The promotion produces a DeviceCMYK image whose ICC
        // conversion happens at render time (after the suspension above is
        // restored), so the parse-time suspend never sees it. Skipping the
        // promotion here keeps the SMask source's display list in its
        // original DeviceGray form, which the renderer paints gray-to-gray
        // without ICC — luminosity = g/255 exactly (regressed
        // `pdf_samples/2495.pdf`'s right-side SMask images).
        let saved_in_smask_form = self.in_smask_form;
        self.in_smask_form = true;

        let saved_nested_mask_flush_count = self.nested_mask_flush_count;
        self.depth += 1;
        let _ = self.interpret_stream(&form_data);
        self.depth -= 1;

        self.in_smask_form = saved_in_smask_form;
        self.icc_cache.restore_default_cmyk(saved_cmyk_hash);

        // Check if Q handlers flushed any gs-set nested soft mask scopes
        // during interpretation. This is tracked via a counter that's
        // incremented in op_big_q when smask_gen changes (NOT by image-level
        // SMasks or other SoftMasked element sources).
        let has_nested_mask_scope = self.nested_mask_flush_count > saved_nested_mask_flush_count;

        // Flush any soft mask scope opened inside the mask form
        self.flush_soft_mask();

        let mask_list = std::mem::replace(&mut self.display_list, saved_display_list);
        self.soft_mask_scope = saved_scope;
        self.content_stream_ctm = saved_content_stream_ctm;
        self.resources = saved_resources;
        self.font_cache = saved_font_cache;
        self.current_font = saved_current_font2;
        self.cs_index = saved_cs_index2;
        self.mc_stack = saved_mc_stack;
        if let Some(saved) = self.gstate_stack.pop() {
            self.gstate = saved;
        }

        // Parse /BC (backdrop color) — may be inline array or indirect reference.
        // BC is in the group's color space, so we check /G's /Group/CS to know
        // how many components to use (rather than guessing from array length).
        let group_n_comps = self.resolve_group_cs_comps(g_dict);

        let backdrop_color = if let Some(bc_obj) = dict.get(b"BC") {
            let bc_resolved = self.resolver.deref(bc_obj).ok();
            let bc_arr = bc_resolved
                .as_ref()
                .and_then(|o| o.as_array())
                .or_else(|| bc_obj.as_array());
            if let Some(arr) = bc_arr {
                let vals: Vec<f64> = arr.iter().filter_map(|o| o.as_f64()).collect();
                if group_n_comps == 1 && !vals.is_empty() {
                    // DeviceGray: first value is gray level
                    Some([vals[0], vals[0], vals[0]])
                } else if group_n_comps == 4 && vals.len() >= 4 {
                    // DeviceCMYK
                    let c = vals[0];
                    let m = vals[1];
                    let y = vals[2];
                    let k = vals[3];
                    Some([
                        (1.0 - c) * (1.0 - k),
                        (1.0 - m) * (1.0 - k),
                        (1.0 - y) * (1.0 - k),
                    ])
                } else if vals.len() >= 3 {
                    Some([vals[0], vals[1], vals[2]])
                } else if vals.len() == 1 {
                    Some([vals[0], vals[0], vals[0]])
                } else {
                    None
                }
            } else {
                None
            }
        } else {
            // No /BC specified: default is all zeros in the group color space.
            // For DeviceCMYK, [0,0,0,0] = no ink = white → RGB [1,1,1].
            // For DeviceRGB/Gray, [0,0,0] = black → RGB [0,0,0] (luminosity 0).
            if group_n_comps == 4 {
                Some([1.0, 1.0, 1.0])
            } else {
                None
            }
        };

        // Check for /TR (transfer function). The common case is {1 exch sub}
        // which inverts the mask values. Detect this and set a flag.
        // Check for /TR (transfer function). The common case is {1 exch sub}
        // which inverts the mask values. Detect this by reading the stream content.
        let transfer_invert = if let Some(tr_obj) = dict.get(b"TR") {
            if let Ok(tr_data) = self.resolver.stream_data_from_obj(tr_obj) {
                let trimmed: Vec<u8> = tr_data
                    .iter()
                    .copied()
                    .filter(|b| !b.is_ascii_whitespace())
                    .collect();
                let s = String::from_utf8_lossy(&trimmed);
                s.contains("exchsub")
            } else {
                false
            }
        } else {
            false
        };

        // When BC is specified and produces a non-zero luminosity value, the
        // soft mask extends beyond the form's BBox — the BC backdrop fills all
        // areas outside the form content. Expand the bbox to cover the entire
        // viewport so the renderer doesn't crop the mask to the form's BBox.
        let effective_bbox = if let Some(bc) = &backdrop_color {
            let bc_lum = 0.2126 * bc[0] + 0.7152 * bc[1] + 0.0722 * bc[2];
            let bc_byte = (bc_lum * 255.0 + 0.5) as u8;
            // After transfer inversion, the effective mask value is 255 - bc_byte.
            // If either the original or inverted value is non-zero, the mask has
            // effect outside the form BBox.
            let effective = if transfer_invert {
                255 - bc_byte
            } else {
                bc_byte
            };
            if effective > 0 {
                [0.0, 0.0, 1e9, 1e9]
            } else {
                device_bbox
            }
        } else {
            device_bbox
        };

        Ok(graphics_state::SoftMask {
            mask_list,
            subtype,
            bbox: effective_bbox,
            backdrop_color,
            transfer_invert,
            has_nested_mask_scope,
        })
    }

    /// Parse a TR/TR2 value into a TransferState.
    ///
    /// PDF spec: TR/TR2 can be a single function (applied to all channels),
    /// an array of 4 functions [R, G, B, Gray], or /Identity.
    fn parse_transfer_function(
        &self,
        obj: &PdfObj,
    ) -> Result<stet_graphics::device::TransferState, PdfError> {
        use crate::resources::function::PdfFunction;
        use stet_graphics::device::TransferState;

        let obj = self.resolver.deref(obj)?;

        // /Identity or /Default → no transfer
        if let Some(name) = obj.as_name()
            && (name == b"Identity" || name == b"Default")
        {
            return Ok(TransferState::default());
        }

        // Array of 4 functions [R, G, B, Gray]
        if let PdfObj::Array(arr) = &obj
            && arr.len() == 4
        {
            let mut tables: [Option<Arc<Vec<f64>>>; 4] = Default::default();
            for (i, fn_obj) in arr.iter().enumerate() {
                let fn_obj = self.resolver.deref(fn_obj)?;
                if let Some(name) = fn_obj.as_name()
                    && (name == b"Identity" || name == b"Default")
                {
                    continue; // None = identity
                }
                if let Ok(func) = PdfFunction::parse(&fn_obj, self.resolver) {
                    tables[i] = Some(Arc::new(sample_transfer_function(&func)));
                }
            }
            return Ok(TransferState {
                gray: None,
                color: Some(tables),
            });
        }

        // Single function → apply to all channels via gray
        if let Ok(func) = PdfFunction::parse(&obj, self.resolver) {
            let table = Arc::new(sample_transfer_function(&func));
            return Ok(TransferState {
                gray: Some(table),
                color: None,
            });
        }

        Ok(TransferState::default())
    }

    // === Shading operator ===

    fn op_sh(&mut self) -> Result<(), PdfError> {
        let name = self
            .operand_stack
            .last()
            .and_then(|o| o.as_name())
            .ok_or(PdfError::Other("sh: expected name".into()))?
            .to_vec();

        let shading_dict = self
            .resolve_resource_subdict(b"Shading")
            .ok_or(PdfError::Other("no Shading resources".into()))?;
        let sh_ref = shading_dict.get(&name).ok_or_else(|| {
            PdfError::Other(format!(
                "Shading /{} not found",
                String::from_utf8_lossy(&name)
            ))
        })?;
        let sh_ref_clone = sh_ref.clone();
        let sh_obj = self.resolver.deref(sh_ref)?;
        let sh_dict = sh_obj
            .as_dict()
            .ok_or(PdfError::Other("Shading is not a dict".into()))?;

        crate::resources::shading::handle_shading(
            &sh_ref_clone,
            sh_dict,
            &self.gstate,
            self.resolver,
            &mut self.display_list,
            &mut self.icc_cache,
        )
    }

    // === Pattern operators ===

    fn handle_pattern_fill(&mut self) -> Result<(), PdfError> {
        let name = self
            .operand_stack
            .last()
            .and_then(|o| o.as_name())
            .ok_or(PdfError::Other("pattern: expected name".into()))?
            .to_vec();

        // For uncolored patterns (PaintType 2), the scn operands include
        // underlying color components before the pattern name. Extract them
        // by resolving the underlying color space from the Pattern CS definition.
        self.extract_pattern_underlying_color(false)?;

        // Check PatternType before resolving — Type 2 (shading) needs different handling
        let pattern_dict = self
            .resolve_resource_subdict(b"Pattern")
            .ok_or(PdfError::Other("no Pattern resources".into()))?;
        let pat_ref = pattern_dict.get(&name).ok_or_else(|| {
            PdfError::Other(format!(
                "Pattern /{} not found",
                String::from_utf8_lossy(&name)
            ))
        })?;
        let pat_obj = self.resolver.deref(pat_ref)?;
        let pat_dict = pat_obj
            .as_dict()
            .ok_or(PdfError::Other("Pattern is not a dict".into()))?;
        let pattern_type = pat_dict.get_int(b"PatternType").unwrap_or(1) as i32;

        if pattern_type == 2 {
            let shading_dl = self.resolve_shading_pattern(pat_dict)?;
            self.gstate.fill_pattern = None;
            self.gstate.fill_shading_pattern = Some(Box::new(ShadingPatternDL(shading_dl)));
        } else {
            let pattern = self.resolve_pattern(&name)?;
            self.gstate.fill_shading_pattern = None;
            self.gstate.fill_pattern = Some(pattern);
        }
        Ok(())
    }

    fn handle_pattern_stroke(&mut self) -> Result<(), PdfError> {
        let name = self
            .operand_stack
            .last()
            .and_then(|o| o.as_name())
            .ok_or(PdfError::Other("pattern: expected name".into()))?
            .to_vec();

        // Extract underlying color components for uncolored patterns
        self.extract_pattern_underlying_color(true)?;

        // Check PatternType before resolving — Type 2 (shading) needs different handling
        let pattern_dict = self
            .resolve_resource_subdict(b"Pattern")
            .ok_or(PdfError::Other("no Pattern resources".into()))?;
        let pat_ref = pattern_dict.get(&name).ok_or_else(|| {
            PdfError::Other(format!(
                "Pattern /{} not found",
                String::from_utf8_lossy(&name)
            ))
        })?;
        let pat_obj = self.resolver.deref(pat_ref)?;
        let pat_dict = pat_obj
            .as_dict()
            .ok_or(PdfError::Other("Pattern is not a dict".into()))?;
        let pattern_type = pat_dict.get_int(b"PatternType").unwrap_or(1) as i32;

        if pattern_type == 2 {
            let shading_dl = self.resolve_shading_pattern(pat_dict)?;
            self.gstate.stroke_pattern = None;
            self.gstate.stroke_shading_pattern = Some(Box::new(ShadingPatternDL(shading_dl)));
        } else {
            let pattern = self.resolve_pattern(&name)?;
            self.gstate.stroke_shading_pattern = None;
            self.gstate.stroke_pattern = Some(pattern);
        }
        Ok(())
    }

    /// Extract underlying color components from the operand stack for Pattern
    /// color spaces with an underlying CS (e.g., `[/Pattern /DeviceRGB]`).
    /// For `scn` with an uncolored pattern, the operands are `c1 c2 ... /PatName`
    /// where c1..cn are the underlying color components.
    fn extract_pattern_underlying_color(&mut self, is_stroke: bool) -> Result<(), PdfError> {
        // Get the color space reference (fill or stroke)
        let cs_ref = if is_stroke {
            &self.gstate.stroke_color_space
        } else {
            &self.gstate.fill_color_space
        };
        let cs_name = match cs_ref {
            ColorSpaceRef::Named(n) => n.clone(),
            _ => return Ok(()),
        };

        // Look up the Pattern CS definition in resources to find the underlying CS.
        // Use the cached cs_index (built by resolve_cs_cached) for fast lookup,
        // falling back to the raw ColorSpace resource dict.
        let cs_obj_opt: Option<crate::objects::PdfObj> = self
            .cs_index
            .as_ref()
            .and_then(|idx| idx.get(cs_name.as_slice()).cloned())
            .or_else(|| {
                let cs_dict = self
                    .resources
                    .get(b"ColorSpace")
                    .and_then(|obj| match obj {
                        PdfObj::Dict(_) => Some(obj.as_dict().unwrap().clone()),
                        PdfObj::Ref(n, g) => self.resolver.resolve(*n, *g).ok()?.as_dict().cloned(),
                        _ => None,
                    })?;
                cs_dict.get(&cs_name).cloned()
            });
        let cs_obj = match cs_obj_opt {
            Some(obj) => obj.clone(),
            None => return Ok(()),
        };
        let cs_resolved = self.resolver.deref(&cs_obj)?;
        let arr = match &cs_resolved {
            PdfObj::Array(a) if a.len() >= 2 => a,
            _ => return Ok(()),
        };
        // Must be [/Pattern <underlying_cs>]
        if arr[0].as_name() != Some(b"Pattern") {
            return Ok(());
        }
        // Resolve the underlying color space
        let underlying_cs = color_space::resolve_color_space_obj(&arr[1], self.resolver)?;
        let n = underlying_cs.num_components();
        if n == 0 {
            return Ok(());
        }

        // The operand stack has: [... c1 c2 ... cn /PatName]
        // The pattern name is at the end; color components are before it.
        let stack_len = self.operand_stack.len();
        if stack_len < n + 1 {
            return Ok(()); // not enough operands
        }
        // Read n components from positions (stack_len - 1 - n) .. (stack_len - 1)
        let mut nums = Vec::with_capacity(n);
        let base = stack_len - 1 - n;
        for i in 0..n {
            nums.push(self.operand_stack[base + i].as_f64().unwrap_or(0.0));
        }
        let intent = self.gstate.rendering_intent;
        let color = color_space::components_to_device_color_icc_with_intent(
            &underlying_cs,
            &nums,
            Some(&mut self.icc_cache),
            intent,
        );
        if is_stroke {
            self.gstate.stroke_color = color;
        } else {
            self.gstate.fill_color = color;
        }
        Ok(())
    }

    fn resolve_pattern(&mut self, name: &[u8]) -> Result<TilingPattern, PdfError> {
        let pattern_dict = self
            .resolve_resource_subdict(b"Pattern")
            .ok_or(PdfError::Other("no Pattern resources".into()))?;
        let pat_ref = pattern_dict.get(name).ok_or_else(|| {
            PdfError::Other(format!(
                "Pattern /{} not found",
                String::from_utf8_lossy(name)
            ))
        })?;

        // Cache tiling patterns by indirect reference — ensures the same
        // pattern stream is interpreted only once (with the first caller's
        // graphics state), matching GhostScript's behaviour.
        if let PdfObj::Ref(obj_num, gen_num) = pat_ref {
            if let Some(cached) = self.pattern_cache.get(&(*obj_num, *gen_num)) {
                return Ok(cached.clone());
            }
        }

        let pat_ref_clone = pat_ref.clone();
        let pat_obj = self.resolver.deref(pat_ref)?;
        let pat_dict = pat_obj
            .as_dict()
            .ok_or(PdfError::Other("Pattern is not a dict".into()))?;

        let pattern_type = pat_dict.get_int(b"PatternType").unwrap_or(1) as i32;

        let result = match pattern_type {
            1 => self.resolve_tiling_pattern(&pat_ref_clone, pat_dict),
            _ => Err(PdfError::Other(format!(
                "Unsupported PatternType {pattern_type}"
            ))),
        }?;

        if let PdfObj::Ref(obj_num, gen_num) = pat_ref {
            self.pattern_cache
                .insert((*obj_num, *gen_num), result.clone());
        }

        Ok(result)
    }

    fn resolve_tiling_pattern(
        &mut self,
        pat_obj: &PdfObj,
        pat_dict: &PdfDict,
    ) -> Result<TilingPattern, PdfError> {
        if self.depth >= MAX_CONTENT_NESTING {
            return Err(PdfError::Other("pattern recursion limit".into()));
        }
        let paint_type = pat_dict.get_int(b"PaintType").unwrap_or(1) as i32;

        let bbox = deref_num_array(self.resolver, pat_dict, b"BBox")
            .map(|v| {
                if v.len() >= 4 {
                    [v[0], v[1], v[2], v[3]]
                } else {
                    [0.0, 0.0, 1.0, 1.0]
                }
            })
            .unwrap_or([0.0, 0.0, 1.0, 1.0]);

        let x_step = pat_dict.get_f64(b"XStep").unwrap_or(bbox[2] - bbox[0]);
        let y_step = pat_dict.get_f64(b"YStep").unwrap_or(bbox[3] - bbox[1]);

        let pattern_matrix = deref_num_array(self.resolver, pat_dict, b"Matrix")
            .map(|v| {
                if v.len() >= 6 {
                    Matrix::new(v[0], v[1], v[2], v[3], v[4], v[5])
                } else {
                    Matrix::identity()
                }
            })
            .unwrap_or_else(Matrix::identity);

        let pattern_resources = if let Some(res_ref) = pat_dict.get(b"Resources") {
            match self.resolver.deref(res_ref)? {
                PdfObj::Dict(d) => d,
                _ => self.resources.clone(),
            }
        } else {
            self.resources.clone()
        };

        let pattern_data = self.resolver.stream_data_from_obj(pat_obj)?;

        // Compute the combined pattern matrix (pattern space → device space).
        // PDF pattern Matrix maps pattern space → the default coordinate system
        // of the parent content stream. Use content_stream_ctm so patterns inside
        // Form XObjects include the form's coordinate transform.
        let combined_matrix = self.content_stream_ctm.concat(&pattern_matrix);

        // Interpret pattern content stream with identity CTM, keeping tile
        // elements in pattern space.  The combined_matrix is stored in the
        // TilingPattern and applied per-element by the renderer (same approach
        // as PostScript op_makepattern).
        self.gstate_stack.push(self.gstate.clone());
        let saved_resources = std::mem::replace(&mut self.resources, pattern_resources);
        let saved_display_list = std::mem::take(&mut self.display_list);
        let saved_content_stream_ctm = self.content_stream_ctm;
        let saved_path = std::mem::take(&mut self.current_path);
        let saved_point = self.current_point.take();
        let saved_subpath = self.subpath_start.take();
        let saved_mc_stack = std::mem::take(&mut self.mc_stack);

        self.gstate.ctm = Matrix::identity();
        self.content_stream_ctm = Matrix::identity();
        self.gstate.clip_path = None;
        self.gstate.clip_path_version = 0;
        self.gstate.clip_stack.clear();
        // Clear parent patterns to prevent infinite recursion if the pattern
        // stream references the same pattern resource.
        self.gstate.fill_pattern = None;
        self.gstate.stroke_pattern = None;
        self.gstate.fill_shading_pattern = None;
        self.gstate.stroke_shading_pattern = None;
        // Reset text rendering mode so pattern tiles don't inherit
        // fill+stroke or other modes from the parent content stream.
        self.gstate.text_rendering_mode = 0;

        self.depth += 1;
        let _ = self.interpret_stream(&pattern_data);
        self.depth -= 1;

        // Flush any pending soft mask scope from the pattern stream
        self.flush_soft_mask();

        let tile_display_list = std::mem::replace(&mut self.display_list, saved_display_list);
        self.content_stream_ctm = saved_content_stream_ctm;
        self.resources = saved_resources;
        self.current_path = saved_path;
        self.current_point = saved_point;
        self.subpath_start = saved_subpath;
        self.mc_stack = saved_mc_stack;
        if let Some(saved) = self.gstate_stack.pop() {
            self.gstate = saved;
        }

        Ok(TilingPattern {
            tile: tile_display_list,
            bbox,
            x_step,
            y_step,
            pattern_matrix: combined_matrix,
            paint_type,
            pattern_id: 0,
            flip_tile_y: false,
        })
    }

    /// Resolve a PatternType 2 (shading pattern) by rendering the shading into
    /// a display list. The caller stores this and emits it at fill time,
    /// clipped to the fill path.
    fn resolve_shading_pattern(&mut self, pat_dict: &PdfDict) -> Result<DisplayList, PdfError> {
        let sh_ref = pat_dict
            .get(b"Shading")
            .ok_or(PdfError::Other("shading pattern missing /Shading".into()))?;
        let sh_ref_clone = sh_ref.clone();
        let sh_obj = self.resolver.deref(sh_ref)?;
        let sh_dict = sh_obj
            .as_dict()
            .ok_or(PdfError::Other("Shading is not a dict".into()))?;

        let pattern_matrix = deref_num_array(self.resolver, pat_dict, b"Matrix")
            .map(|v| {
                if v.len() >= 6 {
                    Matrix::new(v[0], v[1], v[2], v[3], v[4], v[5])
                } else {
                    Matrix::identity()
                }
            })
            .unwrap_or_else(Matrix::identity);

        // Render the shading into a temporary display list with pattern matrix
        // applied to the CTM so coordinates are in device space.
        // Use content_stream_ctm so that patterns inside Form XObjects include
        // the form's coordinate transform.
        //
        // Clear overprint while building the shading display list. The pattern
        // is resolved at `scn`/`SCN` time, but overprint should come from the
        // graphics state at paint time (when Tj/f/S executes). Capturing the
        // resolution-time overprint bakes a stale flag into the shading elements
        // — if the caller applies a different ExtGState between `scn` and the
        // paint operator, the shading would carry the wrong overprint state.
        // Setting overprint=false here is safe because paint-time code wraps
        // shading patterns in isolated groups, so overprint compositing does
        // not cross the group boundary.
        let combined_matrix = self.content_stream_ctm.concat(&pattern_matrix);
        let saved_ctm = self.gstate.ctm;
        let saved_overprint = self.gstate.overprint;
        let saved_overprint_stroke = self.gstate.overprint_stroke;
        self.gstate.ctm = combined_matrix;
        self.gstate.overprint = false;
        self.gstate.overprint_stroke = false;

        let mut shading_dl = DisplayList::new();
        let result = crate::resources::shading::handle_shading(
            &sh_ref_clone,
            sh_dict,
            &self.gstate,
            self.resolver,
            &mut shading_dl,
            &mut self.icc_cache,
        );
        self.gstate.ctm = saved_ctm;
        self.gstate.overprint = saved_overprint;
        self.gstate.overprint_stroke = saved_overprint_stroke;
        result?;
        Ok(shading_dl)
    }
}

/// Test whether two `[xmin, ymin, xmax, ymax]` rectangles overlap by at
/// least `min_extent` device units in BOTH dimensions. The `[f64; 4]`
/// slots are accepted in either ordering (we min/max the pair of x and y
/// components before testing).
///
/// Used by `flush_soft_mask` to discriminate "mask form is meaningfully
/// covering the content" (≥ min_extent in both axes) from "mask form is
/// only edge-touching the content" (< min_extent in at least one axis).
/// The latter case is treated as a no-op mask, matching the historical
/// Ghostscript behavior on PDFs like 5795.pdf where the mask form lives
/// in off-page coordinates and barely grazes the visible content.
fn bboxes_overlap_substantially(a: &[f64; 4], b: &[f64; 4], min_extent: f64) -> bool {
    let (ax0, ay0, ax1, ay1) = (
        a[0].min(a[2]),
        a[1].min(a[3]),
        a[0].max(a[2]),
        a[1].max(a[3]),
    );
    let (bx0, by0, bx1, by1) = (
        b[0].min(b[2]),
        b[1].min(b[3]),
        b[0].max(b[2]),
        b[1].max(b[3]),
    );
    let overlap_w = (ax1.min(bx1) - ax0.max(bx0)).max(0.0);
    let overlap_h = (ay1.min(by1) - ay0.max(by0)).max(0.0);
    overlap_w >= min_extent && overlap_h >= min_extent
}

fn path_device_bbox(path: &PsPath) -> [f64; 4] {
    let mut x_min = f64::INFINITY;
    let mut y_min = f64::INFINITY;
    let mut x_max = f64::NEG_INFINITY;
    let mut y_max = f64::NEG_INFINITY;
    let mut update = |x: f64, y: f64| {
        x_min = x_min.min(x);
        y_min = y_min.min(y);
        x_max = x_max.max(x);
        y_max = y_max.max(y);
    };
    for seg in &path.segments {
        match seg {
            PathSegment::MoveTo(x, y) | PathSegment::LineTo(x, y) => update(*x, *y),
            PathSegment::CurveTo {
                x1,
                y1,
                x2,
                y2,
                x3,
                y3,
            } => {
                update(*x1, *y1);
                update(*x2, *y2);
                update(*x3, *y3);
            }
            PathSegment::ClosePath => {}
        }
    }
    [x_min, y_min, x_max, y_max]
}

/// Convert a color space name to a ColorSpaceRef.
fn name_to_cs_ref(name: &[u8]) -> ColorSpaceRef {
    match name {
        b"DeviceGray" | b"G" => ColorSpaceRef::DeviceGray,
        b"DeviceRGB" | b"RGB" => ColorSpaceRef::DeviceRGB,
        b"DeviceCMYK" | b"CMYK" => ColorSpaceRef::DeviceCMYK,
        _ => ColorSpaceRef::Named(name.to_vec()),
    }
}

/// Expand abbreviated inline image key names.
fn expand_inline_key(key: &[u8]) -> Vec<u8> {
    match key {
        b"BPC" => b"BitsPerComponent".to_vec(),
        b"CS" => b"ColorSpace".to_vec(),
        b"D" => b"Decode".to_vec(),
        b"DP" => b"DecodeParms".to_vec(),
        b"F" => b"Filter".to_vec(),
        b"H" => b"Height".to_vec(),
        b"IM" => b"ImageMask".to_vec(),
        b"I" => b"Interpolate".to_vec(),
        b"W" => b"Width".to_vec(),
        _ => key.to_vec(),
    }
}

/// Expand abbreviated inline image value names.
fn expand_inline_value(name: &[u8]) -> Vec<u8> {
    match name {
        b"G" => b"DeviceGray".to_vec(),
        b"RGB" => b"DeviceRGB".to_vec(),
        b"CMYK" => b"DeviceCMYK".to_vec(),
        b"I" => b"Indexed".to_vec(),
        b"AHx" => b"ASCIIHexDecode".to_vec(),
        b"A85" => b"ASCII85Decode".to_vec(),
        b"LZW" => b"LZWDecode".to_vec(),
        b"Fl" => b"FlateDecode".to_vec(),
        b"RL" => b"RunLengthDecode".to_vec(),
        b"CCF" => b"CCITTFaxDecode".to_vec(),
        b"DCT" => b"DCTDecode".to_vec(),
        _ => name.to_vec(),
    }
}

/// Bilinear upsample of image data to target dimensions.
/// Used when an explicit mask is higher resolution than the image (MRC PDFs).
fn bilinear_upsample_image(
    data: &[u8],
    sw: u32,
    sh: u32,
    dw: u32,
    dh: u32,
    cs: &ImageColorSpace,
) -> Vec<u8> {
    let n = cs.num_components() as usize;
    if n == 0 || sw == 0 || sh == 0 || dw == 0 || dh == 0 {
        return data.to_vec();
    }
    let src_stride = sw as usize * n;
    let dst_stride = dw as usize * n;
    let mut out = vec![0u8; dst_stride * dh as usize];

    for dy in 0..dh as usize {
        let sy = (dy as f32 + 0.5) * sh as f32 / dh as f32 - 0.5;
        let sy0 = (sy.floor() as i32).clamp(0, sh as i32 - 1) as usize;
        let sy1 = (sy0 + 1).min(sh as usize - 1);
        let fy = sy - sy0 as f32;

        for dx in 0..dw as usize {
            let sx = (dx as f32 + 0.5) * sw as f32 / dw as f32 - 0.5;
            let sx0 = (sx.floor() as i32).clamp(0, sw as i32 - 1) as usize;
            let sx1 = (sx0 + 1).min(sw as usize - 1);
            let fx = sx - sx0 as f32;

            let w00 = (1.0 - fx) * (1.0 - fy);
            let w10 = fx * (1.0 - fy);
            let w01 = (1.0 - fx) * fy;
            let w11 = fx * fy;

            let i00 = sy0 * src_stride + sx0 * n;
            let i10 = sy0 * src_stride + sx1 * n;
            let i01 = sy1 * src_stride + sx0 * n;
            let i11 = sy1 * src_stride + sx1 * n;

            let di = dy * dst_stride + dx * n;
            for c in 0..n {
                let v = data[i00 + c] as f32 * w00
                    + data[i10 + c] as f32 * w10
                    + data[i01 + c] as f32 * w01
                    + data[i11 + c] as f32 * w11;
                out[di + c] = (v + 0.5).clamp(0.0, 255.0) as u8;
            }
        }
    }
    out
}

/// Expand image sample data from arbitrary BPC to 8-bit.
/// Merge image sample data with an SMask alpha channel into RGBA.
fn merge_rgb_with_smask(
    image_data: &[u8],
    smask_data: &[u8],
    color_space: &ImageColorSpace,
    width: u32,
    height: u32,
    icc: Option<&stet_graphics::icc::IccCache>,
) -> Vec<u8> {
    // For Indexed images, expand palette indices to RGB first
    if let ImageColorSpace::Indexed {
        base,
        hival,
        lookup,
    } = color_space
    {
        let n_base = base.num_components() as usize;
        let n_pixels = (width * height) as usize;
        let mut expanded = vec![0u8; n_pixels.saturating_mul(n_base)];
        for i in 0..n_pixels {
            let idx = image_data.get(i).copied().unwrap_or(0) as usize;
            let idx = idx.min(*hival as usize);
            let offset = idx * n_base;
            for c in 0..n_base {
                expanded[i * n_base + c] = lookup.get(offset + c).copied().unwrap_or(0);
            }
        }
        return merge_rgb_with_smask(&expanded, smask_data, base, width, height, icc);
    }

    // For Separation/DeviceN, convert through tint table to alternate space first
    if let ImageColorSpace::Separation {
        alt_space,
        tint_table,
        ..
    } = color_space
    {
        let n_pixels = (width * height) as usize;
        let no = tint_table.num_outputs as usize;
        let mut expanded = vec![0u8; n_pixels.saturating_mul(no)];
        let mut alt_comps = vec![0.0f32; no];
        for i in 0..n_pixels {
            let tint = image_data.get(i).copied().unwrap_or(0) as f32 / 255.0;
            tint_table.lookup_1d(tint, &mut alt_comps);
            for c in 0..no {
                expanded[i * no + c] = (alt_comps[c].clamp(0.0, 1.0) * 255.0 + 0.5) as u8;
            }
        }
        return merge_rgb_with_smask(&expanded, smask_data, alt_space, width, height, icc);
    }
    if let ImageColorSpace::DeviceN {
        alt_space,
        tint_table,
        ..
    } = color_space
    {
        let ni = tint_table.num_inputs as usize;
        let no = tint_table.num_outputs as usize;
        let n_pixels = (width * height) as usize;
        let mut expanded = vec![0u8; n_pixels.saturating_mul(no)];
        let mut inputs = vec![0.0f32; ni];
        let mut alt_comps = vec![0.0f32; no];
        for i in 0..n_pixels {
            let si = i * ni;
            for (c, inp) in inputs.iter_mut().enumerate() {
                *inp = image_data.get(si + c).copied().unwrap_or(0) as f32 / 255.0;
            }
            tint_table.lookup_nd(&inputs, &mut alt_comps);
            for c in 0..no {
                expanded[i * no + c] = (alt_comps[c].clamp(0.0, 1.0) * 255.0 + 0.5) as u8;
            }
        }
        return merge_rgb_with_smask(&expanded, smask_data, alt_space, width, height, icc);
    }

    let n_pixels = (width * height) as usize;
    let mut rgba = vec![255u8; n_pixels * 4];
    let n_comps = color_space.num_components();

    // For CMYK data, try ICC bulk conversion first (matches samples_to_rgba quality)
    if n_comps == 4 {
        if let Some(cache) = icc {
            if let Some(cmyk_hash) = cache.default_cmyk_hash() {
                let cmyk_data = if image_data.len() >= n_pixels * 4 {
                    &image_data[..n_pixels * 4]
                } else {
                    image_data
                };
                if let Some(rgb) = cache.convert_image_8bit(cmyk_hash, cmyk_data, n_pixels) {
                    for i in 0..n_pixels {
                        let alpha = smask_data.get(i).copied().unwrap_or(255);
                        let dst = i * 4;
                        let (r, g, b) = (rgb[i * 3], rgb[i * 3 + 1], rgb[i * 3 + 2]);
                        if alpha == 255 {
                            rgba[dst] = r;
                            rgba[dst + 1] = g;
                            rgba[dst + 2] = b;
                            rgba[dst + 3] = 255;
                        } else if alpha == 0 {
                            // rgba already zeroed by default 255, need to zero
                            rgba[dst] = 0;
                            rgba[dst + 1] = 0;
                            rgba[dst + 2] = 0;
                            rgba[dst + 3] = 0;
                        } else {
                            let a = alpha as u16;
                            rgba[dst] = ((r as u16 * a + 127) / 255) as u8;
                            rgba[dst + 1] = ((g as u16 * a + 127) / 255) as u8;
                            rgba[dst + 2] = ((b as u16 * a + 127) / 255) as u8;
                            rgba[dst + 3] = alpha;
                        }
                    }
                    return rgba;
                }
            }
        }
    }

    for i in 0..n_pixels {
        let alpha = smask_data.get(i).copied().unwrap_or(255);
        let dst = i * 4;
        match n_comps {
            3 => {
                // RGB
                let src = i * 3;
                rgba[dst] = image_data.get(src).copied().unwrap_or(0);
                rgba[dst + 1] = image_data.get(src + 1).copied().unwrap_or(0);
                rgba[dst + 2] = image_data.get(src + 2).copied().unwrap_or(0);
            }
            1 => {
                // Gray
                let g = image_data.get(i).copied().unwrap_or(0);
                rgba[dst] = g;
                rgba[dst + 1] = g;
                rgba[dst + 2] = g;
            }
            4 => {
                // CMYK → RGB (PLRM fallback when ICC not available)
                let src = i * 4;
                let c = image_data.get(src).copied().unwrap_or(0) as f64 / 255.0;
                let m = image_data.get(src + 1).copied().unwrap_or(0) as f64 / 255.0;
                let y = image_data.get(src + 2).copied().unwrap_or(0) as f64 / 255.0;
                let k = image_data.get(src + 3).copied().unwrap_or(0) as f64 / 255.0;
                rgba[dst] = ((1.0 - c) * (1.0 - k) * 255.0 + 0.5) as u8;
                rgba[dst + 1] = ((1.0 - m) * (1.0 - k) * 255.0 + 0.5) as u8;
                rgba[dst + 2] = ((1.0 - y) * (1.0 - k) * 255.0 + 0.5) as u8;
            }
            _ => {
                // Unknown — treat as black
            }
        }
        // Premultiply alpha (tiny-skia expects premultiplied RGBA)
        if alpha == 255 {
            rgba[dst + 3] = 255;
        } else if alpha == 0 {
            rgba[dst] = 0;
            rgba[dst + 1] = 0;
            rgba[dst + 2] = 0;
            rgba[dst + 3] = 0;
        } else {
            let a = alpha as u16;
            rgba[dst] = ((rgba[dst] as u16 * a + 127) / 255) as u8;
            rgba[dst + 1] = ((rgba[dst + 1] as u16 * a + 127) / 255) as u8;
            rgba[dst + 2] = ((rgba[dst + 2] as u16 * a + 127) / 255) as u8;
            rgba[dst + 3] = alpha;
        }
    }
    rgba
}

fn expand_bits_to_bytes(
    data: &[u8],
    bpc: u32,
    width: u32,
    height: u32,
    components: u32,
    is_indexed: bool,
) -> Vec<u8> {
    if bpc == 0 || bpc == 8 {
        return data.to_vec();
    }

    // `bpc` is validated at every image entry point, but this is a free
    // function that could be reached from a future caller: a shift of 32 or
    // more is a panic in debug builds and a masked no-op in release.
    if bpc >= 32 {
        return Vec::new();
    }
    let max_val = ((1u32 << bpc) - 1) as f64;
    let samples_per_row = width * components.max(1);
    // Reserve in `usize`, not `u32`: the three-way product overflows a `u32`
    // well before the two-way `width * height` does, and a wrapped capacity
    // silently under-reserves rather than failing.
    let capacity = (width as usize)
        .saturating_mul(height as usize)
        .saturating_mul(components.max(1) as usize);
    let mut result = Vec::with_capacity(capacity);

    for row in 0..height {
        let row_bit_offset = row as usize * ((samples_per_row * bpc).div_ceil(8) * 8) as usize;
        for col in 0..samples_per_row {
            let bit_offset = row_bit_offset + (col * bpc) as usize;
            let byte_offset = bit_offset / 8;
            let bit_shift = bit_offset % 8;

            if byte_offset >= data.len() {
                result.push(0);
                continue;
            }

            // Extract bpc bits
            let mut val = 0u32;
            let mut bits_remaining = bpc;
            let mut cur_byte = byte_offset;
            let mut cur_bit = bit_shift;

            while bits_remaining > 0 && cur_byte < data.len() {
                let available = 8 - cur_bit as u32;
                let take = bits_remaining.min(available);
                let shift = available - take;
                let mask = ((1u32 << take) - 1) << shift;
                val = (val << take) | ((data[cur_byte] as u32 & mask) >> shift);
                bits_remaining -= take;
                cur_bit = 0;
                cur_byte += 1;
            }

            // For Indexed color spaces, values are palette indices — keep raw.
            // For other color spaces, scale to 0-255.
            if is_indexed {
                result.push(val as u8);
            } else {
                result.push((val as f64 / max_val * 255.0 + 0.5) as u8);
            }
        }
    }

    result
}

/// Convert a PDF blend mode name to a numeric code.
fn blend_mode_from_name(name: &[u8]) -> u8 {
    match name {
        b"Normal" | b"Compatible" => 0,
        b"Multiply" => 1,
        b"Screen" => 2,
        b"Overlay" => 3,
        b"Darken" => 4,
        b"Lighten" => 5,
        b"ColorDodge" => 6,
        b"ColorBurn" => 7,
        b"HardLight" => 8,
        b"SoftLight" => 9,
        b"Difference" => 10,
        b"Exclusion" => 11,
        b"Hue" => 12,
        b"Saturation" => 13,
        b"Color" => 14,
        b"Luminosity" => 15,
        _ => 0,
    }
}

fn is_whitespace_byte(b: u8) -> bool {
    matches!(b, b' ' | b'\t' | b'\r' | b'\n' | 0x0C | 0x00)
}

fn is_delimiter_or_ws(b: u8) -> bool {
    is_whitespace_byte(b)
        || matches!(
            b,
            b'(' | b')' | b'<' | b'>' | b'[' | b']' | b'{' | b'}' | b'/' | b'%'
        )
}

/// Evaluate a PDF function at 256 evenly-spaced points in [0,1] to build a transfer table.
fn sample_transfer_function(func: &crate::resources::function::PdfFunction) -> Vec<f64> {
    (0..256)
        .map(|i| {
            let t = i as f64 / 255.0;
            let result = func.evaluate(&[t]);
            result.first().copied().unwrap_or(t).clamp(0.0, 1.0)
        })
        .collect()
}

/// Apply transfer functions to RGB image pixel data (in-place).
///
/// `data` is interleaved RGB (3 bytes per pixel) or RGBA (4 bytes per pixel).
/// Transfer tables are 256-sample [0,1]→[0,1] lookup tables.
fn apply_transfer_to_image(
    data: &mut [u8],
    transfer: &stet_graphics::device::TransferState,
    components: usize,
) {
    // Build 256-entry u8 lookup tables for each RGB channel
    let (r_table, g_table, b_table) = if let Some(ref color) = transfer.color {
        // Per-component transfer: [R, G, B, Gray]
        let r = build_u8_lut(color[0].as_ref().map(|v| &v[..]));
        let g = build_u8_lut(color[1].as_ref().map(|v| &v[..]));
        let b = build_u8_lut(color[2].as_ref().map(|v| &v[..]));
        (r, g, b)
    } else if let Some(ref gray) = transfer.gray {
        // Single function applied to all channels
        let lut = build_u8_lut(Some(&gray[..]));
        (lut, lut, lut)
    } else {
        return; // Identity — nothing to do
    };

    // Apply LUT per channel
    let stride = components;
    for pixel in data.chunks_exact_mut(stride) {
        if pixel.len() >= 3 {
            pixel[0] = r_table[pixel[0] as usize];
            pixel[1] = g_table[pixel[1] as usize];
            pixel[2] = b_table[pixel[2] as usize];
        }
    }
}

/// Apply transfer functions to a DeviceColor (fill/stroke).
fn apply_transfer_to_color(
    color: &DeviceColor,
    transfer: &stet_graphics::device::TransferState,
) -> DeviceColor {
    if let Some(ref color_tables) = transfer.color {
        // Per-component transfer: [R, G, B, Gray]
        let r = apply_transfer_component(color.r, color_tables[0].as_ref().map(|v| &v[..]));
        let g = apply_transfer_component(color.g, color_tables[1].as_ref().map(|v| &v[..]));
        let b = apply_transfer_component(color.b, color_tables[2].as_ref().map(|v| &v[..]));
        DeviceColor::from_rgb(r, g, b)
    } else if let Some(ref gray) = transfer.gray {
        let r = apply_transfer_component(color.r, Some(&gray[..]));
        let g = apply_transfer_component(color.g, Some(&gray[..]));
        let b = apply_transfer_component(color.b, Some(&gray[..]));
        DeviceColor::from_rgb(r, g, b)
    } else {
        color.clone()
    }
}

/// Look up a single f64 component [0,1] through a transfer table.
fn apply_transfer_component(value: f64, table: Option<&[f64]>) -> f64 {
    match table {
        None => value,
        Some(t) if t.len() != 256 => value,
        Some(t) => {
            let idx = (value * 255.0).clamp(0.0, 255.0);
            let lo = idx.floor() as usize;
            let hi = (lo + 1).min(255);
            let frac = idx - lo as f64;
            let v0 = t[lo];
            let v1 = t[hi];
            (v0 + frac * (v1 - v0)).clamp(0.0, 1.0)
        }
    }
}

/// Build a 256-entry u8 lookup table from a transfer table.
fn build_u8_lut(table: Option<&[f64]>) -> [u8; 256] {
    let mut lut = [0u8; 256];
    match table {
        Some(t) if t.len() == 256 => {
            for (i, v) in lut.iter_mut().enumerate() {
                *v = (t[i].clamp(0.0, 1.0) * 255.0 + 0.5) as u8;
            }
        }
        _ => {
            for (i, v) in lut.iter_mut().enumerate() {
                *v = i as u8;
            }
        }
    }
    lut
}