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
//! The content-stream interpreter: the PDF graphics-state machine.
//!
//! Drives the [`crate::content::tokenizer::ContentLexer`] over a page's decoded content
//! bytes, maintaining the graphics-state stack and text/path state, and emits
//! a [`SemanticPage`]. No raster backend is involved and no document state is
//! mutated — every scratch value is owned here, reading only the immutable
//! [`DocumentSnapshot`].
use std::collections::HashMap;
use std::sync::Arc;
use crate::document::{DocumentSnapshot, ParseContext};
use crate::object::{Dictionary, NameId, NameTable, ObjectId, PdfObject, PdfStream, StreamData};
use crate::page_ir::{
BlendMode, FillRule, ImageColorSpace, ImageSMask, LineCap, LineJoin, MaskKind, Matrix,
PageBounds, PaintOrigin, PathData, PathVerb, Point, Rect,
};
use crate::content::marked::MarkedContentSpan;
use crate::content::semantic::{
ActualTextSpan, ActualTextSpanId, FontId, ImageId, PathId, SemColor, SemFont, SemImage,
SemShading, SemShadingKind, SemTiling, SemanticOp, SemanticPage, ShadingId, TextElement,
TextRun, TextRunId, TilingId,
};
use crate::content::state::{ColorSpace, GraphicsState, PathBuilder};
use crate::content::tokenizer::{ContentLexer, Lexeme, Operand};
use crate::content::trace::{
ContentSegment, OpTrace, PageTrace, TraceCurrent, TraceFrame, TraceFrameKind,
};
use crate::content::{ContentError, ContentLimits};
/// A hard cap on the operand stack to bound a malformed stream that never
/// applies an operator.
const MAX_OPERAND_STACK: usize = 1 << 16;
/// Names with a meaning inside an inline image's parameters (ISO 32000-1
/// Tables 92-94 and the filter, colour-space and decode-parameter names an
/// image XObject accepts). Only these, plus names already interned, get
/// their own name-table entry from inline-image operands (B15).
#[rustfmt::skip]
const INLINE_SPEC_NAMES: &[&[u8]] = &[
// Keys (full and abbreviated).
b"BitsPerComponent", b"BPC", b"ColorSpace", b"CS", b"Decode", b"D",
b"DecodeParms", b"DP", b"Filter", b"F", b"Height", b"H", b"ImageMask",
b"IM", b"Interpolate", b"I", b"Width", b"W", b"Intent", b"Length", b"L",
b"Mask",
// Colour spaces (full and abbreviated).
b"DeviceGray", b"G", b"DeviceRGB", b"RGB", b"DeviceCMYK", b"CMYK",
b"Indexed", b"CalGray", b"CalRGB", b"Lab", b"ICCBased", b"Separation",
b"DeviceN", b"Pattern", b"All", b"None",
// Filters (full and abbreviated).
b"ASCIIHexDecode", b"AHx", b"ASCII85Decode", b"A85", b"LZWDecode",
b"LZW", b"FlateDecode", b"Fl", b"RunLengthDecode", b"RL",
b"CCITTFaxDecode", b"CCF", b"DCTDecode", b"DCT", b"JBIG2Decode",
b"JPXDecode", b"Crypt",
// Decode-parameter keys.
b"Predictor", b"Colors", b"Columns", b"EarlyChange", b"K", b"EndOfLine",
b"EncodedByteAlign", b"Rows", b"EndOfBlock", b"BlackIs1",
b"DamagedRowsBeforeError", b"ColorTransform",
// Rendering intents.
b"AbsoluteColorimetric", b"RelativeColorimetric", b"Saturation",
b"Perceptual",
];
/// The placeholder every other inline-image name maps to. A parsed PDF name
/// cannot contain a NUL byte, so it never equals a real key or family name.
const UNKNOWN_INLINE_NAME: &[u8] = b"\0exprim-unknown-inline-name";
/// A hard cap on a Type 0 sampled function's total sample count (`size *
/// n_out`), bounding allocation from an absurd `/Size` (malformed-resource
/// guard). Shadings need only modest resolution.
const MAX_SAMPLED_FN: usize = 1 << 24;
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum MarkupKind {
Highlight,
Underline,
Squiggly,
StrikeOut,
}
fn append_markup_geometry(builder: &mut PathBuilder, quad: [f64; 8], kind: MarkupKind) {
if !quad.iter().all(|value| value.is_finite()) {
return;
}
let points = [
[quad[0], quad[1]],
[quad[2], quad[3]],
[quad[4], quad[5]],
[quad[6], quad[7]],
];
if matches!(kind, MarkupKind::Highlight) {
append_polygon(builder, &[points[0], points[1], points[3], points[2]]);
return;
}
let distance = |a: [f64; 2], b: [f64; 2]| (b[0] - a[0]).hypot(b[1] - a[1]);
let height = (distance(points[0], points[2]) + distance(points[1], points[3])) * 0.5;
let length = distance(points[2], points[3]);
if height <= 1e-6 || length <= 1e-6 {
return;
}
let bottom_mid = [
(points[2][0] + points[3][0]) * 0.5,
(points[2][1] + points[3][1]) * 0.5,
];
let top_mid = [
(points[0][0] + points[1][0]) * 0.5,
(points[0][1] + points[1][1]) * 0.5,
];
let inward_len = distance(bottom_mid, top_mid);
if inward_len <= 1e-6 {
return;
}
let inward = [
(top_mid[0] - bottom_mid[0]) / inward_len,
(top_mid[1] - bottom_mid[1]) / inward_len,
];
let thickness = (height / 14.0).clamp(0.5, height / 3.0);
match kind {
MarkupKind::Underline => {
let offset = thickness;
append_strip(
builder,
add_scaled(points[2], inward, offset),
add_scaled(points[3], inward, offset),
inward,
thickness,
);
}
MarkupKind::StrikeOut => {
append_strip(
builder,
[
(points[0][0] + points[2][0]) * 0.5,
(points[0][1] + points[2][1]) * 0.5,
],
[
(points[1][0] + points[3][0]) * 0.5,
(points[1][1] + points[3][1]) * 0.5,
],
inward,
thickness,
);
}
MarkupKind::Squiggly => {
let amplitude = (height * 0.09).max(thickness);
let baseline = amplitude + thickness;
let steps = ((length / (amplitude * 1.5)).ceil() as usize).clamp(4, 256);
let mut centers = Vec::with_capacity(steps + 1);
for index in 0..=steps {
let t = index as f64 / steps as f64;
let mut center = [
points[2][0] + (points[3][0] - points[2][0]) * t,
points[2][1] + (points[3][1] - points[2][1]) * t,
];
let wave = if index % 2 == 0 { -0.5 } else { 0.5 };
center = add_scaled(center, inward, baseline + wave * amplitude);
centers.push(center);
}
let mut polygon = Vec::with_capacity(centers.len() * 2);
polygon.extend(
centers
.iter()
.copied()
.map(|point| add_scaled(point, inward, thickness * 0.5)),
);
polygon.extend(
centers
.iter()
.rev()
.copied()
.map(|point| add_scaled(point, inward, -thickness * 0.5)),
);
append_polygon(builder, &polygon);
}
MarkupKind::Highlight => {}
}
}
fn add_scaled(point: [f64; 2], vector: [f64; 2], scale: f64) -> [f64; 2] {
[point[0] + vector[0] * scale, point[1] + vector[1] * scale]
}
fn append_strip(
builder: &mut PathBuilder,
start: [f64; 2],
end: [f64; 2],
normal: [f64; 2],
thickness: f64,
) {
let half = thickness * 0.5;
append_polygon(
builder,
&[
add_scaled(start, normal, half),
add_scaled(end, normal, half),
add_scaled(end, normal, -half),
add_scaled(start, normal, -half),
],
);
}
fn append_polygon(builder: &mut PathBuilder, points: &[[f64; 2]]) {
let Some(first) = points.first() else {
return;
};
builder.move_to(first[0], first[1]);
for point in &points[1..] {
builder.line_to(point[0], point[1]);
}
builder.close();
}
#[derive(Debug, Clone)]
struct MarkedContentFrame {
hidden: bool,
actual_text: Option<ActualTextSpan>,
}
/// A `BMC`/`BDC` span opened while [`Interpreter::record_marked`] is set,
/// still awaiting its `EMC`.
#[derive(Debug, Clone)]
struct OpenMarkedSpan {
/// Tag name, or `None` when the opening operator carried no name
/// operand (malformed; the span still nests for pairing purposes but is
/// dropped rather than reported).
tag: Option<String>,
open_offset: usize,
bbox: Option<Rect>,
}
/// One page-compilation job's mutable state. Owned, never shared.
pub(crate) struct Interpreter<'a> {
snapshot: &'a DocumentSnapshot,
ctx: &'a mut ParseContext,
names: &'a NameTable,
limits: &'a ContentLimits,
/// The active resource dictionary (page-level, or a form's while nested).
resources: Option<Arc<PdfObject>>,
/// Optional installed-font source for non-embedded fonts (Font Phase 7).
system_fonts: Option<Arc<dyn crate::font::SystemFontProvider>>,
/// The page-level `/Resources`, kept for the whole interpretation. A form,
/// pattern or CharProc whose own `/Resources` omits a whole category falls
/// back to these — see [`Self::resource_subdict`].
page_resources: Option<Arc<PdfObject>>,
// --- output accumulators ---
ops: Vec<SemanticOp>,
paths: Vec<PathData>,
text_runs: Vec<TextRun>,
images: Vec<SemImage>,
fonts: Vec<SemFont>,
font_cache: HashMap<NameId, FontId>,
/// Document-scoped resolved-font cache (see [`FontResourceCache`]).
font_resources: Arc<FontResourceCache>,
shadings: Vec<SemShading>,
tilings: Vec<SemTiling>,
/// Resolved pattern resources, keyed by resource name, so a pattern used
/// on many draws is compiled once.
pattern_cache: HashMap<NameId, Option<SemColor>>,
/// An uncoloured (`PaintType 2`) tiling pattern used with a further
/// underlying colour: (resource name, RGBA bits) → the tiling entry that
/// shares the first use's compiled cell under that colour. The colour is
/// part of the tiling entry, so `pattern_cache` alone would paint every
/// later use in the first use's colour.
uncolored_tiling_cache: HashMap<(NameId, [u32; 4]), TilingId>,
/// Resolved `/Separation` and `/DeviceN` spaces, keyed by resource name.
/// Their tint transform is a PDF function that must be evaluated per
/// colour, so it is parsed once and reused (a page typically sets the
/// same separation thousands of times).
tint_cache: HashMap<NameId, Option<Arc<TintSpace>>>,
/// Resolved `/Type3` fonts, keyed by resource name (mirrors `tint_cache`).
/// A Type 3 font's glyphs are content streams (`/CharProcs`) executed
/// inline at show time; the FontMatrix, encoding, widths and CharProc
/// streams are parsed once and reused for every glyph the page draws.
type3_cache: HashMap<NameId, Option<Arc<Type3Font>>>,
/// Resolved CIE-based spaces (`/Lab`, `/CalRGB`, `/CalGray`), keyed by
/// resource name (mirrors `tint_cache`). Their parameters are read once;
/// conversion itself is pure math in `exprim::color`.
cie_cache: HashMap<NameId, Option<CieSpace>>,
/// `sc`/`scn` in a resource-named space: whether the space is `/Indexed`,
/// and its palette-carrying form if so (see
/// [`Self::resolve_named_indexed`]), keyed by resource name.
indexed_cache: HashMap<NameId, Option<crate::page_ir::ImageColorSpace>>,
/// Marked-content nesting (`BMC`/`BDC`…`EMC`): `true` for levels opened
/// by a `/OC` `BDC` whose optional-content group is OFF (ISO 32000-1
/// §8.11.3.2; cpdf_occontext.cpp default-visibility semantics).
mc_stack: Vec<MarkedContentFrame>,
mc_stack_floor: usize,
next_actual_text_span: u32,
/// How many enclosing marked-content levels are OC-hidden. While > 0,
/// painting is suppressed (state, clipping, and text advances still
/// apply — hiding content must not shift what follows it).
oc_hidden_count: u32,
/// Record every page-level `BMC`/`BDC`…`EMC` span into
/// [`Self::marked_spans`]. Off unless the marked-content accessor asked
/// for it, so default compilation neither pays for nor observes the
/// inventory.
record_marked: bool,
/// Spans opened at the page level and not yet closed.
marked_open: Vec<OpenMarkedSpan>,
/// Closed spans, in close order (re-sorted to document order on take).
marked_spans: Vec<MarkedContentSpan>,
/// Set by [`Self::build_tint_image_lut`] when it had to repair a
/// degenerate baked tint ramp (PLAN-POST-SWEEP3 §R1); cleared and read by
/// the image builders so the flag lands on the right [`SemImage`].
image_cs_degraded: bool,
/// Record a [`PageTrace`] alongside `ops`. Off unless the audit entry
/// point asked for it, so default compilation neither pays for nor
/// observes the trace (mirrors `record_marked`).
record_trace: bool,
/// Trace entries, index-aligned with `ops`. Empty unless `record_trace`.
trace: Vec<OpTrace>,
/// Page-level `/Contents` segment map (see [`gather_content_mapped`]).
/// Meaningful only for the page content run; nested streams are single
/// streams whose offsets are already stream-relative.
trace_segments: Vec<ContentSegment>,
/// Source stream object of the nested content stream currently being
/// interpreted. `None` at the page level (where [`Self::trace_segments`]
/// resolves the stream per operator) and for direct streams.
trace_stream: Option<ObjectId>,
/// Nested-object stack of the currently executing content stream,
/// outermost first. Empty at the page level.
trace_stack: Vec<TraceFrame>,
/// A pattern/shading resource resolved while producing the *next*
/// emitted op, appended to that op's stack by [`Self::emit`]. Set
/// immediately before the emission it belongs to; never survives it.
trace_extra: Option<TraceFrame>,
/// Content-operator execution sequence (trace only): incremented for
/// every operator keyword and inline image, in execution order, across
/// the page and all nested streams. Separate from `ops_executed` so the
/// operator budget's semantics stay untouched.
trace_seq: u64,
/// Provenance of the content operator currently being dispatched, or
/// `None` when the next emission is synthesized (outside any operator).
/// Saved across nested runs and cleared when each `run` returns.
trace_current: Option<TraceCurrent>,
// --- interpreter state ---
gs: GraphicsState,
gs_stack: Vec<GraphicsState>,
/// Lowest graphics-state stack depth the current nested content stream may
/// pop to. Form-like streams are implicitly isolated even when malformed:
/// an unmatched `Q` inside a CharProc must not consume its caller's save.
gs_stack_floor: usize,
path: PathBuilder,
pending_clip: Option<FillRule>,
text: TextObjectState,
operands: Vec<Operand>,
ops_executed: u64,
invoke_depth: u32,
/// The CTM at entry of the content stream currently being interpreted —
/// its *default user space* in page-space units. Pattern space anchors
/// here (ISO 32000-1 §8.7.3.1: a pattern's `/Matrix` maps pattern space to
/// the default space of the stream in which the pattern is *referenced* —
/// the page, or a form/mask-group's space when invoked under a CTM).
/// Identity for page content; saved/set around each form-content
/// invocation, alongside the resource-cache swap that keeps per-stream
/// pattern resolutions from leaking across anchor changes.
pattern_base: Matrix,
/// Object ids of forms currently on the invocation stack — precise cycle
/// detection for self- or mutually-recursive XObjects.
form_stack: Vec<ObjectId>,
/// Object ids of the soft-mask groups currently being resolved, for
/// recursion detection: a mask group whose content references itself (via
/// an ExtGState `/SMask` naming the same group) is rendered *empty* at the
/// recursive instance (§11.6.5.2 — an empty luminosity group is 0, fully
/// masked), matching MuPDF, rather than recursing to the depth limit.
soft_mask_stack: Vec<ObjectId>,
/// Nesting depth of Type 3 CharProc execution. `d0`/`d1` glyph-metric
/// operators only carry meaning inside a CharProc, so they are honoured
/// only while this is non-zero (a stray `d1` on a page must not silently
/// suppress the page's colours).
type3_nesting: u32,
/// A `d1` CharProc is a shape-only (stencil) glyph: colour-setting
/// operators inside it are ignored so it paints with the fill colour in
/// effect at show time (ISO 32000-1 §9.6.5.1). Scoped per CharProc.
type3_shape_only: bool,
/// The `wx` from the CharProc's leading `d0`/`d1`, captured as an advance
/// fallback for a Type 3 font that supplies no `/Widths`.
type3_d_width: Option<f64>,
/// The page referenced an `/ICCBased` colour space anywhere (fill,
/// stroke, or image). Feeds `PageFeatures::ICC_COLOR` — a *flag*, not a
/// CMM: unsupported profile shapes keep the documented arity
/// approximation, while supported RGB and CMYK image transforms are
/// carried explicitly.
uses_icc_color: bool,
/// Parsed `/ICCBased` profiles by stream object. `None` means "parsed, and
/// there is nothing to apply" (an sRGB or out-of-scope profile), which is
/// worth caching too — a document points every image at the same profile.
icc_cache: HashMap<ObjectId, Option<Arc<crate::color::icc::IccRgb>>>,
/// Parsed `/ICCBased` **CMYK** press profiles by stream object (the
/// device-CMYK counterpart of `icc_cache`). `None` caches a stream that is
/// not a 4-input Lab-PCS lut. Used to convert DeviceCMYK content — both an
/// explicit ICCBased colour space and a `/DefaultCMYK` redirect — the way
/// PDFium routes it through LittleCMS.
icc_cmyk_cache: HashMap<ObjectId, Option<Arc<crate::color::icc::IccCmyk>>>,
/// Backend-neutral copies of parsed CMYK lookup tables for codec-backed
/// images. Kept separately because fills use the evaluator above while the
/// page IR must not depend on `exprim::color`.
icc_cmyk_image_cache: HashMap<ObjectId, Option<Arc<crate::page_ir::IccCmykTransform>>>,
/// Image XObjects already built on this page, by stream object: a page
/// that draws one image many times (a logo per column, a tiled texture)
/// decodes and lowers it once. An entry is only made when the build did
/// not read the current resource dictionary (`image_cs_resource_relative`),
/// so a `/ColorSpace /CS0` that another resource context could resolve
/// differently is rebuilt each time.
image_xobject_cache: HashMap<ObjectId, SemImage>,
/// Set while building an image when its colour space was looked up in the
/// current `/ColorSpace` resource subdictionary rather than given inline.
image_cs_resource_relative: bool,
/// An ExtGState enabled overprint (`/OP` or `/op` true). Feeds
/// `PageFeatures::OVERPRINT`; compositing itself is unchanged.
uses_overprint: bool,
}
/// The name-keyed resolution caches, parked while a nested content stream runs
/// under a different `/Resources` dictionary. See
/// [`Interpreter::take_resource_caches`].
struct ResourceCaches {
font: HashMap<NameId, FontId>,
type3: HashMap<NameId, Option<Arc<Type3Font>>>,
pattern: HashMap<NameId, Option<SemColor>>,
uncolored_tiling: HashMap<(NameId, [u32; 4]), TilingId>,
tint: HashMap<NameId, Option<Arc<TintSpace>>>,
cie: HashMap<NameId, Option<CieSpace>>,
indexed: HashMap<NameId, Option<crate::page_ir::ImageColorSpace>>,
}
/// Text matrices and clipping accumulation belong to BT..ET, not q..Q.
#[derive(Default)]
enum TextObjectState {
#[default]
Outside,
Active(TextObject),
}
struct TextObject {
matrix: Matrix,
line_matrix: Matrix,
clip_runs: Vec<TextRunId>,
}
impl Default for TextObject {
fn default() -> Self {
Self {
matrix: Matrix::IDENTITY,
line_matrix: Matrix::IDENTITY,
clip_runs: Vec::new(),
}
}
}
/// Caller-owned stream state parked during a form, soft mask, or CharProc.
/// Stack floors keep malformed nested closers from consuming caller scopes.
struct NestedStreamFrame {
graphics_floor: usize,
marked_floor: usize,
marked_depth: usize,
hidden_count: u32,
resources: Option<Arc<PdfObject>>,
caches: ResourceCaches,
pattern_base: Matrix,
path: PathBuilder,
pending_clip: Option<FillRule>,
text: TextObjectState,
operands: Vec<Operand>,
type3_shape_only: bool,
type3_d_width: Option<f64>,
}
impl<'a> Interpreter<'a> {
fn enter_nested_stream(
&mut self,
resources: Option<Arc<PdfObject>>,
concat: Matrix,
) -> NestedStreamFrame {
let frame = NestedStreamFrame {
graphics_floor: self.gs_stack_floor,
marked_floor: self.mc_stack_floor,
marked_depth: self.mc_stack.len(),
hidden_count: self.oc_hidden_count,
resources: std::mem::replace(&mut self.resources, resources),
caches: self.take_resource_caches(),
pattern_base: self.pattern_base,
path: std::mem::take(&mut self.path),
pending_clip: self.pending_clip.take(),
text: std::mem::take(&mut self.text),
operands: std::mem::take(&mut self.operands),
type3_shape_only: self.type3_shape_only,
type3_d_width: self.type3_d_width.take(),
};
self.gs_stack.push(self.gs.clone());
self.emit(SemanticOp::Save);
self.gs_stack_floor = self.gs_stack.len();
self.mc_stack_floor = self.mc_stack.len();
if concat != Matrix::IDENTITY {
self.gs.ctm = concat.then(self.gs.ctm);
self.emit(SemanticOp::Concat(concat));
}
self.pattern_base = self.gs.ctm;
self.invoke_depth += 1;
frame
}
fn leave_nested_stream(&mut self, frame: NestedStreamFrame, end_group: bool) {
// Close unbalanced saves while still inside the group's op scope.
while self.gs_stack.len() > self.gs_stack_floor {
if let Some(gs) = self.gs_stack.pop() {
self.gs = gs;
self.emit(SemanticOp::Restore);
}
}
if end_group {
self.emit(SemanticOp::EndGroup);
}
self.gs_stack_floor = frame.graphics_floor;
if let Some(gs) = self.gs_stack.pop() {
self.gs = gs;
self.emit(SemanticOp::Restore);
}
self.mc_stack.truncate(frame.marked_depth);
self.mc_stack_floor = frame.marked_floor;
self.oc_hidden_count = frame.hidden_count;
self.resources = frame.resources;
self.restore_resource_caches(frame.caches);
self.pattern_base = frame.pattern_base;
self.path = frame.path;
self.pending_clip = frame.pending_clip;
self.text = frame.text;
self.operands = frame.operands;
self.type3_shape_only = frame.type3_shape_only;
self.type3_d_width = frame.type3_d_width;
self.invoke_depth -= 1;
}
fn text_object(&mut self) -> &mut TextObject {
// Retain tolerant placement of text outside BT..ET, but make its
// recovery an explicit transition with fresh matrices.
if matches!(self.text, TextObjectState::Outside) {
self.ctx
.note_recovery("text operator outside BT..ET; starting text object".to_string());
self.text = TextObjectState::Active(TextObject::default());
}
match &mut self.text {
TextObjectState::Active(text) => text,
TextObjectState::Outside => unreachable!(),
}
}
fn text_matrix(&self) -> Matrix {
match &self.text {
TextObjectState::Outside => Matrix::IDENTITY,
TextObjectState::Active(text) => text.matrix,
}
}
fn advance_text(&mut self, tx: f64, ty: f64) {
let text = self.text_object();
text.matrix = Matrix::translate(tx, ty).then(text.matrix);
}
fn end_text_object(&mut self) {
if let TextObjectState::Active(text) = std::mem::take(&mut self.text)
&& !text.clip_runs.is_empty()
{
self.emit(SemanticOp::ClipText {
runs: text.clip_runs,
});
self.gs.clip_depth += 1;
}
}
pub(crate) fn new(
snapshot: &'a DocumentSnapshot,
ctx: &'a mut ParseContext,
limits: &'a ContentLimits,
resources: Option<Arc<PdfObject>>,
system_fonts: Option<Arc<dyn crate::font::SystemFontProvider>>,
) -> Self {
let names = snapshot.names();
Self {
snapshot,
ctx,
names,
limits,
page_resources: resources.clone(),
resources,
system_fonts,
ops: Vec::new(),
paths: Vec::new(),
text_runs: Vec::new(),
images: Vec::new(),
fonts: Vec::new(),
font_cache: HashMap::new(),
font_resources: snapshot.extension::<FontResourceCache>(),
shadings: Vec::new(),
tilings: Vec::new(),
pattern_cache: HashMap::new(),
uncolored_tiling_cache: HashMap::new(),
tint_cache: HashMap::new(),
type3_cache: HashMap::new(),
cie_cache: HashMap::new(),
indexed_cache: HashMap::new(),
mc_stack: Vec::new(),
mc_stack_floor: 0,
next_actual_text_span: 0,
oc_hidden_count: 0,
record_marked: false,
marked_open: Vec::new(),
marked_spans: Vec::new(),
image_cs_degraded: false,
record_trace: false,
trace: Vec::new(),
trace_segments: Vec::new(),
trace_stream: None,
trace_stack: Vec::new(),
trace_extra: None,
trace_seq: 0,
trace_current: None,
gs: GraphicsState::default(),
gs_stack: Vec::new(),
gs_stack_floor: 0,
path: PathBuilder::default(),
pending_clip: None,
text: TextObjectState::Outside,
operands: Vec::new(),
ops_executed: 0,
invoke_depth: 0,
pattern_base: Matrix::IDENTITY,
form_stack: Vec::new(),
soft_mask_stack: Vec::new(),
type3_nesting: 0,
type3_shape_only: false,
type3_d_width: None,
uses_icc_color: false,
icc_cache: HashMap::new(),
icc_cmyk_cache: HashMap::new(),
icc_cmyk_image_cache: HashMap::new(),
image_xobject_cache: HashMap::new(),
image_cs_resource_relative: false,
uses_overprint: false,
}
}
/// Interpret one content byte stream in the current state.
///
/// Content malformation is *recovered*, not fatal (matching PDFium's
/// interpreter): an unparseable token is skipped and an operator that fails
/// on bad/insufficient operands is dropped, each with a `note_recovery`, and
/// interpretation continues — so a single bad byte can never drop an
/// otherwise-paintable page. Only the DoS guards (operator budget,
/// recursion depth, operand-stack overflow, operand nesting depth) still
/// abort; those are the only errors this ever returns `Err` for. See
/// [`ContentError::is_fatal`].
pub(crate) fn run(&mut self, content: &[u8]) -> Result<(), ContentError> {
let mut lexer = ContentLexer::new(content, &self.limits.syntax);
let mut lexemes_seen = 0_u64;
loop {
if lexemes_seen & 0xff == 0 && self.ctx.is_cancelled() {
return Err(ContentError::Cancelled);
}
let pos_before = lexer.pos();
match lexer.next_lexeme() {
Ok(None) => break,
Ok(Some(lex)) => {
lexemes_seen = lexemes_seen.saturating_add(1);
match lex {
Lexeme::Operand(o) => {
if self.operands.len() >= MAX_OPERAND_STACK {
// DoS guard: unbounded operand accumulation. Fatal.
return Err(ContentError::OperandStackOverflow(
self.operands.len(),
));
}
self.operands.push(o);
}
Lexeme::Operator(op) => {
self.ops_executed += 1;
if self.ops_executed > self.limits.max_ops {
return Err(ContentError::OperatorBudget(self.ops_executed));
}
let offset = lexer.last_operator_offset();
if self.record_trace {
// `pos` sits just past the keyword: the span
// is exactly the operator token.
self.trace_seq += 1;
self.trace_current = Some(TraceCurrent {
operator: op.clone(),
span_start: offset,
span_end: lexer.pos(),
seq: self.trace_seq,
});
}
if let Err(e) = self.dispatch(&op, offset) {
if e.is_fatal() {
return Err(e);
}
// Drop the bad operator and reset the operand stack,
// then continue at the next lexeme.
self.ctx.note_recovery(format!(
"content operator {} dropped ({e})",
String::from_utf8_lossy(&op)
));
}
self.operands.clear();
}
Lexeme::InlineImage { dict, data } => {
// One operation against the page budget, like the
// operator it replaces (B15): otherwise a stream
// of inline images is bounded only by the decode
// budget.
self.ops_executed += 1;
if self.ops_executed > self.limits.max_ops {
return Err(ContentError::OperatorBudget(self.ops_executed));
}
if self.record_trace {
// `pos_before` is the `BI` start; `pos` sits
// just past `EI`: the span is the whole image.
self.trace_seq += 1;
self.trace_current = Some(TraceCurrent {
operator: b"BI".to_vec(),
span_start: pos_before,
span_end: lexer.pos(),
seq: self.trace_seq,
});
}
// Suppressed inside an OC-hidden span.
if !self.oc_hidden() {
self.inline_image(&dict, data);
}
self.operands.clear();
}
}
}
Err(e) => {
if e.is_fatal() {
return Err(e);
}
self.ctx
.note_recovery(format!("content token skipped ({e})"));
// Guarantee forward progress. Most malformations leave the
// cursor past the offending token (e.g. a keyword where an
// operand was expected), so we simply continue. But a
// delimiter the lexer refuses to consume (a stray `)` or
// `>`) leaves the cursor where it started; step over one
// byte so the loop cannot spin. `read_inline_image` already
// advances the cursor itself before returning a recoverable
// framing error, so it lands in the "already advanced" case.
if lexer.pos() <= pos_before && !lexer.skip_byte() {
break; // at end of input: return the partial page
}
}
}
}
// A stream's last operator must not leak into whatever emits next:
// the caller's `trace_exit` restores the outer provenance (or none,
// for the page-level run, so post-content annotation wrappers read
// as synthesized).
if self.record_trace {
self.trace_current = None;
}
Ok(())
}
/// Finalize into an immutable [`SemanticPage`].
pub(crate) fn finish(self, bounds: PageBounds) -> SemanticPage {
SemanticPage {
bounds,
ops: self.ops.into(),
paths: self.paths.into(),
text_runs: self.text_runs.into(),
images: self.images.into(),
fonts: self.fonts.into(),
shadings: self.shadings.into(),
tilings: self.tilings.into(),
uses_icc_color: self.uses_icc_color,
uses_overprint: self.uses_overprint,
}
}
// --- operand helpers ---------------------------------------------------
/// The last `N` operands as `f64`s, or `None` if there are too few or any
/// is non-numeric.
fn nums<const N: usize>(&self) -> Option<[f64; N]> {
let ops = &self.operands;
if ops.len() < N {
return None;
}
let base = ops.len() - N;
let mut out = [0.0; N];
for (i, slot) in out.iter_mut().enumerate() {
*slot = ops[base + i].as_f64()?;
}
Some(out)
}
fn last_num(&self) -> Option<f64> {
self.operands.last().and_then(Operand::as_f64)
}
fn intern(&self, bytes: &[u8]) -> NameId {
self.names.intern(bytes)
}
/// The id of a content-stream name that is only used as a key into a
/// resource dictionary, which the caller must already have resolved.
/// Resolving a dictionary interns its keys, so a name that was never
/// interned cannot be one of them: `None` is a miss, exactly as a lookup
/// would have been. Interning it instead grew the document-wide,
/// append-only name table with every distinct missing name (B15).
fn lookup_name(&self, bytes: &[u8]) -> Option<NameId> {
self.names.lookup(bytes)
}
/// The id of a name inside an inline image's parameters (`/F`, `/CS`
/// arrays and dictionaries). Names already interned keep their id; the
/// closed set of names the spec gives meaning there is interned; any
/// other name maps to one shared placeholder that matches no key and no
/// filter or colour-space family, so an adversarial array costs at most
/// one table entry (B15). Callers resolve the resource categories an
/// inline name may refer to first, so a resource name is already
/// interned.
fn inline_name(&self, bytes: &[u8]) -> NameId {
if let Some(id) = self.names.lookup(bytes) {
return id;
}
if INLINE_SPEC_NAMES.contains(&bytes) {
return self.names.intern(bytes);
}
self.names.intern(UNKNOWN_INLINE_NAME)
}
// --- dispatch ----------------------------------------------------------
/// Execute one operator. `offset` is the operator keyword's byte offset
/// in the content slice being interpreted — only the marked-content
/// inventory reads it.
fn dispatch(&mut self, op: &[u8], offset: usize) -> Result<(), ContentError> {
match op {
// --- graphics state ---
b"q" => {
self.gs_stack.push(self.gs.clone());
self.emit(SemanticOp::Save);
}
b"Q" => {
if self.gs_stack.len() > self.gs_stack_floor
&& let Some(prev) = self.gs_stack.pop()
{
self.gs = prev;
self.emit(SemanticOp::Restore);
}
// Unbalanced Q with an empty stack is tolerated (ignored).
}
b"cm" => {
if let Some([a, b, c, d, e, f]) = self.nums() {
let m = Matrix { a, b, c, d, e, f };
self.gs.ctm = m.then(self.gs.ctm);
self.emit(SemanticOp::Concat(m));
}
}
b"w" => {
if let Some(v) = self.last_num() {
self.gs.line_width = v;
self.emit(SemanticOp::SetLineWidth(v));
}
}
b"J" => {
if let Some(v) = self.last_num() {
let cap = map_line_cap(v);
self.gs.line_cap = cap;
self.emit(SemanticOp::SetLineCap(cap));
}
}
b"j" => {
if let Some(v) = self.last_num() {
let join = map_line_join(v);
self.gs.line_join = join;
self.emit(SemanticOp::SetLineJoin(join));
}
}
b"M" => {
if let Some(v) = self.last_num() {
self.gs.miter_limit = v;
self.emit(SemanticOp::SetMiterLimit(v));
}
}
b"d" => self.op_dash(),
// Rendering intent and flatness carry no semantic geometry.
b"ri" | b"i" => {}
b"gs" => self.op_ext_gstate()?,
// --- color ---
b"g" => self.set_device_gray(false),
b"G" => self.set_device_gray(true),
b"rg" => self.set_device_rgb(false),
b"RG" => self.set_device_rgb(true),
b"k" => self.set_device_cmyk(false),
b"K" => self.set_device_cmyk(true),
b"cs" => self.set_color_space(false),
b"CS" => self.set_color_space(true),
b"sc" | b"scn" => self.set_color(false),
b"SC" | b"SCN" => self.set_color(true),
// --- path construction ---
b"m" => {
if let Some([x, y]) = self.nums() {
self.path.move_to(x, y);
}
}
b"l" => {
if let Some([x, y]) = self.nums() {
self.path.line_to(x, y);
}
}
b"c" => {
if let Some([x1, y1, x2, y2, x3, y3]) = self.nums() {
self.path.curve_to(x1, y1, x2, y2, x3, y3);
}
}
b"v" => {
if let Some([x2, y2, x3, y3]) = self.nums() {
self.path.curve_v(x2, y2, x3, y3);
}
}
b"y" => {
if let Some([x1, y1, x3, y3]) = self.nums() {
self.path.curve_y(x1, y1, x3, y3);
}
}
b"re" => {
if let Some([x, y, w, h]) = self.nums() {
self.path.rect(x, y, w, h);
}
}
b"h" => self.path.close(),
// --- path painting ---
b"S" => self.paint(false, None, true),
b"s" => self.paint(true, None, true),
b"f" | b"F" => self.paint(false, Some(FillRule::NonZero), false),
b"f*" => self.paint(false, Some(FillRule::EvenOdd), false),
b"B" => self.paint(false, Some(FillRule::NonZero), true),
b"B*" => self.paint(false, Some(FillRule::EvenOdd), true),
b"b" => self.paint(true, Some(FillRule::NonZero), true),
b"b*" => self.paint(true, Some(FillRule::EvenOdd), true),
b"n" => self.paint(false, None, false),
// --- clipping ---
b"W" => self.pending_clip = Some(FillRule::NonZero),
b"W*" => self.pending_clip = Some(FillRule::EvenOdd),
// --- text ---
b"BT" => {
// Recover a repeated BT by committing the previous object's
// clipping before starting a new object.
self.end_text_object();
self.text = TextObjectState::Active(TextObject::default());
}
b"ET" => self.end_text_object(),
b"Tc" => {
if let Some(v) = self.last_num() {
self.gs.char_spacing = v;
}
}
b"Tw" => {
if let Some(v) = self.last_num() {
self.gs.word_spacing = v;
}
}
b"Tz" => {
if let Some(v) = self.last_num() {
self.gs.horizontal_scale = v;
}
}
b"TL" => {
if let Some(v) = self.last_num() {
self.gs.leading = v;
}
}
b"Tf" => self.op_set_font(),
b"Tr" => {
if let Some(v) = self.last_num() {
self.gs.render_mode = v as u8;
}
}
b"Ts" => {
if let Some(v) = self.last_num() {
self.gs.rise = v;
}
}
b"Td" => {
if let Some([tx, ty]) = self.nums() {
self.text_move(tx, ty);
}
}
b"TD" => {
if let Some([tx, ty]) = self.nums() {
self.gs.leading = -ty;
self.text_move(tx, ty);
}
}
b"Tm" => {
if let Some([a, b, c, d, e, f]) = self.nums() {
let text = self.text_object();
text.line_matrix = Matrix { a, b, c, d, e, f };
text.matrix = text.line_matrix;
}
}
b"T*" => {
let leading = self.gs.leading;
self.text_move(0.0, -leading);
}
b"Tj" => {
if let Some(bytes) = self.operands.last().and_then(Operand::as_string) {
let elements = vec![TextElement::Show(bytes.to_vec())];
self.emit_text_run(elements);
}
}
b"TJ" => self.op_show_array(),
b"'" => {
let leading = self.gs.leading;
self.text_move(0.0, -leading);
if let Some(bytes) = self.operands.last().and_then(Operand::as_string) {
self.emit_text_run(vec![TextElement::Show(bytes.to_vec())]);
}
}
b"\"" => {
// aw ac string "
if let Some([aw, ac]) = self.nums::<2>() {
self.gs.word_spacing = aw;
self.gs.char_spacing = ac;
}
let leading = self.gs.leading;
self.text_move(0.0, -leading);
if let Some(bytes) = self.operands.last().and_then(Operand::as_string) {
self.emit_text_run(vec![TextElement::Show(bytes.to_vec())]);
}
}
// --- XObjects, shadings, marked content, compatibility ---
b"Do" => self.op_do()?,
b"sh" => {
// Suppressed inside an OC-hidden span (paints nothing).
if !self.oc_hidden() {
self.op_shading()?;
}
}
// --- Type 3 glyph metrics (ISO 32000-1 §9.6.5) ---
// `d0 wx wy` (coloured glyph) and `d1 wx wy llx lly urx ury`
// (shape-only glyph) are the first operator of a CharProc. Only
// meaningful while executing one; capture `wx` as an advance
// fallback, and let `d1` lock colour for the rest of the glyph.
b"d0" => {
if self.type3_nesting > 0 && self.type3_d_width.is_none() {
self.type3_d_width = self.operands.first().and_then(Operand::as_f64);
}
}
b"d1" => {
if self.type3_nesting > 0 {
if self.type3_d_width.is_none() {
self.type3_d_width = self.operands.first().and_then(Operand::as_f64);
}
self.type3_shape_only = true;
}
}
// --- marked content (ISO 32000-1 §14.6) ---
// Only `/OC` spans affect rendering: content inside a span whose
// optional-content group is OFF is suppressed (§8.11.3.2). Other
// tags carry no geometry we model.
b"BMC" => {
self.mc_stack.push(MarkedContentFrame {
hidden: false,
actual_text: None,
});
self.marked_open_bmc(offset);
}
b"BDC" => {
let hidden = self.bdc_hides();
let actual_text = self.bdc_actual_text();
self.mc_stack.push(MarkedContentFrame {
hidden,
actual_text,
});
if hidden {
self.oc_hidden_count += 1;
}
self.marked_open_bdc(offset);
}
b"EMC" => {
// Unbalanced EMC is tolerated (ignored), like unbalanced Q.
if self.mc_stack.len() > self.mc_stack_floor {
if let Some(frame) = self.mc_stack.pop()
&& frame.hidden
{
self.oc_hidden_count -= 1;
}
self.marked_close(offset);
}
}
// Any unknown operator: ignore, having consumed the pending
// operands.
_ => {}
}
Ok(())
}
// --- color operators ---------------------------------------------------
fn set_device_gray(&mut self, stroke: bool) {
let v = self.last_num().unwrap_or(0.0);
let color = SemColor::DeviceGray(v);
self.set_color_and_space(stroke, ColorSpace::DeviceGray, color);
}
fn set_device_rgb(&mut self, stroke: bool) {
let [r, g, b] = self.nums().unwrap_or([0.0; 3]);
self.set_color_and_space(stroke, ColorSpace::DeviceRgb, SemColor::DeviceRgb(r, g, b));
}
fn set_device_cmyk(&mut self, stroke: bool) {
let [c, m, y, k] = self.nums().unwrap_or([0.0; 4]);
// A resource `/DefaultCMYK` press profile substitutes for the device
// space (§8.6.5.6): PDFium runs the `k`/`K` operands through it via
// LittleCMS instead of its frozen table. Convert once, here, so the
// colour lands as the same sRGB PDFium produces.
let color = match self.default_cmyk_profile() {
Some(prof) => {
let [r, g, b] = prof.to_srgb([c as f32, m as f32, y as f32, k as f32]);
SemColor::DeviceRgb(r as f64, g as f64, b as f64)
}
None => SemColor::DeviceCmyk(c, m, y, k),
};
self.set_color_and_space(stroke, ColorSpace::DeviceCmyk, color);
}
fn set_color_and_space(&mut self, stroke: bool, space: ColorSpace, color: SemColor) {
if stroke {
self.gs.stroke_space = space;
self.gs.stroke_color = color.clone();
self.push_color_op(SemanticOp::SetStrokeColor(color));
} else {
self.gs.fill_space = space;
self.gs.fill_color = color.clone();
self.push_color_op(SemanticOp::SetFillColor(color));
}
}
/// Emit a colour-setting op, unless a `d1` (shape-only) Type 3 glyph is
/// being executed — such a glyph paints with the fill colour in effect at
/// show time, so its own colour operators are suppressed (§9.6.5.1). The
/// graphics state is still updated by the caller so a matching Restore
/// stays balanced; only the emitted mark is dropped.
fn push_color_op(&mut self, op: SemanticOp) {
if !self.type3_shape_only {
self.emit(op);
}
}
fn set_color_space(&mut self, stroke: bool) {
let Some(name) = self
.operands
.last()
.and_then(Operand::as_name)
.map(<[u8]>::to_vec)
else {
return;
};
let space = self.resolve_color_space(&name);
// Separation/DeviceN start at 1.0 in every component — full colorant,
// i.e. black-ish, not white (ISO 32000-1 §8.6.8). `eval_tint` applies
// that default for an empty operand list.
let initial = match &space {
ColorSpace::Named(id) => match self.resolve_tint_space(*id) {
Some(ts) => self.eval_tint(&ts, &[]),
// CIE spaces initialise to all-zero components (§8.6.3),
// which the conversion turns into the right device black.
None => match self.resolve_cie_space(*id) {
Some(cie) => eval_cie(cie, &[]),
None => initial_color(&space),
},
},
_ => initial_color(&space),
};
if let ColorSpace::Named(id) = &space {
self.note_named_space_family(*id);
}
self.set_color_and_space(stroke, space, initial);
}
/// Record color-management facts about a named colour space that only
/// exist as page feature flags: `/ICCBased` sets `uses_icc_color` (the
/// rendering itself keeps the documented arity approximation).
fn note_named_space_family(&mut self, id: NameId) {
if self.uses_icc_color {
return;
}
let Some(cs) = self.resource_subdict(self.names.known.color_space) else {
return;
};
let Some(entry) = cs.as_dict().and_then(|d| d.get(id)).cloned() else {
return;
};
let Some(obj) = self.resolve_obj(&entry) else {
return;
};
if let PdfObject::Array(items) = &*obj
&& let Some(head) = items.first().and_then(PdfObject::as_name)
&& self.names.resolve(head).as_ref() == b"ICCBased"
{
self.uses_icc_color = true;
}
}
/// Resolve a resource-named space if it is `/Separation` or `/DeviceN`.
///
/// These are *subtractive*: a tint of 1.0 means **full colorant**, and
/// the tint transform maps tints into an alternate space. Treating them
/// by component arity instead (1 tint → DeviceGray) inverts them —
/// `1.0` becomes white — which silently erases text painted in
/// `[/Separation /Black ...]`, a very common way to spell "black" in
/// print-oriented PDFs.
fn resolve_tint_space(&mut self, id: NameId) -> Option<Arc<TintSpace>> {
if let Some(hit) = self.tint_cache.get(&id) {
return hit.clone();
}
let resolved = self.build_tint_space(id);
self.tint_cache.insert(id, resolved.clone());
resolved
}
/// Resolve a resource-named space *only if it is `/Indexed`*, returning the
/// palette-carrying [`ImageColorSpace`]. Other families (Separation/DeviceN,
/// CIE, ICCBased) are left to the tint / CIE / arity paths in
/// [`Self::set_color`]. An `sc`/`scn` in an Indexed space takes an integer
/// palette index, not colour components (§8.6.6.3); without this the index
/// was mis-read as raw components and every fill collapsed to black
/// (pdfbox/2561 page 3 dropped its red/green/blue bars to one black bar).
///
/// Memoised per resource scope, and a space whose array head is not
/// `/Indexed` is never built: every `sc`/`scn` in a Separation, DeviceN or
/// ICCBased space used to build the full image colour space just to learn
/// it was not Indexed — a 256- or 65,536-entry tint bake, or an inflated
/// ICC profile, per operator. The inflations were charged to the decode
/// budget, so a page with enough of them silently lost its later images,
/// forms and soft masks.
fn resolve_named_indexed(&mut self, id: NameId) -> Option<crate::page_ir::ImageColorSpace> {
if let Some(hit) = self.indexed_cache.get(&id) {
return hit.clone();
}
let resolved = if self.named_space_has_indexed_head(id) {
self.resolve_image_colorspace(&PdfObject::Name(id))
.filter(|cs| matches!(cs, crate::page_ir::ImageColorSpace::Indexed { .. }))
} else {
None
};
self.indexed_cache.insert(id, resolved.clone());
resolved
}
/// Whether the resource-named space `id` is an `/Indexed` (or `/I`) array,
/// read from the array head alone. Follows name aliases (`/CS0 /CS1`) as
/// [`Self::resolve_image_colorspace`] does, to the same depth. Only ever
/// answers `false` where that resolver would not return an Indexed space,
/// so it can gate the build without changing any result.
fn named_space_has_indexed_head(&mut self, id: NameId) -> bool {
let mut name = id;
for _ in 0..=self.limits.max_colorspace_depth {
let Some(entry) = self
.resource_subdict(self.names.known.color_space)
.and_then(|cs| cs.as_dict()?.get(name).cloned())
else {
return false;
};
let Some(resolved) = self.resolve_obj(&entry) else {
return false;
};
match &*resolved {
PdfObject::Array(items) => {
return items
.first()
.and_then(PdfObject::as_name)
.is_some_and(|head| {
matches!(self.names.resolve(head).as_ref(), b"Indexed" | b"I")
});
}
PdfObject::Name(next) => name = *next,
_ => return false,
}
}
false
}
fn build_tint_space(&mut self, id: NameId) -> Option<Arc<TintSpace>> {
let cs = self.resource_subdict(self.names.known.color_space)?;
let entry = cs.as_dict().and_then(|d| d.get(id)).cloned()?;
let obj = self.resolve_obj(&entry)?;
let PdfObject::Array(items) = &*obj else {
return None;
};
self.build_tint_space_from_array(items)
}
/// Build a [`TintSpace`] from a resolved `[/Separation …]` / `[/DeviceN …]`
/// array (shared by the resource-named fill path and the image-colorspace
/// path).
fn build_tint_space_from_array(&mut self, items: &[PdfObject]) -> Option<Arc<TintSpace>> {
let head = items.first().and_then(PdfObject::as_name)?;
let kind = self.names.resolve(head).to_vec();
// `[/Separation name alt tint]` | `[/DeviceN names alt tint ...]`
let inputs = match kind.as_slice() {
b"Separation" => 1,
b"DeviceN" => {
let names = self.resolve_obj(items.get(1)?)?;
match &*names {
PdfObject::Array(a) => a.len().max(1),
_ => 1,
}
}
_ => return None,
};
// `/None` marks nothing at all; `/All` paints every plate.
let colorant_name = |this: &mut Self, items: &[PdfObject], name: &[u8]| {
items
.get(1)
.and_then(PdfObject::as_name)
.map(|n| this.names.resolve(n).as_ref() == name)
.unwrap_or(false)
};
let colorant_none = kind == b"Separation" && colorant_name(self, items, b"None");
// `/All` is deliberately *not* special-cased, and deliberately not
// recorded: PDFium's `CPDF_SeparationCS::GetRGB` branches only on
// `/None` and runs the tint transform for every other colorant name,
// `/All` included. Short-circuiting `/All` to neutral ink rendered
// custom/color_separation_3 as flat grey 128 where PDFium, hayro and
// MuPDF all produce the transform's brown (81, 74, 71). If a page
// feature note ever wants it, recompute it here — do not reintroduce
// a field that nothing reads.
let alt_arity = items
.get(2)
.and_then(|alt| self.resolve_image_colorspace(alt))
.map(|cs| cs.components())
.unwrap_or(1);
// A CIE alternate (Lab/CalRGB/CalGray): the transform outputs land in
// that space's component ranges, not device [0,1].
let alt_cie =
items
.get(2)
.and_then(|alt| self.resolve_obj(alt))
.and_then(|alt| match &*alt {
PdfObject::Array(a) => {
let a = a.to_vec();
self.cie_space_from_items(&a)
}
_ => None,
});
// An ICCBased CMYK alternate (the common press-profile spot colour):
// the transform's four outputs go through the profile, not the frozen
// table. Only consulted when `alt_cie` is absent (a profile is not CIE).
let alt_icc_cmyk = if alt_cie.is_none() {
items
.get(2)
.and_then(|alt| self.resolve_obj(alt))
.and_then(|alt| match &*alt {
PdfObject::Array(a) => {
let a = a.to_vec();
self.iccbased_cmyk_from_items(&a)
}
_ => None,
})
} else {
None
};
// The tint transform: 1 input for Separation, N for DeviceN. Built for
// every arity now that the evaluator handles multi-input Type 0 and
// Type 4; `eval_tint` feeds it all colorants through `eval_n`. A
// transform that will not build stays `None` and the caller
// approximates subtractively.
let func = items
.get(3)
.cloned()
.and_then(|f| self.build_function(&f, 0));
Some(Arc::new(TintSpace {
inputs,
alt_arity,
func,
colorant_none,
alt_cie,
alt_icc_cmyk,
}))
}
/// Convert tint values through a `/Separation` or `/DeviceN` space.
fn eval_tint(&self, space: &TintSpace, values: &[f64]) -> SemColor {
if space.colorant_none {
// A /None colorant marks nothing. Nothing in the semantic colour
// model expresses "no marks", so paint white — which is also
// exactly what PDFium composites: `CPDF_SeparationCS::GetRGB`
// returns nullopt for the None type and the color state falls
// back to `GetColorRef().value_or(0xFFFFFFFF)` — white
// (`cpdf_colorstate.cpp:130`). Verified 2026-07-21.
return SemColor::DeviceRgb(1.0, 1.0, 1.0);
}
// Missing operands: the initial colour of these spaces is 1.0 in
// every component (ISO 32000-1 §8.6.8) — full colorant.
let tints: Vec<f32> = if values.is_empty() {
vec![1.0; space.inputs]
} else {
values.iter().map(|v| (*v as f32).clamp(0.0, 1.0)).collect()
};
// Run all colorants through the tint transform (§8.6.6.5). `eval_n`
// dispatches every function type — a 1-input Separation reads the sole
// tint, a multi-input DeviceN feeds all of them into a `SampledN` /
// Type 4 transform, landing the colour in its real alternate space
// instead of the subtractive grey approximation.
if let Some(func) = &space.func {
let out = func.eval_n(&tints);
// A CIE alternate: convert through the alternate space's own
// math (raw components — Lab's L* is 0..100, a*/b* signed; the
// conversions clamp internally). PDFium: base_cs_->GetRGB.
if let Some(cie) = space.alt_cie
&& !out.is_empty()
{
let vals: Vec<f64> = out.iter().map(|v| *v as f64).collect();
return eval_cie(cie, &vals);
}
// An ICCBased CMYK alternate: run the four tint outputs through the
// press profile, matching PDFium's LittleCMS path.
if let Some(prof) = &space.alt_icc_cmyk
&& out.len() == 4
{
let c = |i: usize| out[i].clamp(0.0, 1.0);
let [r, g, b] = prof.to_srgb([c(0), c(1), c(2), c(3)]);
return SemColor::DeviceRgb(r as f64, g as f64, b as f64);
}
if out.len() == space.alt_arity || matches!(out.len(), 1 | 3 | 4) {
let comps: Vec<f32> = out.iter().map(|v| v.clamp(0.0, 1.0)).collect();
match comps.len() {
1 => return SemColor::DeviceGray(comps[0] as f64),
3 => {
return SemColor::DeviceRgb(
comps[0] as f64,
comps[1] as f64,
comps[2] as f64,
);
}
4 => {
return SemColor::DeviceCmyk(
comps[0] as f64,
comps[1] as f64,
comps[2] as f64,
comps[3] as f64,
);
}
// An arity we cannot map to a device colour (e.g. 2, or a
// mismatch against the alternate space): fall through to the
// subtractive approximation below.
_ => {}
}
}
}
// No usable transform (multi-colorant DeviceN, Type 4 function, a
// malformed one): approximate subtractively. The exact hue is lost
// but the *polarity* is right — more tint means darker — which is
// what makes text readable rather than invisible.
let ink = tints.iter().copied().fold(0.0f32, f32::max);
SemColor::DeviceGray((1.0 - ink) as f64)
}
/// Resolve a resource-named colour space into a [`CieSpace`] when its
/// family is `/Lab`, `/CalRGB` or `/CalGray` (ISO 32000-1 §8.6.5), cached
/// by resource name like [`Self::resolve_tint_space`]. `None` for every
/// other family (Separation/DeviceN take the tint path; ICCBased stays an
/// arity approximation by policy).
fn resolve_cie_space(&mut self, id: NameId) -> Option<CieSpace> {
if let Some(hit) = self.cie_cache.get(&id) {
return *hit;
}
let resolved = self.build_cie_space(id);
self.cie_cache.insert(id, resolved);
resolved
}
fn build_cie_space(&mut self, id: NameId) -> Option<CieSpace> {
let entry = self
.resource_subdict(self.names.known.color_space)?
.as_dict()?
.get(id)?
.clone();
let resolved = self.resolve_obj(&entry)?;
let PdfObject::Array(items) = &*resolved else {
return None;
};
let items = items.to_vec();
self.cie_space_from_items(&items)
}
/// Parse an already-resolved `[/Lab …]` / `[/CalRGB …]` / `[/CalGray …]`
/// array into a [`CieSpace`] (shared by the resource-named path and the
/// Separation/DeviceN *alternate*-space path).
fn cie_space_from_items(&mut self, items: &[PdfObject]) -> Option<CieSpace> {
let family = items.first().and_then(PdfObject::as_name)?;
// The parameter dictionary is the (possibly indirect) second element.
// Its absence is malformed; tolerate with spec defaults.
let dict = items
.get(1)
.and_then(|d| self.resolve_obj(d))
.and_then(|d| d.as_dict().cloned());
let f32s = |key: &[u8], out: &mut [f32]| {
let Some(d) = &dict else { return };
let Some(nid) = self.names.lookup(key) else {
return;
};
if let Some(PdfObject::Array(a)) = d.get(nid) {
for (slot, item) in out.iter_mut().zip(a.iter()) {
if let Some(v) = item.as_number() {
*slot = v as f32;
}
}
}
};
match self.names.resolve(family).as_ref() {
b"Lab" => {
// /WhitePoint is accepted-but-unused by the conversion (it
// mirrors PDFium's baked white); /Range defaults per §8.6.5.4.
let mut white_point = [1.0f32, 1.0, 1.0];
let mut range = [-100.0f32, 100.0, -100.0, 100.0];
f32s(b"WhitePoint", &mut white_point);
f32s(b"Range", &mut range);
Some(CieSpace::Lab { white_point, range })
}
b"CalRGB" => {
// Defaults are load-bearing: crate::color::CalRgbTransform always
// applies gamma and matrix, so absent entries must be the
// identity (§8.6.5.3), never zeros (a zero matrix is the
// singular-degrade-to-black path).
let mut white_point = [1.0f32, 1.0, 1.0];
let mut gamma = [1.0f32, 1.0, 1.0];
let mut matrix = [1.0f32, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 1.0];
f32s(b"WhitePoint", &mut white_point);
f32s(b"Gamma", &mut gamma);
f32s(b"Matrix", &mut matrix);
Some(CieSpace::CalRgb(crate::color::CalRgbTransform::new(
white_point,
gamma,
matrix,
)))
}
b"CalGray" => {
let mut gamma = [1.0f32];
if let Some(d) = &dict
&& let Some(nid) = self.names.lookup(b"Gamma")
&& let Some(v) = d.get(nid).and_then(PdfObject::as_number)
{
gamma[0] = v as f32;
}
Some(CieSpace::CalGray { gamma: gamma[0] })
}
// An ICC profile is normally approximated by its `/N` component
// count, which is right for the RGB/Gray/CMYK profiles that make up
// almost all of them. It is badly wrong when the profile's data
// space is *Lab*: pdfjs/issue5939's PANTONE 3278 U is a
// `/Separation` whose alternate is a 3-component Lab profile, so
// its tint transform emits L*=56.5 a*=-43 b*=2 — a mint green.
// Read as RGB that renders hot magenta, because a negative a* is a
// green and a positive one a magenta, and the whole watermark
// flipped hue. The profile header declares its data space at bytes
// 16..20 (ICC.1 §7.2.6), so trust it rather than the arity.
//
// Only Lab is worth intercepting: for the other data spaces the
// arity-based approximation already lands in the right family, and
// without a colour-management engine we cannot do better.
b"ICCBased" => {
let stream = items.get(1).and_then(|s| self.resolve_obj(s))?;
let PdfObject::Stream(stream) = &*stream else {
return None;
};
let profile = self.snapshot.decode_stream_data(stream, self.ctx).ok()?;
if profile.get(16..20)? != b"Lab " {
return None;
}
// ICC Lab encodes a*/b* over -128..127, wider than the PDF
// `/Lab` default of -100..100; clamping to the narrower range
// would clip saturated spot colours.
Some(CieSpace::Lab {
white_point: [1.0, 1.0, 1.0],
range: [-128.0, 127.0, -128.0, 127.0],
})
}
_ => None,
}
}
fn resolve_color_space(&mut self, name: &[u8]) -> ColorSpace {
match name {
b"DeviceGray" | b"G" => ColorSpace::DeviceGray,
b"DeviceRGB" | b"RGB" => ColorSpace::DeviceRgb,
b"DeviceCMYK" | b"CMYK" => ColorSpace::DeviceCmyk,
b"Pattern" => ColorSpace::Pattern(None),
other => {
// A resource-named space that resolves to `[/Pattern base]` is
// a (uncolored) pattern space; anything else stays Named.
if self.named_space_is_pattern(other) {
ColorSpace::Pattern(None)
} else {
ColorSpace::Named(self.intern(other))
}
}
}
}
/// True when a `/ColorSpace` resource named `name` is a Pattern space
/// (`/Pattern` or `[/Pattern base]`).
fn named_space_is_pattern(&mut self, name: &[u8]) -> bool {
let Some(cs) = self.resource_subdict(self.names.known.color_space) else {
return false;
};
let Some(nid) = self.lookup_name(name) else {
return false;
};
let Some(entry) = cs.as_dict().and_then(|d| d.get(nid)).cloned() else {
return false;
};
match self.resolve_obj(&entry).as_deref() {
Some(PdfObject::Name(n)) => self.names.resolve(*n).as_ref() == b"Pattern",
Some(PdfObject::Array(items)) => {
matches!(items.first().and_then(PdfObject::as_name), Some(n) if self.names.resolve(n).as_ref() == b"Pattern")
}
_ => false,
}
}
fn set_color(&mut self, stroke: bool) {
let space = if stroke {
self.gs.stroke_space.clone()
} else {
self.gs.fill_space.clone()
};
let nums: Vec<f64> = self.operands.iter().filter_map(Operand::as_f64).collect();
// A trailing *name* operand means a pattern, whatever the declared
// space says. PDFium decides this way round too — `Handle_SetColorPS_*`
// branches on `pLastParam->IsName()` before it ever looks at the colour
// space — and files rely on it: pdfjs/issue18466 paints a full-page
// rectangle with `/P12 scn` and never emits a `cs` operator at all, so
// the space is still the initial DeviceGray. Reading the operands as
// grey components then yields *black*, and the page rendered as a solid
// black block over its own text.
let pattern_name = self
.operands
.iter()
.rev()
.find_map(Operand::as_name)
.map(|b| self.intern(b));
if !matches!(space, ColorSpace::Pattern(_))
&& let Some(name) = pattern_name
{
let color = self
.resolve_pattern(name, &nums)
.unwrap_or(SemColor::Pattern { name, under: None });
if self.record_trace {
self.trace_extra = self.trace_pattern_frame(&color);
}
if stroke {
self.gs.stroke_color = color.clone();
self.push_color_op(SemanticOp::SetStrokeColor(color));
} else {
self.gs.fill_color = color.clone();
self.push_color_op(SemanticOp::SetFillColor(color));
}
return;
}
let color = match &space {
ColorSpace::DeviceGray => SemColor::DeviceGray(nums.first().copied().unwrap_or(0.0)),
ColorSpace::DeviceRgb => {
SemColor::DeviceRgb(get(&nums, 0), get(&nums, 1), get(&nums, 2))
}
ColorSpace::DeviceCmyk => {
let (c, m, y, k) = (get(&nums, 0), get(&nums, 1), get(&nums, 2), get(&nums, 3));
// A `/DeviceCMYK cs` under a resource `/DefaultCMYK` press
// profile is redirected through it, exactly like the `k`
// operator (§8.6.5.6).
match self.default_cmyk_profile() {
Some(prof) => {
let [r, g, b] = prof.to_srgb([c as f32, m as f32, y as f32, k as f32]);
SemColor::DeviceRgb(r as f64, g as f64, b as f64)
}
None => SemColor::DeviceCmyk(c, m, y, k),
}
}
// Separation/DeviceN carry a tint transform; CIE-based spaces
// (Lab/CalRGB/CalGray) carry conversion parameters — both are
// evaluated here, where the resources live, and emit a device
// colour. Only ICCBased stays component-approximated (profiles
// are a documented policy deferral).
ColorSpace::Named(id) => {
if let Some(cs) = self.resolve_named_indexed(*id) {
// The operand is a palette index; look it up through the
// base space to a device colour.
let index = nums.first().copied().unwrap_or(0.0) as f32;
let rgba = cs_to_rgba(&cs, &[index]);
SemColor::DeviceRgb(rgba[0] as f64, rgba[1] as f64, rgba[2] as f64)
} else {
match self.resolve_tint_space(*id) {
Some(space) => self.eval_tint(&space, &nums),
None => match self.resolve_cie_space(*id) {
Some(cie) => eval_cie(cie, &nums),
// An `/ICCBased` CMYK space carries a press profile
// PDFium runs through LittleCMS; evaluate the four
// operands through it rather than the frozen table.
None => match self.iccbased_cmyk_space(*id) {
Some(prof) if nums.len() >= 4 => {
let [r, g, b] = prof.to_srgb([
nums[0] as f32,
nums[1] as f32,
nums[2] as f32,
nums[3] as f32,
]);
SemColor::DeviceRgb(r as f64, g as f64, b as f64)
}
_ => SemColor::Components {
space: *id,
values: nums,
},
},
},
}
}
}
ColorSpace::Pattern(_) => {
let name = self
.operands
.iter()
.rev()
.find_map(Operand::as_name)
.map(|b| self.intern(b));
// The numeric operands preceding the pattern name are the
// underlying color for an uncolored (PaintType 2) pattern.
match name {
Some(name) => {
let color = self
.resolve_pattern(name, &nums)
.unwrap_or(SemColor::Pattern { name, under: None });
if self.record_trace {
self.trace_extra = self.trace_pattern_frame(&color);
}
color
}
None => SemColor::DeviceGray(0.0),
}
}
};
if stroke {
self.gs.stroke_color = color.clone();
self.push_color_op(SemanticOp::SetStrokeColor(color));
} else {
self.gs.fill_color = color.clone();
self.push_color_op(SemanticOp::SetFillColor(color));
}
}
fn op_dash(&mut self) {
// Operands: [array] phase
let phase = self.last_num().unwrap_or(0.0);
let pattern = self
.operands
.iter()
.find_map(Operand::as_array)
.map(|a| a.iter().filter_map(Operand::as_f64).collect::<Vec<_>>())
.unwrap_or_default();
self.gs.dash_pattern = pattern.clone();
self.gs.dash_phase = phase;
self.emit(SemanticOp::SetDash { pattern, phase });
}
// --- path painting -----------------------------------------------------
fn paint(&mut self, close: bool, fill: Option<FillRule>, stroke: bool) {
if close {
self.path.close();
}
let clip = self.pending_clip.take();
let path_data = self.path.take();
let needs_handle = fill.is_some() || stroke || clip.is_some();
if !needs_handle {
return; // `n` with no pending clip: discard the path.
}
let pid = self.intern_path(path_data);
// An OC-hidden span paints nothing, but its `W … n` clips still
// apply — clipping is state, not marks (§8.11.3.2).
if !self.oc_hidden() {
match (fill, stroke) {
(Some(rule), false) => self.emit(SemanticOp::Fill { path: pid, rule }),
(None, true) => self.emit(SemanticOp::Stroke { path: pid }),
(Some(rule), true) => self.emit(SemanticOp::FillStroke { path: pid, rule }),
(None, false) => {}
}
}
if let Some(rule) = clip {
self.emit(SemanticOp::Clip { path: pid, rule });
self.gs.clip_depth += 1;
}
}
/// Whether painting is currently suppressed by an enclosing OC-hidden
/// marked-content span.
fn oc_hidden(&self) -> bool {
self.oc_hidden_count > 0
}
/// Whether the `BDC` whose operands are on the stack opens a *hidden*
/// span: tag `/OC` and a properties argument naming (via the
/// `/Properties` resource sub-dictionary) an OCG/OCMD that is OFF. An
/// inline-dictionary argument cannot carry references, so it can never
/// name a configured-off group — visible.
fn bdc_hides(&mut self) -> bool {
// Operands: … tag properties. The tag is the second-to-last name.
let n = self.operands.len();
if n < 2 {
return false;
}
let Some(tag) = self.operands[n - 2].as_name() else {
return false;
};
if tag != b"OC" {
return false;
}
let Some(prop_name) = self.operands[n - 1].as_name().map(<[u8]>::to_vec) else {
return false;
};
let Some(properties) = self.resource_subdict(self.intern(b"Properties")) else {
return false;
};
let Some(entry) = self
.lookup_name(&prop_name)
.and_then(|nid| properties.as_dict().and_then(|d| d.get(nid)).cloned())
else {
return false;
};
!self.oc_value_visible(&entry)
}
/// Replacement text carried by the properties operand of the current
/// `BDC`. Both an inline dictionary and a named `/Properties` resource are
/// valid (§14.6). Each BDC scope gets a distinct identity.
fn bdc_actual_text(&mut self) -> Option<ActualTextSpan> {
let properties = self.operands.last()?.clone();
let bytes = match properties {
Operand::Dict(entries) => entries
.iter()
.rev()
.find(|(key, _)| key.as_slice() == b"ActualText")
.and_then(|(_, value)| value.as_string())
.map(<[u8]>::to_vec),
Operand::Name(name) => {
let category = self.intern(b"Properties");
let properties = self.resource_subdict(category)?;
let property_name = self.lookup_name(&name)?;
let entry = properties
.as_dict()
.and_then(|dict| dict.get(property_name))
.cloned()?;
let object = self.resolve_obj(&entry)?;
let dict = object.as_dict()?;
match dict.get(self.intern(b"ActualText")) {
Some(PdfObject::String(value)) => Some(value.0.to_vec()),
_ => None,
}
}
_ => None,
}?;
let utf16 = decode_pdf_text_string(&bytes);
if utf16.is_empty() {
return None;
}
let id = ActualTextSpanId(self.next_actual_text_span);
self.next_actual_text_span = self.next_actual_text_span.saturating_add(1);
Some(ActualTextSpan {
id,
utf16: utf16.into(),
})
}
fn active_actual_text(&self) -> Option<ActualTextSpan> {
self.mc_stack
.iter()
.rev()
.find_map(|frame| frame.actual_text.clone())
}
// --- marked-content inventory ------------------------------------------
//
// Recording is gated on `record_marked` (set only by the marked-content
// accessor) *and* on running the page content stream itself
// (`invoke_depth == 0`). Nested streams — form XObjects, Type 3
// CharProcs, soft masks, tiling cells, annotation appearances — are
// separate byte streams whose offsets belong to no page-level span, so
// their `BMC`/`BDC`/`EMC` and text runs never touch the inventory.
/// Enable span recording for this interpretation. The only caller is the
/// marked-content accessor; default compilation leaves it off.
pub(crate) fn set_record_marked(&mut self) {
self.record_marked = true;
}
/// The recorded spans, in document order. Spans still open (the stream
/// ended without their `EMC`) are reported with no close offset.
pub(crate) fn take_marked_spans(&mut self) -> Vec<MarkedContentSpan> {
for open in self.marked_open.drain(..) {
let Some(tag) = open.tag else {
continue;
};
self.marked_spans.push(MarkedContentSpan {
tag,
open_offset: open.open_offset,
close_offset: None,
bbox: open.bbox,
});
}
self.marked_spans.sort_by_key(|span| span.open_offset);
std::mem::take(&mut self.marked_spans)
}
/// Record a [`PageTrace`] for this run. `segments` is the page-level
/// `/Contents` map from [`gather_content_mapped`]; only the audit entry
/// point calls this.
pub(crate) fn set_record_trace(&mut self, segments: Vec<ContentSegment>) {
self.record_trace = true;
self.trace_segments = segments;
}
/// The recorded trace, index-aligned with the emitted `ops`.
pub(crate) fn take_trace(&mut self) -> PageTrace {
PageTrace {
entries: std::mem::take(&mut self.trace),
}
}
/// Push a semantic op, recording its [`OpTrace`] when
/// [`Self::record_trace`] is set. Every `ops` push goes through here so
/// the trace stays index-aligned with `ops` by construction; with
/// recording off this is exactly a `Vec::push` plus one predictable
/// branch.
fn emit(&mut self, op: SemanticOp) {
let op_index = self.ops.len();
// The one direct push left: this *is* the push path everything else
// funnels through.
self.ops.push(op);
if !self.record_trace {
return;
}
let mut stack = self.trace_stack.clone();
if let Some(extra) = self.trace_extra.take() {
stack.push(extra);
}
let origin = stack
.iter()
.rev()
.find_map(|frame| frame.kind.paint_origin())
.unwrap_or_default();
let Some(current) = self.trace_current.as_ref() else {
// Synthesized: emitted outside any content operator, so there is
// no source stream or byte span to name — only the stack.
self.trace.push(OpTrace {
op_index,
content_op_index: self.trace_seq,
operator: Vec::new(),
synthesized: true,
stream: None,
stack,
span: (0, 0),
origin,
});
return;
};
// At the page level the stream and stream-relative span come from
// the `/Contents` segment map; inside a nested stream the offsets
// are already stream-relative.
let (stream, span) = if self.trace_stack.is_empty() {
segment_span(&self.trace_segments, current.span_start, current.span_end)
} else {
(self.trace_stream, (current.span_start, current.span_end))
};
self.trace.push(OpTrace {
op_index,
content_op_index: current.seq,
operator: current.operator.clone(),
synthesized: false,
stream,
stack,
span,
origin,
});
}
/// Enter a nested content stream for tracing: the frame is pushed, the
/// source stream object becomes current, and the outer operator's
/// provenance is parked for [`Self::trace_exit`]. No-op unless
/// [`Self::record_trace`] is set.
fn trace_enter(
&mut self,
kind: TraceFrameKind,
object: Option<ObjectId>,
) -> (Option<ObjectId>, Option<TraceCurrent>) {
if !self.record_trace {
return (None, None);
}
let saved_stream = std::mem::replace(&mut self.trace_stream, object);
let saved_current = self.trace_current.take();
self.trace_stack.push(TraceFrame { kind, object });
(saved_stream, saved_current)
}
/// Leave a nested content stream entered with [`Self::trace_enter`].
fn trace_exit(&mut self, saved: (Option<ObjectId>, Option<TraceCurrent>)) {
if !self.record_trace {
return;
}
self.trace_stack.pop();
self.trace_stream = saved.0;
self.trace_current = saved.1;
}
/// The stack frame for a pattern `color` just resolved, naming its
/// backing object when known. `None` for non-pattern colors and for the
/// symbolic fallback (whose object was never resolved).
fn trace_pattern_frame(&self, color: &SemColor) -> Option<TraceFrame> {
let (kind, object) = match color {
SemColor::ShadingPattern { shading, .. } => (
TraceFrameKind::ShadingPattern,
self.shadings.get(shading.index())?.object,
),
SemColor::TilingPattern { tiling, .. } => (
TraceFrameKind::TilingPattern,
self.tilings.get(tiling.index())?.object,
),
_ => return None,
};
object.map(|object| TraceFrame {
kind,
object: Some(object),
})
}
/// Whether a marked-content event belongs in the inventory.
fn marked_active(&self) -> bool {
self.record_marked && self.invoke_depth == 0
}
fn marked_open_bmc(&mut self, offset: usize) {
if !self.marked_active() {
return;
}
let tag = self
.operands
.last()
.and_then(Operand::as_name)
.map(|name| String::from_utf8_lossy(name).into_owned());
self.marked_open.push(OpenMarkedSpan {
tag,
open_offset: offset,
bbox: None,
});
}
fn marked_open_bdc(&mut self, offset: usize) {
if !self.marked_active() {
return;
}
// Operands: … tag properties. The tag is the second-to-last name,
// mirroring `bdc_hides`.
let tag = self
.operands
.len()
.checked_sub(2)
.and_then(|i| self.operands[i].as_name())
.map(|name| String::from_utf8_lossy(name).into_owned());
self.marked_open.push(OpenMarkedSpan {
tag,
open_offset: offset,
bbox: None,
});
}
fn marked_close(&mut self, offset: usize) {
if !self.marked_active() {
return;
}
// Unbalanced EMC is tolerated (ignored), like `mc_stack` above.
let Some(open) = self.marked_open.pop() else {
return;
};
let Some(tag) = open.tag else {
return;
};
self.marked_spans.push(MarkedContentSpan {
tag,
open_offset: open.open_offset,
close_offset: Some(offset),
bbox: open.bbox,
});
}
/// Fold a just-emitted text run's bounds into every open span. Called
/// with the run-start text matrix still in place (the advance below
/// has not run yet), so the box covers what this run paints.
fn marked_note_text_run(&mut self, font: FontId, elements: &[TextElement]) {
if !self.marked_active() || self.marked_open.is_empty() {
return;
}
let Some(run_box) = self.marked_run_box(font, elements) else {
return;
};
for open in &mut self.marked_open {
open.bbox = Some(open.bbox.map_or(run_box, |bbox| bbox.union(run_box)));
}
}
/// Advance-derived user-space box for a text run: the rectangle from
/// the run origin to its total displacement, `font_size` tall, mapped
/// through the run's text matrix and the CTM. `None` when any input is
/// non-finite (content numbers are untrusted).
fn marked_run_box(&self, font: FontId, elements: &[TextElement]) -> Option<Rect> {
let (tx, ty) = self.text_displacement(font, elements);
let size = self.gs.font_size.abs();
let rise = self.gs.rise;
if !(tx.is_finite() && ty.is_finite() && size.is_finite() && rise.is_finite()) {
return None;
}
if !self.text_matrix().is_finite() || !self.gs.ctm.is_finite() {
return None;
}
let x0 = 0.0f64.min(tx);
let mut x1 = 0.0f64.max(tx);
let y0 = rise + 0.0f64.min(ty);
let y1 = rise + 0.0f64.max(ty) + size;
if x1 <= x0 {
// Vertical and empty runs have no horizontal displacement but
// still occupy roughly an em in width.
x1 = x0 + size;
}
let matrix = self.text_matrix().then(self.gs.ctm);
let mut bounds: Option<Rect> = None;
for (x, y) in [(x0, y0), (x1, y0), (x0, y1), (x1, y1)] {
let corner = matrix.apply(Point { x, y });
if !corner.x.is_finite() || !corner.y.is_finite() {
return None;
}
let point = Rect {
x0: corner.x,
y0: corner.y,
x1: corner.x,
y1: corner.y,
};
bounds = Some(bounds.map_or(point, |bbox| bbox.union(point)));
}
bounds.map(Rect::normalized)
}
/// Visibility of a `/OC` value (an OCG or OCMD, usually by reference)
/// under the document's default configuration. Anything unresolvable or
/// unconfigured is visible — default-visibility semantics
/// (cpdf_occontext.cpp).
fn oc_value_visible(&mut self, value: &PdfObject) -> bool {
let id = value.as_reference();
let Some(resolved) = self.resolve_obj(value) else {
return true;
};
let Some(dict) = resolved.as_dict() else {
return true;
};
let type_is_ocmd = dict
.get(self.names.known.type_)
.and_then(PdfObject::as_name)
.is_some_and(|n| self.names.resolve(n).as_ref() == b"OCMD");
if type_is_ocmd {
// Membership dictionary: visible if ANY listed OCG is on (the
// /P /AnyOn default; the simple /VE Any policy). No /OCGs →
// visible.
let Some(ocgs_raw) = dict.get(self.intern(b"OCGs")).cloned() else {
return true;
};
let mut ids: Vec<ObjectId> = Vec::new();
match &ocgs_raw {
PdfObject::Reference(_) => {
// A single OCG ref, or a ref to the array itself.
if let Some(arr) = self.resolve_obj(&ocgs_raw)
&& let PdfObject::Array(items) = &*arr
{
ids.extend(items.iter().filter_map(PdfObject::as_reference));
} else if let Some(id) = ocgs_raw.as_reference() {
ids.push(id);
}
}
PdfObject::Array(items) => {
ids.extend(items.iter().filter_map(PdfObject::as_reference));
}
_ => {}
}
if ids.is_empty() {
return true;
}
return ids.iter().any(|id| self.snapshot.ocg_visible(*id));
}
// A plain OCG: identity is its object id (matching /ON //OFF refs);
// a direct dictionary has none and cannot be configured off.
id.is_none_or(|id| self.snapshot.ocg_visible(id))
}
fn intern_path(&mut self, path: PathData) -> PathId {
let id = PathId(self.paths.len() as u32);
self.paths.push(path);
id
}
// --- text --------------------------------------------------------------
fn text_move(&mut self, tx: f64, ty: f64) {
let t = Matrix::translate(tx, ty);
let text = self.text_object();
text.line_matrix = t.then(text.line_matrix);
text.matrix = text.line_matrix;
}
fn op_set_font(&mut self) {
// Operands: /Name size
let size = self.last_num().unwrap_or(0.0);
let Some(name) = self
.operands
.iter()
.find_map(Operand::as_name)
.map(|b| b.to_vec())
else {
return;
};
let font = self.lookup_font(&name);
self.gs.font = Some(font);
self.gs.font_size = size;
}
fn op_show_array(&mut self) {
let Some(array) = self.operands.last().and_then(Operand::as_array) else {
return;
};
let mut elements = Vec::new();
for item in array {
match item {
Operand::String(s) => elements.push(TextElement::Show(s.clone())),
other => {
if let Some(n) = other.as_f64() {
elements.push(TextElement::Adjust(n));
}
}
}
}
self.emit_text_run(elements);
}
fn emit_text_run(&mut self, elements: Vec<TextElement>) {
let Some(font) = self.gs.font else {
// Showing text with no selected font: nothing placeable.
return;
};
self.text_object();
// One `Vec` -> `Arc` move; the run and the Type 3 path below then
// share the elements instead of each holding a full copy.
let elements: std::sync::Arc<[TextElement]> = elements.into();
let type3 = self.fonts[font.index()].subtype == b"Type3";
let visible = !self.oc_hidden();
let run = TextRun {
font,
font_size: self.gs.font_size,
render_mode: self.gs.render_mode,
char_spacing: self.gs.char_spacing,
word_spacing: self.gs.word_spacing,
horizontal_scale: self.gs.horizontal_scale,
rise: self.gs.rise,
text_matrix: self.text_matrix(),
elements: std::sync::Arc::clone(&elements),
visible: visible && !type3,
actual_text: self.active_actual_text(),
};
let id = TextRunId(self.text_runs.len() as u32);
self.text_runs.push(run);
self.emit(SemanticOp::ShowText(id));
// The run-start text matrix is still in place (the advance below has
// not run yet), which is what the marked-content box needs.
self.marked_note_text_run(font, &elements);
// Type 3 glyphs paint through CharProc geometry. Keep the ShowText
// operation above for extraction, then use the established renderer
// path (which also advances the text matrix).
if type3 {
self.show_type3(font, &elements);
return;
}
if visible {
// Clip render modes (Tr 4 fill+clip, 5 stroke+clip, 6 fill+stroke+clip,
// 7 clip only) additionally add this run's glyph outlines to the text
// object's clipping path, flushed at `ET` (ISO 32000-1 §9.4.3). The
// `ShowText` above still carries the paint for modes 4–6; mode 7 paints
// nothing (skipped by the backend) but still contributes to the clip.
if matches!(self.gs.render_mode, 4 | 5 | 6 | 7) {
self.text_object().clip_runs.push(id);
}
}
// Advance the text line position by the run's total displacement, so a
// following show operator starts where this one ended (ISO 32000-1
// §9.4.4). Without it, consecutive `Tj`/`TJ` operators that rely on
// the viewer to advance (rather than repositioning with `Td`/`Tm`)
// pile every run onto the same origin.
let (tx, ty) = self.text_displacement(font, &elements);
if tx != 0.0 || ty != 0.0 {
self.advance_text(tx, ty);
}
}
/// A run's total displacement in text space: the running sum of glyph
/// advances — width·Tfs/1000 + Tc (+ Tw for a word-spacing code) — plus
/// the explicit `TJ` adjustments (−n/1000·Tfs), all scaled by Th. This
/// mirrors `lower::placed_glyphs`, which lays out glyphs *within* a run
/// from the same quantities.
fn text_displacement(&self, font: FontId, elements: &[TextElement]) -> (f64, f64) {
let th = self.gs.horizontal_scale / 100.0;
let fs = self.gs.font_size;
let metrics = self.fonts[font.index()].metrics.clone();
// Vertical writing (wmode 1): displacement runs along −y using the
// `/W2`//`/DW2` metrics, and neither the advance nor the `TJ`
// adjustments are scaled by Th (which only scales horizontally —
// §9.4.4 "in vertical writing mode, tx = 0, ty = …").
let vertical = metrics.is_vertical();
let (mut tx, mut ty) = (0.0f64, 0.0f64);
for e in elements.iter() {
match e {
TextElement::Show(bytes) => {
for dc in metrics.decode(bytes.as_slice()) {
let word = if dc.word_space {
self.gs.word_spacing
} else {
0.0
};
if let Some(vp) = vertical.then(|| metrics.vertical(dc.cid)).flatten() {
let w1 = vp.advance as f64 / 1000.0 * fs;
ty += w1 + self.gs.char_spacing + word;
} else {
let w = dc.advance as f64 / 1000.0 * fs;
tx += (w + self.gs.char_spacing + word) * th;
}
}
}
TextElement::Adjust(n) => {
if vertical {
ty += -n / 1000.0 * fs;
} else {
tx += -n / 1000.0 * fs * th;
}
}
}
}
(tx, ty)
}
/// Show a run of Type 3 text: execute each code's CharProc content stream
/// inline (bracketed by Save/Concat/Restore, like a form), then advance the
/// text matrix by the glyph's width (ISO 32000-1 §9.6.5).
///
/// The rendering matrix for a glyph is `FontMatrix × Trm`, where `Trm` is
/// the text-space→user-space matrix `[Tfs·Th 0 0 Tfs 0 Ts] × Tm`; the
/// ambient CTM is carried by the surrounding `Concat` scope, so the Concat
/// we emit is only the glyph-space→current-user-space part.
fn show_type3(&mut self, font: FontId, elements: &[TextElement]) {
let resource_name = self.fonts[font.index()].resource_name;
let Some(t3) = self.type3_cache.get(&resource_name).cloned().flatten() else {
// A Type 3 font whose CharProcs/FontMatrix could not be parsed:
// there is nothing placeable and no width data to advance by.
return;
};
let tfs = self.gs.font_size;
let th = self.gs.horizontal_scale / 100.0;
let trise = self.gs.rise;
let tc = self.gs.char_spacing;
let tw = self.gs.word_spacing;
// Render modes 3 (invisible) and 7 (clip-only) place no marks but still
// advance the text position; so does an OC-hidden span.
let invisible = self.gs.render_mode == 3 || self.gs.render_mode == 7 || self.oc_hidden();
let fm = t3.font_matrix;
let param = Matrix {
a: tfs * th,
b: 0.0,
c: 0.0,
d: tfs,
e: 0.0,
f: trise,
};
for element in elements {
match element {
TextElement::Adjust(n) => {
// A TJ adjustment moves the next glyph; thousandths of a
// text-space unit, negative moves forward.
let adj = -n / 1000.0 * tfs * th;
self.advance_text(adj, 0.0);
}
TextElement::Show(bytes) => {
for &code in bytes.iter() {
// Glyph space → current user space (CTM applied by the
// enclosing scope): FontMatrix, then the text params,
// then the current text matrix.
let concat = fm.then(param).then(self.text_matrix());
let mut d_width = None;
if !invisible {
if let Some(char_proc) = t3.char_procs[code as usize].clone() {
d_width = self.exec_char_proc(
char_proc.object,
&char_proc.stream,
concat,
t3.resources.clone(),
);
} else {
self.ctx.note_recovery(format!(
"Type 3 glyph for code {code} has no CharProc; advancing only"
));
}
}
// Advance: `/Widths` is authoritative (what viewers
// use); the `d0`/`d1` `wx` is a fallback when it is
// absent. Widths are in glyph space, so the horizontal
// text-space advance is `FontMatrix.a · wx`.
let wx = if t3.has_widths {
t3.widths[code as usize]
} else {
d_width.unwrap_or(0.0)
};
let w0 = fm.a * wx;
let mut adv = w0 * tfs + tc;
// Word spacing applies to the single-byte code 32.
if code == 32 {
adv += tw;
}
adv *= th;
self.advance_text(adv, 0.0);
}
}
}
}
}
/// Execute one Type 3 CharProc content stream inline, bracketed by
/// Save/Concat/Restore. Returns the `wx` from a leading `d0`/`d1`, if any
/// (an advance fallback). Recursion-guarded by the shared invoke depth so a
/// glyph that shows its own font terminates.
fn exec_char_proc(
&mut self,
object: Option<ObjectId>,
stream: &PdfStream,
concat: Matrix,
resources: Option<Arc<PdfObject>>,
) -> Option<f64> {
if self.invoke_depth >= self.limits.max_invoke_depth {
self.ctx
.note_recovery("Type 3 glyph exceeded recursion depth; glyph skipped".to_string());
return None;
}
let content = match self.snapshot.decode_stream_data(stream, self.ctx) {
Ok(c) => c,
Err(_) => {
self.ctx
.note_recovery("Type 3 CharProc stream undecodable; glyph skipped".to_string());
return None;
}
};
let frame = self.enter_nested_stream(resources, concat);
self.type3_shape_only = false;
self.type3_nesting += 1;
// 3. Execute (a malformed CharProc is a skipped glyph, never fatal).
let trace_saved = self.trace_enter(TraceFrameKind::Type3Glyph, object);
self.emit(SemanticOp::BeginPaintOrigin(PaintOrigin::Type3Glyph));
if let Err(e) = self.run(&content) {
self.ctx
.note_recovery(format!("Type 3 CharProc aborted: {e}"));
}
self.emit(SemanticOp::EndPaintOrigin);
self.trace_exit(trace_saved);
self.type3_nesting -= 1;
let captured = self.type3_d_width;
self.leave_nested_stream(frame, false);
captured
}
/// Parse a `/Type3` font dictionary into a reusable [`Type3Font`]: its
/// FontMatrix, CharProc execution resources, per-code CharProc streams
/// (resolved through `/Encoding` + `/Differences`), and per-code glyph-space
/// widths (ISO 32000-1 §9.6.5).
fn build_type3(&mut self, dict: &Dictionary) -> Option<Arc<Type3Font>> {
let font_matrix = read_matrix(dict, self.intern(b"FontMatrix"));
// CharProc execution uses the font's own /Resources, falling back to
// the resources active where the font is used.
let resources = match dict.get(self.intern(b"Resources")).cloned() {
Some(res) => self.resolve_obj(&res),
None => self.resources.clone(),
};
// Per-code glyph names come from /Encoding (/Differences overrides,
// else the base encoding's names). Type 3 goes code → NAME →
// /CharProcs, never through Unicode.
let (base, diffs) = self.read_encoding(dict, false, None);
// Widths are in glyph space (NOT divided by 1000).
let first_char = dict
.get(self.intern(b"FirstChar"))
.and_then(PdfObject::as_int)
.unwrap_or(0);
let width_vals: Vec<f64> = match dict.get(self.intern(b"Widths")).cloned() {
Some(w) => match self.resolve_obj(&w).as_deref() {
Some(PdfObject::Array(items)) => {
items.iter().map(|it| self.number_or_resolved(it)).collect()
}
_ => Vec::new(),
},
None => Vec::new(),
};
let has_widths = !width_vals.is_empty();
let mut widths = [0.0f64; 256];
for (i, w) in width_vals.iter().enumerate() {
let code = first_char + i as i64;
if (0..256).contains(&code) {
widths[code as usize] = *w;
}
}
// Resolve each code's CharProc content stream once.
let char_procs_dict = dict
.get(self.intern(b"CharProcs"))
.cloned()
.and_then(|c| self.resolve_obj(&c))
.and_then(|o| o.as_dict().cloned());
let mut char_procs: [Option<CharProc>; 256] = std::array::from_fn(|_| None);
if let Some(cp) = char_procs_dict {
for code in 0u32..256 {
let name = diffs
.get(&(code as u8))
.map(|n| n.as_slice())
.or_else(|| crate::font::builtin_glyph_name(base, code as u8));
let Some(name) = name else { continue };
let nid = self.intern(name);
let Some(entry) = cp.get(nid).cloned() else {
continue;
};
if let Some(obj) = self.resolve_obj(&entry)
&& let PdfObject::Stream(s) = &*obj
{
char_procs[code as usize] = Some(CharProc {
object: entry.as_reference(),
stream: s.clone(),
});
}
}
}
Some(Arc::new(Type3Font {
font_matrix,
resources,
char_procs,
widths,
has_widths,
}))
}
fn lookup_font(&mut self, name: &[u8]) -> FontId {
let nid = self.intern(name);
if let Some(fid) = self.font_cache.get(&nid) {
return *fid;
}
let sem_font = self.resolve_font(nid);
let fid = FontId(self.fonts.len() as u32);
self.fonts.push(sem_font);
self.font_cache.insert(nid, fid);
fid
}
/// Best-effort resolution of a font resource into a [`SemFont`]. Any
/// failure degrades to an unresolved descriptor rather than aborting the
/// page (a missing font must not blank the whole page).
fn resolve_font(&mut self, name: NameId) -> SemFont {
let mut sem = SemFont {
resource_name: name,
object: None,
subtype: Vec::new(),
base_font: Vec::new(),
metrics: Arc::new(crate::font::FontMetrics::Simple(
crate::font::SimpleWidths::empty(),
)),
program: None,
face_index: 0,
glyph_map: Arc::new(crate::font::GlyphMap::Identity),
synthesis: crate::font::Synthesis::default(),
unicode_map: Arc::new(crate::font::UnicodeMap::new()),
charset: crate::font::Charset::Ansi,
font_bbox: None,
type3_matrix: None,
};
let Some(font_dict) = self.resource_subdict(self.names.known.font) else {
return sem;
};
let Some(entry) = font_dict.as_dict().and_then(|d| d.get(name)).cloned() else {
return sem;
};
sem.object = entry.as_reference();
let Some(font_obj) = self.resolve_obj(&entry) else {
return sem;
};
let Some(dict) = font_obj.as_dict() else {
return sem;
};
// Everything below depends only on the font dictionary object (and the
// system-font provider for substitution), never on the page, so a font
// reached by reference is resolved once per document and reused by
// every later page compile — the per-page interpreter otherwise
// re-inflates and re-parses each embedded program on every page.
let cache_key = sem.object.map(|object| FontCacheKey {
object,
provider: self.system_fonts_identity(),
});
// Resolve each font once per document even when several compile
// workers reach it at the same time: the slot's lock makes the
// second worker wait for the first worker's result instead of
// redoing the parse. Pipelines start every compile worker on a
// different page of the same book at once, so without this the
// first N pages each paid the full resolution for the same fonts.
// Type 3 fonts are never cached (see `FontResourceCache`), so they
// take no slot and never wait on one.
if let Some(sub) = dict
.get(self.names.known.subtype)
.and_then(PdfObject::as_name)
{
sem.subtype = self.names.resolve(sub).to_vec();
}
let slot = cache_key
.as_ref()
.filter(|_| sem.subtype != b"Type3")
.map(|key| self.font_resources.slot(key.clone()));
let _resolving = match &slot {
Some(slot) => {
if let Some(cached) = slot.get() {
let mut sem = SemFont::clone(cached);
sem.resource_name = name;
return sem;
}
let guard = slot.resolving();
if let Some(cached) = slot.get() {
let mut sem = SemFont::clone(cached);
sem.resource_name = name;
return sem;
}
Some(guard)
}
None => None,
};
let base_key = self.intern(b"BaseFont");
if let Some(base) = dict.get(base_key).and_then(PdfObject::as_name) {
sem.base_font = self.names.resolve(base).to_vec();
}
sem.font_bbox = self.resolve_font_bbox(dict, sem.subtype == b"Type0");
let mut unicode_map = self.to_unicode_map(dict);
// Type 3: no outline program. Parse the CharProcs/FontMatrix/Encoding/
// Widths into a side table keyed by resource name; showing text draws
// each glyph's content stream inline (§9.6.5). The SemFont stays
// program-less — nothing places it as a glyph run.
if sem.subtype == b"Type3" {
self.fill_simple_unicode_map(dict, None, &mut unicode_map);
sem.unicode_map = Arc::new(unicode_map);
let t3 = self.build_type3(dict);
if let Some(type3) = &t3 {
sem.type3_matrix = Some(type3.font_matrix);
let widths = type3
.widths
.iter()
.map(|width| (width * type3.font_matrix.a * 1000.0) as f32)
.collect();
sem.metrics = Arc::new(crate::font::FontMetrics::Simple(
crate::font::SimpleWidths::new(0, widths, 0.0),
));
}
self.type3_cache.insert(name, t3);
return sem;
}
// Advance metrics: two-byte Identity CID for Type 0, else simple.
if sem.subtype == b"Type0" {
// The `/Encoding` CMap decodes byte strings into CIDs. Identity-H/V
// (the dominant embedded-subset case) keeps the fast two-byte path;
// a predefined CJK CMap name or an embedded CMap stream routes
// through the CMap machinery (variable-width codes → CID).
let widths = self.build_cid_widths(dict);
let (cmap, vertical) = self.resolve_cid_encoding(dict);
sem.charset = self
.descendant_cidfont(dict)
.and_then(|font| font.as_dict().cloned())
.and_then(|font| self.cid_ordering(&font))
.map(|ordering| crate::font::Charset::from_ordering(&ordering))
.filter(|charset| charset.is_cjk())
.unwrap_or_else(|| crate::font::Charset::from_font_name(&sem.base_font));
sem.metrics = Arc::new(if vertical {
// Writing mode 1 (`Identity-V` or a `/WMode 1` CMap): decode
// as usual, lay out along −y with the `/W2`//`/DW2` metrics.
crate::font::FontMetrics::CidVertical {
widths,
vertical: self.build_cid_vertical(dict),
cmap,
}
} else {
match cmap {
Some(cmap) => crate::font::FontMetrics::CidCMap { widths, cmap },
None => crate::font::FontMetrics::CidIdentity(widths),
}
});
let (program, cid_to_gid, face_index) = self.build_cid_program(dict);
sem.program = program;
sem.face_index = face_index;
sem.glyph_map = Arc::new(crate::font::GlyphMap::Cid(cid_to_gid));
} else {
// Simple font: resolve code→GID through the encoding and a font
// program — the embedded one, or a bundled standard face chosen
// by substitution (fonts.md Font Phase 3).
let embedded = self.embedded_program(dict).and_then(|bytes| {
crate::font::FontProgram::parse(bytes.clone()).map(|p| (bytes, p))
});
let resolved = match embedded {
Some((bytes, prog)) => Some((bytes, prog, None, 0)),
None => {
let charset = crate::font::Charset::from_font_name(&sem.base_font);
self.substitute_font(dict, &sem.base_font, charset)
.map(|s| {
// A bundled substitute may lack the requested cut
// (Symbol/ZapfDingbats): record what to synthesize.
if !s.system {
sem.synthesis =
crate::font::synthesis(s.face, s.want_bold, s.want_italic);
}
(s.bytes, s.program, Some(s.face), s.face_index)
})
}
};
let widths = self.build_simple_widths(dict);
if let Some((bytes, prog, face, face_index)) = resolved {
self.fill_simple_unicode_map(dict, face, &mut unicode_map);
let table = self.build_simple_gids(dict, &prog, face);
// Last-resort Unicode: reverse the embedded cmap for any
// code the encoding left unmapped (a symbolic Latin subset
// with no /Encoding and no /ToUnicode —
// PLAN-TEXT-EXTRACTION §5.2 step 4).
self.fill_program_cmap_unicode(&prog, &table, &mut unicode_map);
// A font with no /Widths uses the standard-14 metrics
// (§9.6.2.1); the bundled faces are metric-compatible, so
// their own advances are those metrics.
if !widths.has_widths() && face.is_some() {
sem.metrics = Arc::new(crate::font::FontMetrics::Simple(standard_widths(
&prog, &table,
)));
} else {
sem.metrics = Arc::new(crate::font::FontMetrics::Simple(widths));
}
sem.program = Some(bytes);
sem.face_index = face_index;
sem.glyph_map = Arc::new(crate::font::GlyphMap::Simple(table));
} else {
self.fill_simple_unicode_map(dict, None, &mut unicode_map);
sem.metrics = Arc::new(crate::font::FontMetrics::Simple(widths));
}
}
sem.unicode_map = Arc::new(unicode_map);
if let (Some(key), Some(slot)) = (cache_key, &slot) {
self.font_resources.insert(key, slot, &sem);
}
sem
}
/// Identity of the system-font provider for the resolved-font cache key: a
/// substituted font depends on which provider answered, so two compilers
/// with different providers must not share entries.
fn system_fonts_identity(&self) -> usize {
self.system_fonts
.as_ref()
.map_or(0, |provider| Arc::as_ptr(provider) as *const () as usize)
}
fn resolve_font_bbox(&mut self, font: &Dictionary, composite: bool) -> Option<[f64; 4]> {
let target = if composite {
self.descendant_cidfont(font)?
} else {
Arc::new(PdfObject::Dictionary(Arc::new(font.clone())))
};
let target = target.as_dict()?;
if let Some(bounds) = read_rect(target, self.intern(b"FontBBox")) {
return Some(bounds);
}
let descriptor = target.get(self.intern(b"FontDescriptor"))?.clone();
let descriptor = self.resolve_obj(&descriptor)?;
read_rect(descriptor.as_dict()?, self.intern(b"FontBBox"))
}
/// Resolve and parse the font's `/ToUnicode` stream while the snapshot is
/// available. The semantic page owns the result and never borrows the
/// document.
fn to_unicode_map(&mut self, dict: &Dictionary) -> crate::font::UnicodeMap {
let key = self.intern(b"ToUnicode");
let Some(value) = dict.get(key).cloned() else {
return crate::font::UnicodeMap::new();
};
let Some(object) = self.resolve_obj(&value) else {
return crate::font::UnicodeMap::new();
};
let PdfObject::Stream(stream) = &*object else {
return crate::font::UnicodeMap::new();
};
self.snapshot
.decode_stream_data(stream, self.ctx)
.ok()
.and_then(|bytes| crate::font::parse_to_unicode(&bytes))
.unwrap_or_default()
}
/// Complete a simple font's Unicode map from `/Encoding` and glyph names.
/// Existing `/ToUnicode` entries remain authoritative.
fn fill_simple_unicode_map(
&mut self,
dict: &Dictionary,
face: Option<crate::font::StandardFont>,
map: &mut crate::font::UnicodeMap,
) {
let symbolic = self.font_is_symbolic(dict);
let builtin = match face {
Some(crate::font::StandardFont::Symbol) => Some(crate::font::BaseEncoding::SymbolFont),
Some(crate::font::StandardFont::ZapfDingbats) => {
Some(crate::font::BaseEncoding::ZapfDingbats)
}
_ => None,
};
let (base, differences) = self.read_encoding(dict, symbolic, builtin);
for code in 0u16..=255 {
let code = code as u8;
let named = differences
.get(&code)
.map(Vec::as_slice)
.or_else(|| crate::font::builtin_glyph_name(base, code));
let unicode = named
.and_then(crate::font::glyph_name_to_char)
.or_else(|| base.to_char(code));
if let Some(ch) = unicode {
let mut encoded = [0u16; 2];
let units = ch.encode_utf16(&mut encoded);
map.insert_if_absent(
code as u32,
Arc::<[u16]>::from(units),
crate::font::UnicodeSource::SimpleEncoding,
);
}
}
}
/// Fill any still-unmapped code from the embedded font program's cmap,
/// reversed (PLAN-TEXT-EXTRACTION §5.2 step 4). `/ToUnicode` and the
/// simple-encoding pass keep priority (`insert_if_absent`); this only
/// rescues a font that names no usable encoding — the common Office
/// "symbolic" Latin TrueType subset, whose `(3,0)` cmap still carries
/// the glyph identities.
fn fill_program_cmap_unicode(
&self,
prog: &crate::font::FontProgram,
table: &[u32; 256],
map: &mut crate::font::UnicodeMap,
) {
for code in 0u32..256 {
if map.get(code).is_some() {
continue;
}
let gid = table[code as usize];
if gid == 0 {
continue;
}
if let Some(ch) = prog.char_for_gid(gid) {
let mut buf = [0u16; 2];
let units = ch.encode_utf16(&mut buf);
map.insert_if_absent(
code,
Arc::<[u16]>::from(&units[..]),
crate::font::UnicodeSource::FontProgram,
);
}
}
}
/// Build a simple font's 256-entry code→GID table from its `/Encoding`
/// (base + `/Differences`) resolved through the embedded program's cmap.
fn build_simple_gids(
&mut self,
dict: &Dictionary,
prog: &crate::font::FontProgram,
face: Option<crate::font::StandardFont>,
) -> Box<[u32; 256]> {
let symbolic = self.font_is_symbolic(dict);
// A substituted symbolic face brings its own built-in encoding.
let builtin = match face {
Some(crate::font::StandardFont::Symbol) => Some(crate::font::BaseEncoding::SymbolFont),
Some(crate::font::StandardFont::ZapfDingbats) => {
Some(crate::font::BaseEncoding::ZapfDingbats)
}
_ => None,
};
let (base, differences) = self.read_encoding(dict, symbolic, builtin);
let mut table = Box::new([0u32; 256]);
for code in 0u32..256 {
// A glyph name is authoritative: look it up in the font's `post`
// names first (exact, and the only route for glyphs with no
// Unicode), then fall back to name→Unicode→cmap. The name comes
// from /Differences, else from a symbolic face's built-in
// encoding.
let named = differences
.get(&(code as u8))
.map(|n| n.as_slice())
.or_else(|| crate::font::builtin_glyph_name(base, code as u8));
let by_name = named.and_then(|n| prog.gid_for_name(n));
let ch = named
.and_then(crate::font::glyph_name_to_char)
.or_else(|| base.to_char(code as u8));
let gid = by_name.or_else(|| match ch {
Some(c) => prog
.gid_for_char(c)
.or_else(|| symbolic.then(|| prog.gid_for_code(code as u8)).flatten()),
None => symbolic.then(|| prog.gid_for_code(code as u8)).flatten(),
});
table[code as usize] = gid.unwrap_or(0);
}
table
}
/// A font is symbolic if its descriptor `/Flags` has the Symbolic bit (4).
/// Pick a bundled standard face for a font the document did not embed
/// (fonts.md Font Phase 3). Returns its bytes and parsed program.
///
/// Substitution never fails, so non-embedded text renders as glyphs
/// rather than placement boxes; only an unparseable bundled face (a
/// build error) falls through to `None`.
fn substitute_font(
&mut self,
dict: &Dictionary,
base_font: &[u8],
charset: crate::font::Charset,
) -> Option<Substituted> {
let descriptor = dict
.get(self.intern(b"FontDescriptor"))
.cloned()
.and_then(|d| self.resolve_obj(&d))
.and_then(|d| d.as_dict().cloned());
let num = |d: &Dictionary, key: &[u8], this: &mut Self| -> Option<f64> {
d.get(this.intern(key)).and_then(PdfObject::as_number)
};
let (flags, stem_v, italic_angle) = match &descriptor {
Some(d) => (
num(d, b"Flags", self).map(|f| f as u32),
num(d, b"StemV", self),
num(d, b"ItalicAngle", self),
),
None => (None, None, None),
};
let (face, want_bold, want_italic) =
crate::font::substitute_with_style(crate::font::SubstitutionRequest {
base_font,
flags,
stem_v,
italic_angle,
});
// An installed font that actually answers to this name beats a
// metric-compatible stand-in — and is the only way to cover CJK or a
// face outside the standard 14. Falls through to the bundled face.
if let Some(found) = self.system_font_for(base_font, face, flags, italic_angle, charset) {
return Some(found);
}
let bytes = face.program_data();
let program = crate::font::FontProgram::parse(bytes.clone())?;
Some(Substituted {
bytes,
program,
face,
want_bold,
want_italic,
face_index: 0,
system: false,
})
}
/// Ask the injected system-font provider for `base_font`.
///
/// Returns the bundled `face` alongside, since the caller still needs it
/// to know whether a symbolic built-in encoding applies.
fn system_font_for(
&mut self,
base_font: &[u8],
face: crate::font::StandardFont,
flags: Option<u32>,
italic_angle: Option<f64>,
charset: crate::font::Charset,
) -> Option<Substituted> {
let provider = self.system_fonts.clone()?;
let flags = flags.unwrap_or(0);
let found = provider.lookup(&crate::font::SystemFontRequest {
family: crate::font::strip_subset_tag(base_font),
bold: face.is_bold(),
italic: face.is_italic() || italic_angle.is_some_and(|a| a != 0.0),
serif: flags & 0x2 != 0,
fixed_pitch: flags & 0x1 != 0,
charset,
})?;
// Face index matters: the CJK families ship as .ttc collections.
let program = crate::font::FontProgram::parse_indexed(found.data.clone(), found.index)?;
// A system-provider face was selected BY the requested style, so
// nothing is synthesized for it.
Some(Substituted {
bytes: found.data,
program,
face,
want_bold: face.is_bold(),
want_italic: face.is_italic(),
face_index: found.index,
system: true,
})
}
fn font_is_symbolic(&mut self, dict: &Dictionary) -> bool {
dict.get(self.intern(b"FontDescriptor"))
.cloned()
.and_then(|d| self.resolve_obj(&d))
.and_then(|d| {
d.as_dict()
.and_then(|d| d.get(self.intern(b"Flags")))
.and_then(PdfObject::as_int)
})
.map(|f| f & 0x4 != 0)
.unwrap_or(false)
}
/// Read `/Encoding`: a named base, or a dictionary with `/BaseEncoding` and
/// a `/Differences` array (code → glyph name overrides).
/// `(base encoding, /Differences)` for a simple font. `builtin` is the
/// encoding to assume when the font names none — for a substituted
/// Symbol/ZapfDingbats face that is the face's own table (Annex D),
/// which is the only way its codes reach glyphs.
fn read_encoding(
&mut self,
dict: &Dictionary,
symbolic: bool,
builtin: Option<crate::font::BaseEncoding>,
) -> (crate::font::BaseEncoding, HashMap<u8, Vec<u8>>) {
let default = builtin.unwrap_or(if symbolic {
crate::font::BaseEncoding::Symbolic
} else {
crate::font::BaseEncoding::Standard
});
let mut diffs: HashMap<u8, Vec<u8>> = HashMap::new();
let Some(enc) = dict.get(self.intern(b"Encoding")).cloned() else {
return (default, diffs);
};
let enc = match self.resolve_obj(&enc) {
Some(e) => e,
None => return (default, diffs),
};
match &*enc {
PdfObject::Name(n) => (
crate::font::BaseEncoding::from_name(&self.names.resolve(*n)).unwrap_or(default),
diffs,
),
PdfObject::Dictionary(ed) => {
let base = ed
.get(self.intern(b"BaseEncoding"))
.and_then(PdfObject::as_name)
.and_then(|n| crate::font::BaseEncoding::from_name(&self.names.resolve(n)))
.unwrap_or(default);
if let Some(PdfObject::Array(items)) = ed
.get(self.intern(b"Differences"))
.cloned()
.and_then(|d| self.resolve_obj(&d))
.as_deref()
{
let mut code = 0u32;
for item in items.iter() {
match item {
PdfObject::Integer(i) => code = (*i).max(0) as u32,
PdfObject::Name(n) => {
if code < 256 {
diffs.insert(code as u8, self.names.resolve(*n).to_vec());
}
code += 1;
}
_ => {}
}
}
}
(base, diffs)
}
_ => (default, diffs),
}
}
/// Load a composite font's embedded outline program (`/FontFile2` TrueType
/// or `/FontFile3` CFF/OpenType from the descendant CIDFont's descriptor)
/// and its `/CIDToGIDMap`.
/// `(program, CID→GID map, face index)` for a Type 0 font's descendant.
fn build_cid_program(
&mut self,
type0: &Dictionary,
) -> (Option<Arc<[u8]>>, crate::font::CidToGid, u32) {
let Some(cidfont) = self.descendant_cidfont(type0) else {
return (None, crate::font::CidToGid::Identity, 0);
};
let Some(dict) = cidfont.as_dict() else {
return (None, crate::font::CidToGid::Identity, 0);
};
let dict = &dict.clone();
// /CIDToGIDMap: /Identity (or absent) → Identity; a stream → the map.
// It is only meaningful for a CIDFontType2 (TrueType) descendant.
let mut cid_to_gid = match dict.get(self.intern(b"CIDToGIDMap")).cloned() {
Some(PdfObject::Name(_)) | None => crate::font::CidToGid::Identity,
Some(other) => match self.resolve_obj(&other).as_deref() {
Some(PdfObject::Stream(s)) => match self.snapshot.decode_stream_data(s, self.ctx) {
Ok(bytes) => crate::font::CidToGid::from_stream(&bytes),
Err(_) => crate::font::CidToGid::Identity,
},
_ => crate::font::CidToGid::Identity,
},
};
let program = self.embedded_program(dict);
if let Some(bytes) = &program {
// A CIDFontType0 descendant embeds a CID-keyed CFF, whose glyphs
// are addressed by GID while the PDF addresses them by CID. The
// CFF's charset is the only mapping between the two (/CIDToGIDMap
// is a CIDFontType2 feature), and it is *not* identity in a real
// subset font — so without this the text draws wrong glyphs or
// .notdef boxes.
let subtype = dict
.get(self.intern(b"Subtype"))
.and_then(PdfObject::as_name)
.map(|n| self.names.resolve(n).to_vec())
.unwrap_or_default();
if subtype == b"CIDFontType0"
&& let Some(map) = crate::font::cid_to_gid_from_cff(bytes)
{
cid_to_gid = map;
}
return (program, cid_to_gid, 0);
}
// Not embedded. A CID font's repertoire comes from /CIDSystemInfo;
// Adobe-Identity-0 says nothing (its CIDs are the original font's
// glyph ids), so fall back to any CMap name the producer left in
// /BaseFont — `DengXian-GBK-EUC-H-Identity-H` and friends.
let base_font = dict
.get(self.intern(b"BaseFont"))
.and_then(PdfObject::as_name)
.map(|n| self.names.resolve(n).to_vec())
.unwrap_or_default();
let charset = match self.cid_ordering(dict) {
Some(ordering) if crate::font::Charset::from_ordering(&ordering).is_cjk() => {
crate::font::Charset::from_ordering(&ordering)
}
_ => crate::font::Charset::from_font_name(&base_font),
};
match self.substitute_font(dict, &base_font, charset) {
Some(s) => {
// A substitute face indexes glyphs by its own cmap, not by the
// document's CIDs — an identity CID→GID into it draws
// arbitrary glyphs. For a known CJK charset resolved against
// an *installed* face (fonts.md Font Phase 7), bridge
// CID → Unicode (transcribed Adobe-*-UCS2 tables) → the
// face's charmap. Bundled faces are Latin-only, so the
// provider-off default is untouched.
if s.system
&& charset.is_cjk()
&& let Some(map) =
crate::font::CidToGid::from_unicode_bridge(charset, &s.program)
{
cid_to_gid = map;
}
(Some(s.bytes), cid_to_gid, s.face_index)
}
None => (None, cid_to_gid, 0),
}
}
/// Resolve a Type 0 font's `/Encoding` into the CMap that decodes its byte
/// strings into CIDs (ISO 32000-1 §9.7.5). Returns:
///
/// * `None` for `Identity-H`/`Identity-V` (code = CID, two bytes) — the
/// caller uses the fast [`FontMetrics::CidIdentity`] path.
/// * a **predefined** CMap for a known charset name (`GBK-EUC-H`,
/// `UniGB-UCS2-H`, `90ms-RKSJ-H`, …), ported from PDFium's tables.
/// * an **embedded** CMap parsed from an `/Encoding` stream (honoring an
/// in-stream `usecmap` of a predefined base).
///
/// An unrecognized name or an unparseable stream returns `None`; the caller
/// then falls back to Identity. A best-effort `/CIDSystemInfo /Ordering`
/// note is emitted so the residual is visible (predefined-name coverage is
/// PDFium-complete, so this fallback is rare).
///
/// The second return is the writing mode: `true` for vertical (wmode 1 —
/// `Identity-V`, a `-V` predefined CMap, or an embedded `/WMode 1` CMap).
fn resolve_cid_encoding(
&mut self,
type0: &Dictionary,
) -> (Option<Arc<crate::font::CMap>>, bool) {
let Some(resolved) = type0
.get(self.intern(b"Encoding"))
.cloned()
.and_then(|enc| self.resolve_obj(&enc))
else {
return (None, false);
};
match &*resolved {
PdfObject::Name(n) => {
let name = self.names.resolve(*n).to_vec();
if name == b"Identity-H" {
return (None, false);
}
if name == b"Identity-V" {
return (None, true);
}
match crate::font::predefined_cmap(&name) {
Some(cmap) => {
let vertical = cmap.wmode() == 1;
(Some(cmap), vertical)
}
None => {
let ordering = self.descendant_cidfont(type0).and_then(|c| {
c.as_dict()
.map(|d| d.clone())
.and_then(|d| self.cid_ordering(&d))
});
self.ctx.note_recovery(format!(
"unrecognized Type0 /Encoding /{} (Ordering {:?}); using Identity",
String::from_utf8_lossy(&name),
ordering.as_deref().map(String::from_utf8_lossy),
));
(None, false)
}
}
}
PdfObject::Stream(stream) => {
let cmap = self
.snapshot
.decode_stream_data(stream, self.ctx)
.ok()
.and_then(|bytes| crate::font::parse_embedded_cmap(&bytes));
match cmap {
Some(cmap) => {
let vertical = cmap.wmode() == 1;
(Some(Arc::new(cmap)), vertical)
}
None => {
self.ctx.note_recovery(
"embedded Type0 /Encoding CMap did not parse; using Identity".into(),
);
(None, false)
}
}
}
_ => (None, false),
}
}
/// `/CIDSystemInfo /Ordering` of a descendant CIDFont.
fn cid_ordering(&mut self, cidfont: &Dictionary) -> Option<Vec<u8>> {
let info = self.resolve_obj(&cidfont.get(self.intern(b"CIDSystemInfo"))?.clone())?;
let dict = info.as_dict()?;
match dict.get(self.intern(b"Ordering"))? {
PdfObject::String(s) => Some(s.as_bytes().to_vec()),
_ => None,
}
}
/// Resolve a Type 0 font's one descendant CIDFont dictionary.
fn descendant_cidfont(&mut self, type0: &Dictionary) -> Option<Arc<PdfObject>> {
let arr = self.resolve_obj(&type0.get(self.intern(b"DescendantFonts"))?.clone())?;
let first = match &*arr {
PdfObject::Array(items) => items.first()?.clone(),
_ => return None,
};
self.resolve_obj(&first)
}
/// Decode the `/FontFile2` or `/FontFile3` program from a font/CIDFont
/// dictionary's `/FontDescriptor`.
fn embedded_program(&mut self, dict: &Dictionary) -> Option<Arc<[u8]>> {
let descriptor = self.resolve_obj(&dict.get(self.intern(b"FontDescriptor"))?.clone())?;
let descriptor = descriptor.as_dict()?;
// /FontFile2 (TrueType) and /FontFile3 (CFF/OpenType) go to Skrifa;
// /FontFile is bare Type 1, which the native interpreter handles
// (fonts.md Font Phase 5). `FontProgram::parse` picks the engine.
let file = descriptor
.get(self.intern(b"FontFile2"))
.or_else(|| descriptor.get(self.intern(b"FontFile3")))
.or_else(|| descriptor.get(self.intern(b"FontFile")))?
.clone();
let obj = self.resolve_obj(&file)?;
let PdfObject::Stream(stream) = &*obj else {
return None;
};
let bytes = self.snapshot.decode_stream_data(stream, self.ctx).ok()?;
Some(Arc::from(bytes))
}
/// Read the descendant CIDFont's `/DW` + `/W` into CID advance widths.
fn build_cid_widths(&mut self, type0: &Dictionary) -> crate::font::CidWidths {
// /DescendantFonts is a one-element array of the CIDFont (usually a ref).
let Some(cidfont) = type0
.get(self.intern(b"DescendantFonts"))
.cloned()
.and_then(|d| self.resolve_obj(&d))
.and_then(|arr| match &*arr {
PdfObject::Array(items) => items.first().cloned(),
_ => None,
})
.and_then(|f| self.resolve_obj(&f))
else {
return crate::font::CidWidths::uniform(1000.0);
};
let Some(dict) = cidfont.as_dict() else {
return crate::font::CidWidths::uniform(1000.0);
};
let dict = dict.clone();
let dw = dict
.get(self.intern(b"DW"))
.cloned()
.and_then(|dw| self.resolve_obj(&dw))
.and_then(|dw| dw.as_number())
.unwrap_or(1000.0) as f32;
let ranges = match dict
.get(self.intern(b"W"))
.cloned()
.and_then(|w| self.resolve_obj(&w))
{
Some(w) => match &*w {
PdfObject::Array(items) => parse_cid_w(&self.resolve_metric_items(items)),
_ => Vec::new(),
},
None => Vec::new(),
};
crate::font::CidWidths::new(dw, ranges)
}
/// The elements of a `/W` or `/W2` array with their indirect references
/// resolved: the top-level entries, and the entries of each nested metrics
/// array. Acrobat's ClearScan fonts write `/W [0 885 0 R]`, the whole
/// per-CID width array behind a reference; left unresolved, the font has
/// no widths at all and every glyph takes `/DW`. A reference that does not
/// resolve is kept as it is, which the parsers skip.
fn resolve_metric_items(&mut self, items: &[PdfObject]) -> Vec<PdfObject> {
let mut resolve = |object: &PdfObject| -> PdfObject {
match object {
PdfObject::Reference(_) => self
.resolve_obj(object)
.map(|resolved| (*resolved).clone())
.unwrap_or_else(|| object.clone()),
direct => direct.clone(),
}
};
items
.iter()
.map(|item| match resolve(item) {
PdfObject::Array(inner)
if inner
.iter()
.any(|entry| matches!(entry, PdfObject::Reference(_))) =>
{
PdfObject::Array(inner.iter().map(&mut resolve).collect())
}
other => other,
})
.collect()
}
/// Read the descendant CIDFont's `/DW2` + `/W2` into vertical metrics
/// (ISO 32000-1 §9.7.4.3), mirroring [`Self::build_cid_widths`]. Spec
/// defaults (`/DW2 [880 −1000]`, `vx = w0/2`) when absent.
fn build_cid_vertical(&mut self, type0: &Dictionary) -> crate::font::CidVerticalMetrics {
let Some(cidfont) = self.descendant_cidfont(type0) else {
return crate::font::CidVerticalMetrics::default_metrics();
};
let Some(dict) = cidfont.as_dict() else {
return crate::font::CidVerticalMetrics::default_metrics();
};
let dict = dict.clone();
let (mut vy, mut w1y) = (880.0f32, -1000.0f32);
if let Some(dw2) = dict
.get(self.intern(b"DW2"))
.cloned()
.and_then(|d| self.resolve_obj(&d))
&& let PdfObject::Array(a) = &*dw2
{
let a = self.resolve_metric_items(a);
if let Some(v) = a.first().and_then(PdfObject::as_number) {
vy = v as f32;
}
if let Some(v) = a.get(1).and_then(PdfObject::as_number) {
w1y = v as f32;
}
}
let ranges = match dict
.get(self.intern(b"W2"))
.cloned()
.and_then(|w| self.resolve_obj(&w))
{
Some(w) => match &*w {
PdfObject::Array(items) => parse_cid_w2(&self.resolve_metric_items(items)),
_ => Vec::new(),
},
None => Vec::new(),
};
crate::font::CidVerticalMetrics::new(vy, w1y, ranges)
}
/// Read `/FirstChar` + `/Widths` (+ descriptor `/MissingWidth`) into a
/// simple-font advance table.
fn build_simple_widths(&mut self, dict: &Dictionary) -> crate::font::SimpleWidths {
let first_char = dict
.get(self.intern(b"FirstChar"))
.and_then(PdfObject::as_int)
.unwrap_or(0)
.max(0) as u32;
let widths = match dict.get(self.intern(b"Widths")).cloned() {
Some(w) => match self.resolve_obj(&w).as_deref() {
Some(PdfObject::Array(items)) => items
.iter()
.map(|it| self.number_or_resolved(it) as f32)
.collect(),
_ => Vec::new(),
},
None => Vec::new(),
};
// /MissingWidth lives on the font descriptor.
let missing = dict
.get(self.intern(b"FontDescriptor"))
.cloned()
.and_then(|d| self.resolve_obj(&d))
.and_then(|d| {
d.as_dict()
.and_then(|d| d.get(self.intern(b"MissingWidth")))
.and_then(PdfObject::as_number)
})
.unwrap_or(0.0) as f32;
crate::font::SimpleWidths::new(first_char, widths, missing)
}
/// A number, resolving an indirect reference (some producers store per-glyph
/// widths as references); non-numbers become 0.
fn number_or_resolved(&mut self, obj: &PdfObject) -> f64 {
if let Some(n) = obj.as_number() {
return n;
}
self.resolve_obj(obj)
.and_then(|o| o.as_number())
.unwrap_or(0.0)
}
// --- XObjects / inline images ------------------------------------------
/// `Do`: invoke an XObject. Form XObjects execute inline (their operations
/// flattened into this op stream, wrapped in Save/Concat/BBox-clip/Restore,
/// recursion-guarded); image XObjects emit a `DrawImage`.
fn op_do(&mut self) -> Result<(), ContentError> {
let Some(name) = self
.operands
.iter()
.rev()
.find_map(Operand::as_name)
.map(<[u8]>::to_vec)
else {
return Ok(());
};
let Some(xobjects) = self.resource_subdict(self.names.known.x_object) else {
return Ok(());
};
let Some(nid) = self.lookup_name(&name) else {
return Ok(());
};
let Some(entry) = xobjects.as_dict().and_then(|d| d.get(nid)).cloned() else {
return Ok(());
};
let obj_id = entry.as_reference();
let Some(xobj) = self.resolve_obj(&entry) else {
return Ok(());
};
let PdfObject::Stream(stream) = &*xobj else {
return Ok(());
};
let stream = stream.clone();
// Optional content: skip the XObject inside an OC-hidden span, and
// honor its own `/OC` membership (§8.11.3.3) — images and forms both.
if self.oc_hidden() {
return Ok(());
}
if let Some(oc) = stream.dict.get(self.intern(b"OC")).cloned()
&& !self.oc_value_visible(&oc)
{
return Ok(());
}
let subtype = stream
.dict
.get(self.names.known.subtype)
.and_then(PdfObject::as_name)
.map(|n| self.names.resolve(n));
match subtype.as_deref() {
Some(b"Image") => {
self.draw_image_xobject(obj_id, &stream);
Ok(())
}
// Treat a missing /Subtype as a form (tolerant); anything else is
// an XObject kind we do not model (PostScript), ignored.
Some(b"Form") | None => self.invoke_form(obj_id, &stream),
_ => Ok(()),
}
}
fn draw_image_xobject(&mut self, obj_id: Option<ObjectId>, stream: &PdfStream) {
if let Some(id) = obj_id
&& let Some(cached) = self.image_xobject_cache.get(&id)
{
let img = cached.clone();
let id = ImageId(self.images.len() as u32);
self.images.push(img);
self.emit(SemanticOp::DrawImage(id));
return;
}
let dict = &stream.dict;
let w_key = self.intern(b"Width");
let width = self.dict_int_indirect(dict, w_key).unwrap_or(0).max(0) as u32;
let h_key = self.intern(b"Height");
let height = self.dict_int_indirect(dict, h_key).unwrap_or(0).max(0) as u32;
let is_mask = dict_bool(dict, self.intern(b"ImageMask"));
let bpc_key = self.intern(b"BitsPerComponent");
let bpc = self
.dict_int_indirect(dict, bpc_key)
.map(|v| v.clamp(0, 255) as u8)
.unwrap_or(if is_mask { 1 } else { 0 });
let filters = dict
.get(self.names.known.filter)
.map(|f| self.filter_names(f))
.unwrap_or_default();
let interpolate = dict_bool(dict, self.intern(b"Interpolate"));
// Color space: absent for a stencil mask; else resolve the space.
self.image_cs_degraded = false;
self.image_cs_resource_relative = false;
let color_space = if is_mask {
None
} else {
dict.get(self.intern(b"ColorSpace"))
.cloned()
.and_then(|cs| self.resolve_image_colorspace(&cs))
.or(Some(crate::page_ir::ImageColorSpace::Gray))
};
let lowering_degraded = self.image_cs_degraded;
let decode = self.read_decode_array(dict);
// Decode through the general filters; a codec filter (DCT/JPX/
// JBIG2/CCITT) stops decoding and yields the encoded payload for
// the backend's codec registry.
let (samples, codec, codec_data) =
match self.snapshot.decode_stream_data_to_codec(stream, self.ctx) {
Ok((bytes, None)) => (Some(Arc::from(bytes)), None, None),
Ok((bytes, Some(name))) => (None, codec_kind(name.as_bytes()), Some(bytes.into())),
Err(_) => (None, None, None),
};
let smask = self.build_image_smask(dict);
// `/SMaskInData` (§7.4.7): a JPXDecode image's own opacity channel acts
// as a soft mask (1) or premultiplied opacity (2). Only honoured when
// there is no separate `/SMask` (which takes precedence).
let smask_in_data = if smask.is_some() {
0
} else {
dict_int(dict, self.intern(b"SMaskInData"))
.unwrap_or(0)
.clamp(0, 2) as u8
};
// `/SMask` overrides `/Mask` (§8.9.6.4 note); a stencil base image does
// its own masking. Otherwise resolve an explicit hard `/Mask`.
let mask = if smask.is_some() || is_mask {
None
} else {
self.build_image_mask(dict, color_space.as_ref(), bpc)
};
let codec_parms = codec.and_then(|_| self.read_codec_parms(dict));
// Spaces the per-texel sampler cannot express — Lab (needs the CIE
// conversion per sample, not an arity remap) and multi-input DeviceN
// (needs the n-input tint transform, no 1-D LUT) — are converted to
// plain RGB8 samples here, once, at compile time.
let (color_space, decode, samples, bpc) = if !is_mask
&& mask.is_none()
&& let Some(s) = &samples
&& let Some(cs_raw) = dict.get(self.intern(b"ColorSpace")).cloned()
&& let Some(rgb) = self.convert_special_image_samples(
&cs_raw,
s,
bpc,
width,
height,
decode.as_deref(),
) {
(
Some(crate::page_ir::ImageColorSpace::Rgb),
None,
Some(rgb),
8,
)
} else {
(color_space, decode, samples, bpc)
};
let img = SemImage {
object: obj_id,
width,
height,
bits_per_component: bpc,
is_mask,
filters,
inline_data: Vec::new(),
color_space,
interpolate,
decode,
samples,
codec,
codec_data,
codec_parms,
smask,
mask,
smask_in_data,
lowering_degraded,
};
if let Some(obj) = obj_id
&& !self.image_cs_resource_relative
{
self.image_xobject_cache.insert(obj, img.clone());
}
let id = ImageId(self.images.len() as u32);
self.images.push(img);
self.emit(SemanticOp::DrawImage(id));
}
/// Convert 8-bit image samples in a space the sampler cannot express to
/// packed RGB8, per sample, at compile time:
///
/// - **Lab**: each texel runs through the same `crate::color::lab_to_rgb`
/// the fill path uses (`/Decode` defaults to `[0 100]` for L* and the
/// space's `/Range` for a*/b*, §8.9.5.2), instead of the old
/// arity remap that read L*a*b* bytes as RGB.
/// - **Multi-input DeviceN** (n > 1 colorants with a buildable tint
/// transform): each texel's n tints run through `eval_tint`
/// (memoized on the raw sample tuple — scans carry few distinct
/// colors), instead of the `1 − max(tint)` grey fallback.
///
/// `None` (no conversion; caller keeps the arity approximation) for any
/// other family, non-8-bpc data, short buffers, or oversized images.
/// Parse an `/ICCBased` stream's profile into an sRGB transform, or `None`
/// when it is sRGB (nothing to do), not a matrix/TRC RGB profile, or
/// undecodable. Cached per stream: a document typically references one
/// profile from every image on every page.
fn icc_rgb_transform(
&mut self,
stream_obj: &PdfObject,
) -> Option<Arc<crate::color::icc::IccRgb>> {
let key = match stream_obj {
PdfObject::Reference(id) => Some(*id),
_ => None,
};
if let Some(id) = key
&& let Some(hit) = self.icc_cache.get(&id)
{
return hit.clone();
}
let resolved = self.resolve_obj(stream_obj)?;
let built = (|| {
let PdfObject::Stream(stream) = &*resolved else {
return None;
};
// Only 3-component profiles are in scope; /N is authoritative for
// arity per §8.6.5.5.
if dict_int(&stream.dict, self.intern(b"N")).unwrap_or(3) != 3 {
return None;
}
let bytes = self.snapshot.decode_stream_data(stream, self.ctx).ok()?;
crate::color::icc::IccRgb::from_profile(&bytes).map(Arc::new)
})();
if let Some(id) = key {
self.icc_cache.insert(id, built.clone());
}
built
}
/// Parse an `/ICCBased` **CMYK** stream (`/N 4`, CMYK-data/Lab-PCS lut) into
/// a CMYK→sRGB evaluator, cached per stream object. `None` when the stream
/// is not that shape (any other profile keeps the frozen-table arity
/// approximation).
fn cmyk_profile_from_stream(
&mut self,
stream_obj: &PdfObject,
) -> Option<Arc<crate::color::icc::IccCmyk>> {
let key = match stream_obj {
PdfObject::Reference(id) => Some(*id),
_ => None,
};
if let Some(id) = key
&& let Some(hit) = self.icc_cmyk_cache.get(&id)
{
return hit.clone();
}
let resolved = self.resolve_obj(stream_obj)?;
let built = (|| {
let PdfObject::Stream(stream) = &*resolved else {
return None;
};
if dict_int(&stream.dict, self.intern(b"N")).unwrap_or(4) != 4 {
return None;
}
let bytes = self.snapshot.decode_stream_data(stream, self.ctx).ok()?;
crate::color::icc::IccCmyk::from_cmyk_profile(&bytes).map(Arc::new)
})();
if let Some(id) = key {
self.icc_cmyk_cache.insert(id, built.clone());
}
built
}
fn cmyk_image_transform(
&mut self,
stream_obj: &PdfObject,
) -> Option<Arc<crate::page_ir::IccCmykTransform>> {
let key = match stream_obj {
PdfObject::Reference(id) => Some(*id),
_ => None,
};
if let Some(id) = key
&& let Some(hit) = self.icc_cmyk_image_cache.get(&id)
{
return hit.clone();
}
let built = self.cmyk_profile_from_stream(stream_obj).map(|profile| {
let (grid, input_tables, clut, output_tables) = profile.ir_tables();
Arc::new(crate::page_ir::IccCmykTransform {
grid,
input_tables,
clut,
output_tables,
})
});
if let Some(id) = key {
self.icc_cmyk_image_cache.insert(id, built.clone());
}
built
}
/// If a colour-space array `[/ICCBased stream]` names a CMYK press profile,
/// return its evaluator. Marks `uses_icc_color` for the feature flag.
fn iccbased_cmyk_from_items(
&mut self,
items: &[PdfObject],
) -> Option<Arc<crate::color::icc::IccCmyk>> {
let head = items.first().and_then(PdfObject::as_name)?;
if self.names.resolve(head).as_ref() != b"ICCBased" {
return None;
}
self.uses_icc_color = true;
self.cmyk_profile_from_stream(items.get(1)?)
}
/// The current resource dictionary's `/ColorSpace /DefaultCMYK` press
/// profile, if it declares one as an `/ICCBased` CMYK space. PDFium routes
/// DeviceCMYK content (the `k`/`K` operators and `/DeviceCMYK` images)
/// through this profile when present (ISO 32000-1 §8.6.5.6;
/// `CPDF_DocPageData::GetColorSpaceInternal`).
fn default_cmyk_profile(&mut self) -> Option<Arc<crate::color::icc::IccCmyk>> {
let did = self.intern(b"DefaultCMYK");
let entry = self
.resource_subdict(self.names.known.color_space)?
.as_dict()?
.get(did)?
.clone();
let resolved = self.resolve_obj(&entry)?;
let PdfObject::Array(items) = &*resolved else {
return None;
};
let items = items.to_vec();
self.iccbased_cmyk_from_items(&items)
}
/// The CMYK press profile a resource-named colour space `id` carries, when
/// it is an `[/ICCBased stream]` with a 4-input Lab lut. Cached parse via
/// [`Self::cmyk_profile_from_stream`].
fn iccbased_cmyk_space(&mut self, id: NameId) -> Option<Arc<crate::color::icc::IccCmyk>> {
let entry = self
.resource_subdict(self.names.known.color_space)?
.as_dict()?
.get(id)?
.clone();
let resolved = self.resolve_obj(&entry)?;
let PdfObject::Array(items) = &*resolved else {
return None;
};
let items = items.to_vec();
self.iccbased_cmyk_from_items(&items)
}
fn convert_special_image_samples(
&mut self,
cs_obj: &PdfObject,
samples: &Arc<[u8]>,
bpc: u8,
width: u32,
height: u32,
decode: Option<&[[f32; 2]]>,
) -> Option<Arc<[u8]>> {
const MAX_PIXELS: usize = 64 * 1024 * 1024;
if bpc != 8 {
return None;
}
let n_px = (width as usize).checked_mul(height as usize)?;
if n_px == 0 || n_px > MAX_PIXELS {
return None;
}
// Resolve a named resource / indirect reference down to the array.
let resolved = self.resolve_obj(cs_obj)?;
let items: Vec<PdfObject> = match &*resolved {
PdfObject::Array(a) => a.to_vec(),
PdfObject::Name(n) => {
let nid = *n;
let entry = self
.resource_subdict(self.names.known.color_space)?
.as_dict()?
.get(nid)?
.clone();
// Found in the page's resources (a device name never is).
self.image_cs_resource_relative = true;
match &*self.resolve_obj(&entry)? {
PdfObject::Array(a) => a.to_vec(),
_ => return None,
}
}
_ => return None,
};
let head = items.first().and_then(PdfObject::as_name)?;
match self.names.resolve(head).as_ref() {
// An `/ICCBased` RGB stream whose profile is not sRGB: the samples
// are encoded in *that* profile, and reading them as if they were
// already sRGB shifts the whole image. Convert once, here. The
// common sRGB profile yields no converter and falls through, so the
// usual case stays a pass-through.
b"ICCBased" => {
let stream = items.get(1)?;
// A 3-component matrix/TRC RGB profile (the common non-sRGB case).
if let Some(icc) = self.icc_rgb_transform(stream) {
let src = samples.get(..n_px.checked_mul(3)?)?;
let mut out = Vec::with_capacity(n_px * 3);
// `/Decode` is fixed for the whole image; resolve the three
// ranges once instead of walking the array three times per
// pixel.
let ranges: [[f32; 2]; 3] = std::array::from_fn(|c| {
decode.and_then(|d| d.get(c)).copied().unwrap_or([0.0, 1.0])
});
let dec = |c: usize, raw: u8| -> f32 {
let [lo, hi] = ranges[c];
lo + raw as f32 / 255.0 * (hi - lo)
};
for px in src.chunks_exact(3) {
let rgb = icc.to_srgb([dec(0, px[0]), dec(1, px[1]), dec(2, px[2])]);
for c in rgb {
out.push((c.clamp(0.0, 1.0) * 255.0).round() as u8);
}
}
return Some(Arc::from(out));
}
// A 4-component CMYK press profile: convert each texel through
// the lut, matching PDFium's LittleCMS image path. Only fires
// for non-codec (Flate/raw) CMYK samples; a CMYK JPEG decodes in
// the backend and keeps the frozen-table path. Memoised on the
// raw tuple — a one-time compile cost bounded by distinct inks.
let prof = self.cmyk_profile_from_stream(stream)?;
let src = samples.get(..n_px.checked_mul(4)?)?;
let mut memo: HashMap<[u8; 4], [u8; 3]> = HashMap::new();
let mut out = Vec::with_capacity(n_px * 3);
for px in src.chunks_exact(4) {
let key = [px[0], px[1], px[2], px[3]];
let rgb8 = *memo.entry(key).or_insert_with(|| {
let dec = |c: usize, raw: u8| -> f32 {
let [lo, hi] =
decode.and_then(|d| d.get(c)).copied().unwrap_or([0.0, 1.0]);
lo + raw as f32 / 255.0 * (hi - lo)
};
let rgb = prof.to_srgb([
dec(0, px[0]),
dec(1, px[1]),
dec(2, px[2]),
dec(3, px[3]),
]);
[
(rgb[0].clamp(0.0, 1.0) * 255.0).round() as u8,
(rgb[1].clamp(0.0, 1.0) * 255.0).round() as u8,
(rgb[2].clamp(0.0, 1.0) * 255.0).round() as u8,
]
});
out.extend_from_slice(&rgb8);
}
Some(Arc::from(out))
}
b"Lab" => {
let mut white_point = [1.0f32, 1.0, 1.0];
let mut range = [-100.0f32, 100.0, -100.0, 100.0];
if let Some(d) = items
.get(1)
.and_then(|d| self.resolve_obj(d))
.and_then(|d| d.as_dict().cloned())
{
for (key, out) in [
(&b"WhitePoint"[..], &mut white_point[..]),
(b"Range", &mut range[..]),
] {
if let Some(nid) = self.names.lookup(key)
&& let Some(PdfObject::Array(a)) = d.get(nid)
{
for (slot, item) in out.iter_mut().zip(a.iter()) {
if let Some(v) = item.as_number() {
*slot = v as f32;
}
}
}
}
}
// §8.9.5.2: the Decode default for a Lab image is
// [0 100 amin amax bmin bmax].
let default_decode: [[f32; 2]; 3] =
[[0.0, 100.0], [range[0], range[1]], [range[2], range[3]]];
// Fixed for the whole image: resolve once, not three times
// per pixel.
let ranges: [[f32; 2]; 3] = std::array::from_fn(|c| {
decode
.and_then(|d| d.get(c))
.copied()
.unwrap_or(default_decode[c])
});
let dec = |c: usize, raw: u8| -> f32 {
let [lo, hi] = ranges[c];
lo + raw as f32 / 255.0 * (hi - lo)
};
let src = samples.get(..n_px.checked_mul(3)?)?;
let mut out = Vec::with_capacity(n_px * 3);
for px in src.chunks_exact(3) {
let [r, g, b] = crate::color::lab_to_rgb(
dec(0, px[0]),
dec(1, px[1]),
dec(2, px[2]),
white_point,
range,
);
let to = |v: f32| (v.clamp(0.0, 1.0) * 255.0 + 0.5) as u8;
out.extend_from_slice(&[to(r), to(g), to(b)]);
}
Some(Arc::from(out))
}
b"DeviceN" => {
let space = self.build_tint_space_from_array(&items)?;
if space.inputs < 2 || space.func.is_none() {
return None; // 1-input takes the TintLut path; no func → arity approx
}
let n = space.inputs;
let src = samples.get(..n_px.checked_mul(n)?)?;
let dec = |c: usize, raw: u8| -> f64 {
match decode.and_then(|d| d.get(c)) {
Some([lo, hi]) => (*lo + raw as f32 / 255.0 * (hi - lo)) as f64,
None => raw as f64 / 255.0,
}
};
// Memoize on the raw tuple: real multi-colorant images carry
// few distinct ink combinations.
let mut memo: HashMap<Vec<u8>, [u8; 3]> = HashMap::new();
let mut out = Vec::with_capacity(n_px * 3);
let mut tints = vec![0.0f64; n];
for px in src.chunks_exact(n) {
let rgb = match memo.get(px) {
Some(rgb) => *rgb,
None => {
for (c, (t, raw)) in tints.iter_mut().zip(px.iter()).enumerate() {
*t = dec(c, *raw);
}
let rgb = sem_color_to_rgb8(&self.eval_tint(&space, &tints));
memo.insert(px.to_vec(), rgb);
rgb
}
};
out.extend_from_slice(&rgb);
}
Some(Arc::from(out))
}
_ => None,
}
}
/// Read a `/Decode` array into per-component `[min, max]` pairs.
fn read_decode_array(&mut self, dict: &Dictionary) -> Option<Vec<[f32; 2]>> {
// `/Decode` is frequently an *indirect* reference to the array (and,
// rarely, its elements are). `read_num_array` only matches a direct
// array, so resolve one level here first — otherwise an indirect
// `/Decode [1 0 …]` inversion is silently dropped and the image renders
// inverted (e.g. a dark scan meant to be shown light).
let raw = dict.get(self.intern(b"Decode"))?.clone();
let resolved = self.resolve_obj(&raw)?;
let PdfObject::Array(items) = &*resolved else {
return None;
};
let arr: Vec<f64> = items
.iter()
.filter_map(|it| match it {
PdfObject::Reference(_) => self.resolve_obj(it).and_then(|o| o.as_number()),
other => other.as_number(),
})
.collect();
Some(pairs_f32(arr))
}
/// Resolve an image `/ColorSpace` object into a device-family / Indexed
/// space; unrecognized spaces fall back to `None` (caller defaults to Gray).
fn resolve_image_colorspace(
&mut self,
obj: &PdfObject,
) -> Option<crate::page_ir::ImageColorSpace> {
self.resolve_image_colorspace_depth(obj, 0)
}
fn resolve_image_colorspace_depth(
&mut self,
obj: &PdfObject,
depth: u32,
) -> Option<crate::page_ir::ImageColorSpace> {
use crate::page_ir::ImageColorSpace as Cs;
if depth > self.limits.max_colorspace_depth {
return None;
}
let resolved = self.resolve_obj(obj)?;
match &*resolved {
PdfObject::Name(n) => {
let name = self.names.resolve(*n);
match name.as_ref() {
b"DeviceGray" | b"G" | b"CalGray" => Some(Cs::Gray),
b"DeviceRGB" | b"RGB" | b"CalRGB" | b"Lab" => Some(Cs::Rgb),
b"DeviceCMYK" | b"CMYK" => Some(Cs::Cmyk),
// A named resource space (`/CS0`): look it up and recurse.
_ => {
self.image_cs_resource_relative = true;
// Already an interned name: no lookup needed.
let nid = *n;
let entry = self
.resource_subdict(self.names.known.color_space)?
.as_dict()?
.get(nid)?
.clone();
self.resolve_image_colorspace_depth(&entry, depth + 1)
}
}
}
PdfObject::Array(items) => self.colorspace_from_array(items, depth),
_ => None,
}
}
fn colorspace_from_array(
&mut self,
items: &[PdfObject],
depth: u32,
) -> Option<crate::page_ir::ImageColorSpace> {
use crate::page_ir::ImageColorSpace as Cs;
let head = items.first()?.as_name()?;
match self.names.resolve(head).as_ref() {
b"ICCBased" => {
self.uses_icc_color = true;
let stream = self.resolve_obj(items.get(1)?)?;
let n = stream
.as_dict()
.and_then(|d| dict_int(d, self.intern(b"N")))
.unwrap_or(3);
Some(match n {
1 => Cs::Gray,
4 => match items
.get(1)
.and_then(|stream| self.cmyk_image_transform(stream))
{
Some(transform) => Cs::IccCmyk { transform },
None => Cs::Cmyk,
},
// A 3-component profile that is not sRGB is carried into the
// IR so the sampler can apply it; a *codec* image's samples
// cannot be converted at compile time the way directly
// decoded ones are. sRGB (the common case) yields no
// transform and stays plain Rgb.
_ => match items.get(1).and_then(|o| self.icc_rgb_transform(o)) {
Some(icc) => Cs::IccRgb {
trc: Arc::from(icc.trc_flat()),
matrix: icc.matrix(),
},
None => Cs::Rgb,
},
})
}
b"CalGray" => Some(Cs::Gray),
b"CalRGB" => Some(Cs::Rgb),
// `/Lab` image samples are L*a*b*, not RGB. The signed a*/b* axes
// have to reach the sampler with their `/Range`, so this cannot
// collapse to `Cs::Rgb` the way `/CalRGB` can.
b"Lab" => {
let mut white_point = [1.0f32, 1.0, 1.0];
let mut range = [-100.0f32, 100.0, -100.0, 100.0];
let dict = items
.get(1)
.and_then(|d| self.resolve_obj(d))
.and_then(|d| d.as_dict().cloned());
if let Some(d) = &dict {
for (key, out) in [
(&b"WhitePoint"[..], &mut white_point[..]),
(&b"Range"[..], &mut range[..]),
] {
if let Some(nid) = self.names.lookup(key)
&& let Some(PdfObject::Array(a)) = d.get(nid)
{
for (slot, item) in out.iter_mut().zip(a.iter()) {
if let Some(v) = item.as_number() {
*slot = v as f32;
}
}
}
}
}
Some(Cs::Lab { white_point, range })
}
b"ICC" => Some(Cs::Rgb),
b"Indexed" | b"I" => {
let base_obj = items.get(1)?.clone();
let hival = items.get(2).and_then(PdfObject::as_int).unwrap_or(0).max(0) as u32;
let lookup = self.read_indexed_lookup(items.get(3)?)?;
// A palette in a space the sampler cannot express (Lab, whose
// signed a*/b* bytes read as RGB collapse to near-black, or a
// multi-input DeviceN) is pre-converted to sRGB here — the
// palette is a `(hival+1)×1` image in the base space. The
// sampler then does a plain index→RGB fetch.
let entries = hival.saturating_add(1);
let palette: Arc<[u8]> = Arc::from(lookup.clone());
if let Some(rgb) =
self.convert_special_image_samples(&base_obj, &palette, 8, entries, 1, None)
{
return Some(Cs::Indexed {
base: Box::new(Cs::Rgb),
hival,
lookup: rgb,
});
}
let base = self.resolve_image_colorspace_depth(&base_obj, depth + 1)?;
Some(Cs::Indexed {
base: Box::new(base),
hival,
lookup: Arc::from(lookup),
})
}
// A `/Separation` (or 1-colorant `/DeviceN`) image sample is a
// *tint*, not a gray value. Bake the tint transform into a 256-entry
// sample→sRGB LUT so the sampler routes it correctly instead of
// mis-reading it as DeviceGray (which inverts near-white scans to
// near-black — the dominant residual over-ink class). Falls back to
// the arity approximation only if the transform will not build.
b"Separation" => self
.build_tint_image_lut(items)
.map(|rgb| Cs::TintLut { rgb })
.or(Some(Cs::Gray)),
b"DeviceN" => {
let names_len = self
.resolve_obj(items.get(1)?)
.and_then(|o| match &*o {
PdfObject::Array(a) => Some(a.len()),
_ => None,
})
.unwrap_or(1);
if names_len == 1
&& let Some(rgb) = self.build_tint_image_lut(items)
{
return Some(Cs::TintLut { rgb });
}
// Two colorants (a spot + black duotone, e.g. `/DeviceN
// [/PANTONE#207482#20C /Black] /DeviceCMYK`) bake to a 2-D
// table. The arity approximation would read one tint as
// DeviceGray and drop the other entirely.
if names_len == 2
&& let Some(rgb) = self.build_tint_image_lut2(items)
{
return Some(Cs::TintLut2 { rgb });
}
Some(if names_len == 4 {
Cs::Cmyk
} else if names_len == 3 {
Cs::Rgb
} else {
Cs::Gray
})
}
_ => None,
}
}
/// Bake a 1-input `/Separation`/`/DeviceN` tint transform into a 256-entry
/// sample→sRGB table (`256 × 3` bytes) for image sampling. Entry `i` is the
/// alternate-space colour of tint `i/255`, converted to sRGB with the same
/// `pdf_color` conversions the fill path uses. `None` for a multi-input
/// space (no 1-D LUT) or a transform that will not build — the caller then
/// keeps the arity approximation.
fn build_tint_image_lut(&mut self, items: &[PdfObject]) -> Option<Arc<[u8]>> {
let space = self.build_tint_space_from_array(items)?;
if space.inputs != 1 {
return None;
}
let mut rgb = Vec::with_capacity(256 * 3);
for i in 0..256u32 {
let sem = self.eval_tint(&space, &[i as f64 / 255.0]);
rgb.extend_from_slice(&sem_color_to_rgb8(&sem));
}
// R1 (PLAN-POST-SWEEP3): a *wrong-but-valid* LUT. A real tint
// transform must vary with the tint — tint 0 ≈ no colorant, tint 1 =
// full colorant. When the function evaluated but baked to a (near-)
// constant ramp (evaluation errored per-sample, clamped flat, or the
// function itself is degenerate), sampling through it blankets the
// image in one colour — the Separation/Indexed "blank cover" class.
// Repair with the polarity-correct subtractive ramp the non-LUT path
// would have used, and mark the draw degraded so the tracker sees it.
// `/None` colorants are excluded: their all-white LUT is deliberate
// policy ("marks nothing"), not degradation.
if space.func.is_some() && !space.colorant_none && lut_is_degenerate(&rgb) {
for (i, px) in rgb.chunks_exact_mut(3).enumerate() {
let g = 255 - i as u8; // tint i/255 → gray 1 − tint
px.copy_from_slice(&[g, g, g]);
}
self.image_cs_degraded = true;
self.ctx.note_recovery(
"degenerate tint-transform ramp replaced with subtractive approximation"
.to_string(),
);
}
Some(Arc::from(rgb))
}
/// Bake a 2-input `/DeviceN` tint transform into a `256 x 256 x 3`
/// sample-pair→sRGB table for image sampling. Entry `(a, b)` is the
/// alternate-space colour of tints `(a/255, b/255)`, converted with the same
/// `pdf_color` conversions the fill path uses.
///
/// 65 536 evaluations of the tint function is the cost, paid once per image
/// space; three inputs would be 16.7 M evaluations and a 48 MiB table, which
/// is why this stops at two.
fn build_tint_image_lut2(&mut self, items: &[PdfObject]) -> Option<Arc<[u8]>> {
let space = self.build_tint_space_from_array(items)?;
if space.inputs != 2 || space.func.is_none() {
return None;
}
let mut rgb = Vec::with_capacity(256 * 256 * 3);
for a in 0..256u32 {
for b in 0..256u32 {
let sem = self.eval_tint(&space, &[a as f64 / 255.0, b as f64 / 255.0]);
rgb.extend_from_slice(&sem_color_to_rgb8(&sem));
}
}
// Same degeneracy guard as the 1-input LUT: a table that does not vary
// means the transform did not really evaluate, and sampling through it
// would blanket the image in one colour. Fall back to the arity
// approximation rather than paint a flat lie.
if lut_is_degenerate(&rgb) {
return None;
}
Some(Arc::from(rgb))
}
/// Read an Indexed color space's lookup table (a string or a stream).
fn read_indexed_lookup(&mut self, obj: &PdfObject) -> Option<Vec<u8>> {
let resolved = self.resolve_obj(obj)?;
match &*resolved {
PdfObject::String(s) => Some(s.as_bytes().to_vec()),
PdfObject::Stream(stream) => self.snapshot.decode_stream_data(stream, self.ctx).ok(),
_ => None,
}
}
/// Build a grayscale `/SMask` soft mask from an image dictionary.
///
/// Codec-encoded masks (JBIG2 for MRC scans, DCT/JPX elsewhere) keep
/// their encoded payload for the backend's registry, exactly like the
/// base image: the interpreter never decodes codecs.
fn build_image_smask(&mut self, dict: &Dictionary) -> Option<Arc<ImageSMask>> {
let smask = self.resolve_obj(&dict.get(self.intern(b"SMask"))?.clone())?;
let PdfObject::Stream(stream) = &*smask else {
return None;
};
let sdict = &stream.dict;
let w_key = self.intern(b"Width");
let width = self.dict_int_indirect(sdict, w_key).unwrap_or(0).max(0) as u32;
let h_key = self.intern(b"Height");
let height = self.dict_int_indirect(sdict, h_key).unwrap_or(0).max(0) as u32;
let bpc_key = self.intern(b"BitsPerComponent");
let bpc = self
.dict_int_indirect(sdict, bpc_key)
.unwrap_or(8)
.clamp(1, 16) as u8;
let decode = self.read_decode_array(sdict).map(Arc::from);
let codec_parms = self.read_codec_parms(sdict);
let (samples, codec, codec_data) =
match self.snapshot.decode_stream_data_to_codec(stream, self.ctx) {
Ok((bytes, None)) => (Arc::from(bytes), None, None),
Ok((bytes, Some(name))) => (
Arc::from(Vec::new()),
codec_kind(name.as_bytes()),
Some(bytes.into()),
),
Err(_) => return None,
};
Some(Arc::new(ImageSMask {
width,
height,
bits_per_component: bpc,
decode,
samples,
codec,
codec_data,
codec_parms,
}))
}
/// Build an explicit `/Mask` (ISO 32000-1 §8.9.6.3–8.9.6.4) from an image
/// dictionary. The caller has already ruled out `/SMask` (which overrides)
/// and stencil base images. Two forms:
///
/// * an **array** → color-key masking: `[min0 max0 …]` in raw-sample space.
/// Rejected (→ `None`, paint unmasked) when the length is not `2 ×
/// component-count` or any bound exceeds `2^bpc − 1`, matching PDFium's
/// tolerance for malformed masks.
/// * a **stream** → a 1-bit stencil image-mask XObject, carried as an
/// [`ImageSMask`] payload (reusing its codec plumbing; the *polarity* is
/// handled at sampling time, not here).
fn build_image_mask(
&mut self,
dict: &Dictionary,
color_space: Option<&ImageColorSpace>,
bpc: u8,
) -> Option<crate::page_ir::ImageMask> {
let mask = self.resolve_obj(&dict.get(self.intern(b"Mask"))?.clone())?;
match &*mask {
// Color-key masking: integer ranges in raw-sample space.
PdfObject::Array(items) => {
let ncomp = color_space.map(ImageColorSpace::components).unwrap_or(1);
if items.len() != ncomp * 2 {
return None;
}
let max_raw: i64 = (1i64 << bpc.min(31)) - 1;
let mut ranges = Vec::with_capacity(ncomp);
for pair in items.chunks_exact(2) {
let lo = pair[0].as_int()?;
let hi = pair[1].as_int()?;
// Malformed: negative or out of the sample range, or lo > hi.
if lo < 0 || hi < 0 || lo > max_raw || hi > max_raw || lo > hi {
return None;
}
ranges.push([lo as u32, hi as u32]);
}
Some(crate::page_ir::ImageMask::ColorKey(Arc::from(ranges)))
}
// Stencil mask: a 1-bit image-mask XObject.
PdfObject::Stream(stream) => {
let sdict = &stream.dict;
let w_key = self.intern(b"Width");
let width = self.dict_int_indirect(sdict, w_key).unwrap_or(0).max(0) as u32;
let h_key = self.intern(b"Height");
let height = self.dict_int_indirect(sdict, h_key).unwrap_or(0).max(0) as u32;
let mut decode: Option<Vec<[f32; 2]>> = self.read_decode_array(sdict);
// §8.9.6.4's polarity (sample 1 = masked out) is defined for a
// *stencil*, i.e. a stream with `/ImageMask true`. Producers do
// point `/Mask` at an ordinary 1-bit `/DeviceGray` image
// instead (pdfjs issue6621), and there the samples read as
// coverage the other way up — 1 paints. PDFium, MuPDF and hayro
// all agree on that; taking the stencil polarity literally
// masked out everything those three paint and left the image
// invisible. Flip whatever polarity the stream declares.
if !dict_bool(sdict, self.intern(b"ImageMask")) {
decode = Some(match decode {
Some(d) if !d.is_empty() => d.iter().map(|&[lo, hi]| [hi, lo]).collect(),
_ => vec![[1.0, 0.0]],
});
}
let decode = decode.map(Arc::from);
let codec_parms = self.read_codec_parms(sdict);
let (samples, codec, codec_data) =
match self.snapshot.decode_stream_data_to_codec(stream, self.ctx) {
Ok((bytes, None)) => (Arc::from(bytes), None, None),
Ok((bytes, Some(name))) => (
Arc::from(Vec::new()),
codec_kind(name.as_bytes()),
Some(bytes.into()),
),
Err(_) => return None,
};
Some(crate::page_ir::ImageMask::Stencil(Arc::new(ImageSMask {
width,
height,
// An /ImageMask is 1-bit by definition (§8.9.6.2).
bits_per_component: 1,
decode,
samples,
codec,
codec_data,
codec_parms,
})))
}
_ => None,
}
}
/// Read the `/DecodeParms` a codec needs: JBIG2's globals stream and
/// CCITT's parameters. `/DecodeParms` may be a dict or an array parallel
/// to `/Filter`, so every entry is inspected.
fn read_codec_parms(&mut self, dict: &Dictionary) -> Option<crate::page_ir::CodecParms> {
let parms = self.resolve_obj(&dict.get(self.names.known.decode_parms)?.clone())?;
let candidates: Vec<PdfObject> = match &*parms {
PdfObject::Array(items) => items.to_vec(),
other => vec![other.clone()],
};
let mut out = crate::page_ir::CodecParms {
// The spec's CCITT defaults (ISO 32000-1 table 11).
columns: 1728,
end_of_block: true,
..Default::default()
};
let mut found = false;
for entry in candidates {
let Some(entry) = self.resolve_obj(&entry) else {
continue;
};
let Some(d) = entry.as_dict() else { continue };
let d = d.clone();
found = true;
if let Some(reference) = d.get(self.intern(b"JBIG2Globals")).cloned()
&& let Some(resolved) = self.resolve_obj(&reference)
&& let PdfObject::Stream(stream) = &*resolved
&& let Ok(bytes) = self.snapshot.decode_stream_data(stream, self.ctx)
{
out.jbig2_globals = Some(Arc::from(bytes));
}
let int = |this: &mut Self, key: &[u8]| -> Option<i64> {
let value = d.get(this.intern(key))?.clone();
this.resolve_obj(&value)?.as_int()
};
let boolean = |this: &mut Self, key: &[u8]| -> Option<bool> {
let value = d.get(this.intern(key))?.clone();
match &*this.resolve_obj(&value)? {
PdfObject::Boolean(b) => Some(*b),
_ => None,
}
};
if let Some(k) = int(self, b"K") {
out.k = k as i32;
}
if let Some(c) = int(self, b"Columns") {
out.columns = c.max(0) as u32;
}
if let Some(r) = int(self, b"Rows") {
out.rows = r.max(0) as u32;
}
if let Some(v) = boolean(self, b"BlackIs1") {
out.black_is_1 = v;
}
if let Some(v) = boolean(self, b"EncodedByteAlign") {
out.byte_align = v;
}
if let Some(v) = boolean(self, b"EndOfLine") {
out.end_of_line = v;
}
if let Some(v) = boolean(self, b"EndOfBlock") {
out.end_of_block = v;
}
}
found.then_some(out)
}
/// Execute a Form XObject inline (ISO 32000-1 §8.10.1).
fn invoke_form(
&mut self,
obj_id: Option<ObjectId>,
stream: &PdfStream,
) -> Result<(), ContentError> {
self.invoke_form_with_origin(obj_id, stream, PaintOrigin::FormXObject)
}
/// Execute a form while attributing its direct content to `origin`.
/// Annotation appearance streams use their own origin; forms invoked from
/// inside an appearance still enter through `invoke_form`, so the
/// innermost Form XObject wins.
fn invoke_form_with_origin(
&mut self,
obj_id: Option<ObjectId>,
stream: &PdfStream,
origin: PaintOrigin,
) -> Result<(), ContentError> {
if self.invoke_depth >= self.limits.max_invoke_depth {
return Err(ContentError::RecursionDepth(self.invoke_depth));
}
// Precise cycle detection: a form already on the stack is skipped
// rather than re-entered (tolerant — matches how viewers survive
// self-referential forms).
if let Some(id) = obj_id
&& self.form_stack.contains(&id)
{
return Ok(());
}
let content = self.snapshot.decode_stream_data(stream, self.ctx)?;
let matrix = read_matrix(&stream.dict, self.intern(b"Matrix"));
let bbox = read_rect(&stream.dict, self.intern(b"BBox"));
let group = self.read_group(&stream.dict, bbox, matrix);
let form_res = match stream.dict.get(self.names.known.resources).cloned() {
Some(res) => self.resolve_obj(&res),
None => self.resources.clone(),
};
// Clear the leftover `Do` operands so the form's first operator does
// not see them.
self.operands.clear();
let frame = self.enter_nested_stream(form_res, matrix);
// 3. Clip to /BBox (in form space, i.e. after the Matrix concat).
if let Some([x0, y0, x1, y1]) = bbox {
let path = rect_path(x0, y0, x1 - x0, y1 - y0);
let pid = self.intern_path(path);
self.emit(SemanticOp::Clip {
path: pid,
rule: FillRule::NonZero,
});
self.gs.clip_depth += 1;
}
// A transparency group scopes the form's compositing. Capture the
// group's composite params (ca/blend at the invocation) BEFORE
// resetting them for the content: the group as a whole is composited
// with them, while its content paints with alpha/blend reset to
// 1/Normal (ISO 32000-1 §11.6.6), avoiding a double alpha.
if let Some((isolated, knockout, bounds)) = group {
self.emit(SemanticOp::BeginGroup {
isolated,
knockout,
bounds,
opacity: self.gs.fill_alpha,
blend: self.gs.blend,
});
self.gs.fill_alpha = 1.0;
self.gs.stroke_alpha = 1.0;
self.gs.blend = BlendMode::Normal;
}
if let Some(id) = obj_id {
self.form_stack.push(id);
}
// Only form and annotation-appearance invocations reach here; anything
// else would still be a form-shaped nested stream.
let trace_kind = match origin {
PaintOrigin::AnnotationAppearance => TraceFrameKind::AnnotationAppearance,
_ => TraceFrameKind::FormXObject,
};
let trace_saved = self.trace_enter(trace_kind, obj_id);
self.emit(SemanticOp::BeginPaintOrigin(origin));
let result = self.run(&content);
self.emit(SemanticOp::EndPaintOrigin);
self.trace_exit(trace_saved);
if obj_id.is_some() {
self.form_stack.pop();
}
self.leave_nested_stream(frame, group.is_some());
result
}
/// Render a page's annotation static appearances after the page content
/// (ISO 32000-1 §12.5.5; PDFium `FPDF_ANNOT` display pass).
///
/// PDFium two-pass order (`CPDF_AnnotList::DisplayAnnots`): every
/// non-widget annotation first, then the widgets. `Hidden`/`NoView`
/// annotations are skipped for screen rendering. Each annotation is
/// rendered from a *fresh* graphics state — never the state the page
/// content happened to end in.
///
/// Only DoS-guard errors propagate (same contract as [`Self::run`]);
/// everything else drops just the offending annotation.
pub(crate) fn run_annotations(
&mut self,
annots: &[crate::document::PageAnnotation],
) -> Result<(), ContentError> {
// Balance any un-restored `q` the page content left behind so the
// annotations (and lowering's state stack) start clean; likewise any
// dangling marked-content (OC) suppression.
while self.gs_stack.pop().is_some() {
self.emit(SemanticOp::Restore);
}
self.mc_stack.clear();
self.oc_hidden_count = 0;
for widgets_pass in [false, true] {
for annot in annots {
let is_widget = annot
.subtype
.is_some_and(|s| self.names.resolve(s).as_ref() == b"Widget");
if is_widget != widgets_pass {
continue;
}
if annot.hidden_for_display() {
continue;
}
if let Err(e) = self.render_annotation(annot) {
if e.is_fatal() {
return Err(e);
}
self.ctx
.note_recovery(format!("annotation appearance dropped ({e})"));
}
}
}
Ok(())
}
/// Render one annotation's `/AP /N` appearance stream (§12.5.5
/// algorithm): map the form's `/BBox` through its `/Matrix`, fit that
/// extent onto `/Rect` with matrix `A`, then run the form under `A`
/// (the form's own `/Matrix` + `/BBox` clip are applied by
/// [`Self::invoke_form`], yielding the spec's `/Matrix` ∘ `A`).
fn render_annotation(
&mut self,
annot: &crate::document::PageAnnotation,
) -> Result<(), ContentError> {
let Some((stream_id, stream)) = self.annotation_appearance(annot) else {
return self.render_markup_annotation(annot);
};
let bbox = read_rect(&stream.dict, self.intern(b"BBox"));
let matrix = read_matrix(&stream.dict, self.intern(b"Matrix"));
let Some(fit) = appearance_matrix(bbox, matrix, annot.rect) else {
self.ctx.note_recovery(
"annotation appearance skipped (degenerate /BBox or /Rect)".to_string(),
);
return Ok(());
};
// Fresh per-annotation state (PDFium renders each annotation through
// its own CPDF_RenderContext layer, not the page's ending state).
self.gs = GraphicsState::default();
self.text = TextObjectState::Outside;
self.path = PathBuilder::default();
self.pending_clip = None;
self.operands.clear();
self.gs_stack.push(self.gs.clone());
self.emit(SemanticOp::Save);
if fit != Matrix::IDENTITY {
self.gs.ctm = fit.then(self.gs.ctm);
self.emit(SemanticOp::Concat(fit));
}
let result =
self.invoke_form_with_origin(stream_id, &stream, PaintOrigin::AnnotationAppearance);
if let Some(prev) = self.gs_stack.pop() {
self.gs = prev;
self.emit(SemanticOp::Restore);
}
result
}
/// Synthesize the conventional static appearance for text-markup
/// annotations whose author omitted `/AP /N`. A usable appearance stream
/// is always authoritative; this fallback covers only the four geometric
/// markup subtypes defined by §12.5.6.10.
fn render_markup_annotation(
&mut self,
annot: &crate::document::PageAnnotation,
) -> Result<(), ContentError> {
let Some(subtype) = annot.subtype.map(|name| self.names.resolve(name)) else {
return Ok(());
};
let kind = match subtype.as_ref() {
b"Highlight" => MarkupKind::Highlight,
b"Underline" => MarkupKind::Underline,
b"Squiggly" => MarkupKind::Squiggly,
b"StrikeOut" => MarkupKind::StrikeOut,
_ => return Ok(()),
};
let fallback_quad = [
annot.rect[0],
annot.rect[3],
annot.rect[2],
annot.rect[3],
annot.rect[0],
annot.rect[1],
annot.rect[2],
annot.rect[1],
];
let quads: &[[f64; 8]] = if annot.quad_points.is_empty() {
if annot.rect[0] >= annot.rect[2] || annot.rect[1] >= annot.rect[3] {
return Ok(());
}
std::slice::from_ref(&fallback_quad)
} else {
&annot.quad_points
};
let mut builder = PathBuilder::default();
for quad in quads {
append_markup_geometry(&mut builder, *quad, kind);
}
if builder.is_empty() {
return Ok(());
}
let path = self.intern_path(builder.take());
let default = if matches!(kind, MarkupKind::Highlight) {
SemColor::DeviceRgb(1.0, 1.0, 0.0)
} else {
SemColor::DeviceGray(0.0)
};
let color = match annot.color {
Some(crate::document::AnnotationColor::Gray(gray)) => {
SemColor::DeviceGray(f64::from(gray))
}
Some(crate::document::AnnotationColor::Rgb(rgb)) => {
SemColor::DeviceRgb(f64::from(rgb[0]), f64::from(rgb[1]), f64::from(rgb[2]))
}
Some(crate::document::AnnotationColor::Cmyk(cmyk)) => SemColor::DeviceCmyk(
f64::from(cmyk[0]),
f64::from(cmyk[1]),
f64::from(cmyk[2]),
f64::from(cmyk[3]),
),
None => default,
};
let blend = if matches!(kind, MarkupKind::Highlight) {
BlendMode::Multiply
} else {
BlendMode::Normal
};
// Each synthesized appearance is an isolated semantic state just like
// an appearance Form. Attribution remains AnnotationAppearance so
// sweep diagnostics do not misclassify these pixels as page content.
let trace_saved = self.trace_enter(TraceFrameKind::AnnotationAppearance, annot.source);
self.emit(SemanticOp::Save);
self.emit(SemanticOp::BeginPaintOrigin(
PaintOrigin::AnnotationAppearance,
));
self.emit(SemanticOp::SetFillColor(color));
self.emit(SemanticOp::SetFillAlpha(annot.opacity.clamp(0.0, 1.0)));
self.emit(SemanticOp::SetBlendMode(blend));
self.emit(SemanticOp::Fill {
path,
rule: FillRule::NonZero,
});
self.emit(SemanticOp::EndPaintOrigin);
self.emit(SemanticOp::Restore);
self.trace_exit(trace_saved);
Ok(())
}
/// Select an annotation's normal appearance stream. Always `/AP /N`
/// (PDFium renders `AppearanceMode::kNormal` unconditionally — never
/// `/D` or `/R`). When `/N` is a sub-dictionary of states, `/AS` picks
/// the entry; with no `/AS`, a single-entry dictionary falls back to
/// that entry (tolerance PDFium shares), otherwise nothing is drawn.
fn annotation_appearance(
&mut self,
annot: &crate::document::PageAnnotation,
) -> Option<(Option<ObjectId>, Arc<PdfStream>)> {
let ap = self.resolve_obj(annot.appearance.as_ref()?)?;
let n_raw = ap.as_dict()?.get(self.intern(b"N"))?.clone();
let n_id = match &n_raw {
PdfObject::Reference(id) => Some(*id),
_ => None,
};
let n = self.resolve_obj(&n_raw)?;
match &*n {
PdfObject::Stream(s) => Some((n_id, s.clone())),
PdfObject::Dictionary(states) => {
let entry = match annot.appearance_state {
Some(state) => states.get(state).cloned(),
None if states.len() == 1 => states.iter().next().map(|(_, v)| v.clone()),
None => None,
}?;
let entry_id = match &entry {
PdfObject::Reference(id) => Some(*id),
_ => None,
};
let resolved = self.resolve_obj(&entry)?;
match &*resolved {
PdfObject::Stream(s) => Some((entry_id, s.clone())),
_ => None,
}
}
_ => None,
}
}
/// Read a form's `/Group` as a transparency group, if present. Returns
/// `(isolated, knockout, bounds)`, with `bounds` the `/BBox` mapped through
/// the form's effective CTM (matrix ∘ current CTM) — a conservative extent
/// in page space for later offscreen allocation.
fn read_group(
&mut self,
dict: &Dictionary,
bbox: Option<[f64; 4]>,
matrix: Matrix,
) -> Option<(bool, bool, Rect)> {
let group_ref = dict.get(self.intern(b"Group"))?.clone();
let group = self.resolve_obj(&group_ref)?;
let gdict = group.as_dict()?;
let s = gdict.get(self.intern(b"S")).and_then(PdfObject::as_name)?;
if self.names.resolve(s).as_ref() != b"Transparency" {
return None;
}
let isolated = dict_bool(gdict, self.intern(b"I"));
let knockout = dict_bool(gdict, self.intern(b"K"));
let bounds = group_bounds(bbox, matrix.then(self.gs.ctm));
Some((isolated, knockout, bounds))
}
fn filter_names(&self, obj: &PdfObject) -> Vec<Vec<u8>> {
match obj {
PdfObject::Name(n) => vec![self.names.resolve(*n).to_vec()],
PdfObject::Array(items) => items
.iter()
.filter_map(PdfObject::as_name)
.map(|n| self.names.resolve(n).to_vec())
.collect(),
_ => Vec::new(),
}
}
fn inline_image(&mut self, dict: &[(Vec<u8>, Operand)], data: Vec<u8>) {
let mut width = 0u32;
let mut height = 0u32;
let mut bpc = 0u8;
let mut is_mask = false;
let mut filters = Vec::new();
let mut interpolate = false;
let mut cs: Option<Operand> = None;
let mut decode: Option<Vec<[f32; 2]>> = None;
// Inline images cannot reference a stream, so `/Mask` here is only ever
// the color-key array form (§8.9.6.4); it has no abbreviated key.
let mut mask_op: Option<Operand> = None;
let mut dp_op: Option<Operand> = None;
for (key, value) in dict {
match key.as_slice() {
b"W" | b"Width" => width = value.as_int().unwrap_or(0).max(0) as u32,
b"H" | b"Height" => height = value.as_int().unwrap_or(0).max(0) as u32,
b"BPC" | b"BitsPerComponent" => {
bpc = value.as_int().unwrap_or(0).clamp(0, 255) as u8
}
b"IM" | b"ImageMask" => is_mask = matches!(value, Operand::Bool(true)),
b"F" | b"Filter" => filters = collect_filters(value),
b"I" | b"Interpolate" => interpolate = matches!(value, Operand::Bool(true)),
b"CS" | b"ColorSpace" => cs = Some(value.clone()),
b"D" | b"Decode" => {
if let Operand::Array(a) = value {
let nums: Vec<f64> = a.iter().filter_map(Operand::as_f64).collect();
decode = Some(pairs_f32(nums));
}
}
b"Mask" => mask_op = Some(value.clone()),
b"DP" | b"DecodeParms" => dp_op = Some(value.clone()),
_ => {}
}
}
if is_mask && bpc == 0 {
bpc = 1;
}
self.image_cs_degraded = false;
let color_space = if is_mask {
None
} else {
Some(self.inline_colorspace(cs.as_ref()))
};
let lowering_degraded = self.image_cs_degraded;
// Color-key `/Mask` only — a stencil (stream) mask can't appear inline.
// Suppressed for stencil base images, matching the XObject path.
let mask = if is_mask {
None
} else {
mask_op.and_then(|op| inline_color_key_mask(&op, color_space.as_ref(), bpc))
};
let (samples, codec, codec_data) = self.decode_inline(&filters, &data);
let img = SemImage {
object: None,
width,
height,
bits_per_component: bpc,
is_mask,
filters,
inline_data: data,
color_space,
interpolate,
decode,
samples,
codec,
codec_data,
// Inline images spell /DecodeParms as /DP (Table 93); the keys
// *inside* the parms dict are not abbreviated, so the standard
// CCITT parameter names apply. JBIG2 globals need an indirect
// stream, which inline images cannot reference — CCITT is the
// only codec that takes parameters here.
codec_parms: dp_op.as_ref().and_then(inline_codec_parms),
smask: None,
mask,
smask_in_data: 0,
lowering_degraded,
};
let id = ImageId(self.images.len() as u32);
self.images.push(img);
self.emit(SemanticOp::DrawImage(id));
}
/// Map an inline image's `/CS` (abbreviation or named resource) to a color
/// space, defaulting to Gray.
fn inline_colorspace(&mut self, cs: Option<&Operand>) -> ImageColorSpace {
match cs {
Some(Operand::Name(n)) => match n.as_slice() {
b"G" | b"DeviceGray" | b"CalGray" => ImageColorSpace::Gray,
b"RGB" | b"DeviceRGB" | b"CalRGB" => ImageColorSpace::Rgb,
b"CMYK" | b"DeviceCMYK" => ImageColorSpace::Cmyk,
other => {
// A named resource color space (or a spec family name
// such as `/Lab`). Resolve the category first, so a
// resource name is interned when it exists.
let _ = self.resource_subdict(self.names.known.color_space);
let name = PdfObject::Name(self.inline_name(other));
self.resolve_image_colorspace(&name)
.unwrap_or(ImageColorSpace::Gray)
}
},
// `/CS` may be written out in full (§8.9.5.1 permits any of the
// colour-space forms an image XObject accepts, abbreviations
// optional), most often `[/I /RGB 255 <palette>]`. Falling back to
// DeviceGray here reads palette *indices* as grey levels — on
// custom/image_inline_5 index 1 is a light blue but reads as near
// black, and the page rendered at ink 0.53 against PDFium's 0.06.
Some(other @ (Operand::Array(_) | Operand::Dict(_))) => {
let _ = self.resource_subdict(self.names.known.color_space);
let obj = self.operand_to_object(other);
self.resolve_image_colorspace(&obj)
.unwrap_or(ImageColorSpace::Gray)
}
_ => ImageColorSpace::Gray,
}
}
/// Convert a content-stream operand into a [`PdfObject`], so an inline
/// image's parameters can go through the same resolution paths as an image
/// XObject's dictionary. Inline operands are always direct — there are no
/// indirect references inside a content stream — so this is a pure
/// structural mapping.
fn operand_to_object(&mut self, op: &Operand) -> PdfObject {
match op {
Operand::Int(v) => PdfObject::Integer(*v),
Operand::Real(v) => PdfObject::Real(*v),
Operand::Bool(v) => PdfObject::Boolean(*v),
Operand::Null => PdfObject::Null,
Operand::Name(n) => PdfObject::Name(self.inline_name(n)),
Operand::String(s) => PdfObject::String(crate::object::PdfString::new(s.as_slice())),
Operand::Array(items) => {
PdfObject::Array(items.iter().map(|i| self.operand_to_object(i)).collect())
}
Operand::Dict(pairs) => {
let entries: Vec<(NameId, PdfObject)> = pairs
.iter()
.map(|(k, v)| (self.inline_name(k), self.operand_to_object(v)))
.collect();
PdfObject::Dictionary(Arc::new(Dictionary::from_pairs(entries)))
}
}
}
/// Filter-decode inline image bytes through the general filters by
/// wrapping them in a synthetic stream. A codec filter stops decoding:
/// the triple is `(samples, codec kind, codec-encoded payload)`.
#[allow(clippy::type_complexity)]
fn decode_inline(
&mut self,
filters: &[Vec<u8>],
data: &[u8],
) -> (
Option<Arc<[u8]>>,
Option<crate::page_ir::ImageCodecKind>,
Option<crate::page_ir::SharedBytes>,
) {
if filters.is_empty() {
return (Some(Arc::from(data)), None, None);
}
let filter_obj = if filters.len() == 1 {
PdfObject::Name(self.inline_name(&filters[0]))
} else {
PdfObject::Array(
filters
.iter()
.map(|f| PdfObject::Name(self.inline_name(f)))
.collect(),
)
};
let dict = Dictionary::from_pairs([(self.names.known.filter, filter_obj)]);
let stream = PdfStream {
dict,
data: StreamData::Owned(Arc::from(data)),
};
match self.snapshot.decode_stream_data_to_codec(&stream, self.ctx) {
Ok((bytes, None)) => (Some(Arc::from(bytes)), None, None),
Ok((bytes, Some(name))) => (None, codec_kind(name.as_bytes()), Some(bytes.into())),
Err(_) => (None, None, None),
}
}
/// `gs`: apply a named ExtGState (ISO 32000-1 §8.4.5). Phase 2 applies the
/// parameters the semantic layer models: fill/stroke alpha, blend mode,
/// and line width; the rest (soft masks, transfer functions, halftones)
/// arrive with later phases.
fn op_ext_gstate(&mut self) -> Result<(), ContentError> {
let Some(name) = self
.operands
.iter()
.rev()
.find_map(Operand::as_name)
.map(<[u8]>::to_vec)
else {
return Ok(());
};
let Some(egs) = self.resource_subdict(self.names.known.ext_g_state) else {
return Ok(());
};
let Some(nid) = self.lookup_name(&name) else {
return Ok(());
};
let Some(entry) = egs.as_dict().and_then(|d| d.get(nid)).cloned() else {
return Ok(());
};
let Some(state) = self.resolve_obj(&entry) else {
return Ok(());
};
let dict = match state.as_dict() {
Some(d) => d.clone(),
None => return Ok(()),
};
let dict = &dict;
if let Some(ca) = dict_num(dict, self.intern(b"ca")) {
self.gs.fill_alpha = ca as f32;
self.emit(SemanticOp::SetFillAlpha(ca as f32));
}
if let Some(ca) = dict_num(dict, self.intern(b"CA")) {
self.gs.stroke_alpha = ca as f32;
self.emit(SemanticOp::SetStrokeAlpha(ca as f32));
}
if let Some(lw) = dict_num(dict, self.intern(b"LW")) {
self.gs.line_width = lw;
self.emit(SemanticOp::SetLineWidth(lw));
}
// /OP (stroke) and /op (fill) overprint: recorded as a page feature
// flag (§8.6.7); compositing itself is unchanged.
for key in [&b"OP"[..], b"op"] {
if matches!(dict.get(self.intern(key)), Some(PdfObject::Boolean(true))) {
self.uses_overprint = true;
}
}
if let Some(blend) = dict.get(self.intern(b"BM")) {
// /BM may be a single name or an array (first recognized wins).
let name = match blend {
PdfObject::Name(n) => Some(*n),
PdfObject::Array(items) => items.iter().find_map(PdfObject::as_name),
_ => None,
};
if let Some(n) = name {
let mode = map_blend_mode(&self.names.resolve(n));
self.gs.blend = mode;
self.emit(SemanticOp::SetBlendMode(mode));
}
}
// /SMask: a soft-mask dictionary, or /None to disable.
if let Some(smask) = dict.get(self.intern(b"SMask")).cloned() {
if matches!(&smask, PdfObject::Name(n) if self.names.resolve(*n).as_ref() == b"None") {
self.emit(SemanticOp::ClearSoftMask);
} else if let Some(sm) = self.resolve_obj(&smask)
&& let Some(sm) = sm.as_dict()
{
let sm = sm.clone();
let luminosity = matches!(
sm.get(self.intern(b"S")).and_then(PdfObject::as_name),
Some(s) if self.names.resolve(s).as_ref() == b"Luminosity"
);
// /BC (luminosity only): explicit backdrop color, converted
// to RGB bytes with the device approximation (§11.6.5.2).
let kind = if luminosity {
match read_num_array(&sm, self.intern(b"BC")) {
Some(bc) if !bc.is_empty() => {
let comps: Vec<f32> = bc.iter().map(|v| *v as f32).collect();
let rgba = comps_to_rgba(&comps);
MaskKind::LuminosityBc {
backdrop: [
(rgba[0] * 255.0 + 0.5) as u8,
(rgba[1] * 255.0 + 0.5) as u8,
(rgba[2] * 255.0 + 0.5) as u8,
],
}
}
_ => MaskKind::Luminosity,
}
} else {
MaskKind::Alpha
};
let transfer = self.build_transfer_lut(&sm);
if let Some(g) = sm.get(self.intern(b"G")).cloned() {
let group_id = g.as_reference();
if let Some(group) = self.resolve_obj(&g)
&& let PdfObject::Stream(stream) = &*group
{
let stream = stream.clone();
self.run_soft_mask(kind, transfer, &stream, group_id)?;
}
}
}
}
Ok(())
}
/// Sample the `/SMask` dictionary's `/TR` transfer function into a
/// 256-entry LUT (`None` for absent or `/Identity` — and for a sampled
/// LUT that turns out to *be* the identity, so the common no-op case
/// costs the render nothing).
fn build_transfer_lut(&mut self, sm: &Dictionary) -> Option<crate::page_ir::TransferLut> {
let tr = sm.get(self.intern(b"TR")).cloned()?;
if matches!(&tr, PdfObject::Name(n) if self.names.resolve(*n).as_ref() == b"Identity") {
return None;
}
let func = self.build_function(&tr, 0)?;
let mut lut = [0u8; 256];
let mut identity = true;
for (i, slot) in lut.iter_mut().enumerate() {
let t = i as f32 / 255.0;
let v = func.eval(t).first().copied().unwrap_or(t).clamp(0.0, 1.0);
*slot = (v * 255.0 + 0.5) as u8;
identity &= *slot == i as u8;
}
if identity {
None
} else {
Some(std::sync::Arc::new(lut))
}
}
/// Render a soft-mask group's content isolated, bracketed by
/// Begin/EndSoftMask so a backend can derive the per-pixel mask (its
/// luminosity or alpha) and apply it to subsequent painting.
fn run_soft_mask(
&mut self,
kind: MaskKind,
transfer: Option<crate::page_ir::TransferLut>,
stream: &PdfStream,
group_id: Option<ObjectId>,
) -> Result<(), ContentError> {
if self.invoke_depth >= self.limits.max_invoke_depth {
return Err(ContentError::RecursionDepth(self.invoke_depth));
}
// A soft-mask group that references itself (directly or through a
// cycle) renders *empty* at the recursive instance: a luminosity group
// with no marks is 0 everywhere, i.e. fully masked, and an alpha group
// is likewise fully transparent (§11.6.5.2). Emit an empty
// Begin/EndSoftMask so the backend derives that all-masking mask
// instead of dropping the mask (over-painting) or recursing to the
// depth limit. resvg_masking_mask_recursive_on_self is exactly this.
let recursive = group_id.is_some_and(|id| self.soft_mask_stack.contains(&id));
if recursive {
self.emit(SemanticOp::BeginSoftMask { kind, transfer });
self.emit(SemanticOp::EndSoftMask);
return Ok(());
}
let content = self.snapshot.decode_stream_data(stream, self.ctx)?;
let matrix = read_matrix(&stream.dict, self.intern(b"Matrix"));
let bbox = read_rect(&stream.dict, self.intern(b"BBox"));
let form_res = match stream.dict.get(self.names.known.resources).cloned() {
Some(res) => self.resolve_obj(&res),
None => self.resources.clone(),
};
self.emit(SemanticOp::BeginSoftMask { kind, transfer });
let frame = self.enter_nested_stream(form_res, matrix);
if let Some([x0, y0, x1, y1]) = bbox {
let path = rect_path(x0, y0, x1 - x0, y1 - y0);
let pid = self.intern_path(path);
self.emit(SemanticOp::Clip {
path: pid,
rule: FillRule::NonZero,
});
self.gs.clip_depth += 1;
}
// Mask content paints fresh (no inherited alpha/blend/soft-mask).
self.gs.fill_alpha = 1.0;
self.gs.stroke_alpha = 1.0;
self.gs.blend = BlendMode::Normal;
if let Some(id) = group_id {
self.soft_mask_stack.push(id);
}
let trace_saved = self.trace_enter(TraceFrameKind::SoftMask, group_id);
self.emit(SemanticOp::BeginPaintOrigin(PaintOrigin::SoftMaskContent));
let result = self.run(&content);
self.emit(SemanticOp::EndPaintOrigin);
self.trace_exit(trace_saved);
if group_id.is_some() {
self.soft_mask_stack.pop();
}
self.leave_nested_stream(frame, false);
self.emit(SemanticOp::EndSoftMask);
result
}
// --- shadings & patterns ----------------------------------------------
/// `sh`: paint a shading dictionary from the `/Shading` resources across
/// the current clip in current user space (ISO 32000-1 §8.7.4.2).
fn op_shading(&mut self) -> Result<(), ContentError> {
let Some(name) = self
.operands
.iter()
.rev()
.find_map(Operand::as_name)
.map(<[u8]>::to_vec)
else {
return Ok(());
};
let Some(shadings) = self.resource_subdict(self.names.known.shading) else {
return Ok(());
};
let Some(nid) = self.lookup_name(&name) else {
return Ok(());
};
let Some(entry) = shadings.as_dict().and_then(|d| d.get(nid)).cloned() else {
return Ok(());
};
let object = entry.as_reference();
let Some(obj) = self.resolve_obj(&entry) else {
return Ok(());
};
let kind = self.build_shading(&obj);
// A shading type we cannot rasterize is skipped for `sh` (nothing to
// paint without a region-filling color); patterns keep the hook.
if matches!(kind, SemShadingKind::Unsupported { .. }) {
return Ok(());
}
let bbox = self.shading_bbox(&obj);
let id = ShadingId(self.shadings.len() as u32);
self.shadings.push(SemShading { object, kind, bbox });
if self.record_trace {
self.trace_extra = object.map(|object| TraceFrame {
kind: TraceFrameKind::Shading,
object: Some(object),
});
}
self.emit(SemanticOp::PaintShading(id));
Ok(())
}
/// Park the name-keyed resolution caches while a nested content stream
/// runs under a different `/Resources` dictionary.
///
/// These caches are keyed by resource *name*, and a name means whatever the
/// currently active `/Resources` says it means. A form XObject, a soft mask
/// and a Type 3 CharProc each bring their own dictionary, so an entry
/// filled under one must not answer a lookup under another. pdfjs/issue8565
/// gives `/Sh1` three different meanings — page, tiling pattern, soft-mask
/// form — and the soft mask's entry was answering the tiling pattern's
/// lookup, painting the mask's grey luminosity ramp where an orange shading
/// belonged.
///
/// All five move together on purpose. `show_type3` reaches `type3_cache`
/// through `fonts[id].resource_name`, so scoping `font_cache` without
/// `type3_cache` (or the reverse) can hand back a font whose Type 3 data is
/// no longer reachable and silently drop glyphs.
///
/// Known cost, measured and accepted: clearing `font_cache` re-resolves an
/// identical font object into a second `SemFont`, which shifts font
/// substitution slightly on some text pages (An Investors Guide to Trading
/// Options: p22 +0.0026, p33 +0.0030, p44 +0.0045, p55 -0.0040 against
/// PDFium). It is worth it — the same scoping is what fixes
/// processstudies.46.1.0025's five sampled pages (~0.06 -> ~0.007 each).
/// Keying these two by resolved object rather than by name would get both;
/// nothing measured today needs it.
///
/// Called with the `self.resources` swap it belongs to; restored by
/// [`Self::restore_resource_caches`] alongside `saved_res`.
fn take_resource_caches(&mut self) -> ResourceCaches {
ResourceCaches {
font: std::mem::take(&mut self.font_cache),
type3: std::mem::take(&mut self.type3_cache),
pattern: std::mem::take(&mut self.pattern_cache),
uncolored_tiling: std::mem::take(&mut self.uncolored_tiling_cache),
tint: std::mem::take(&mut self.tint_cache),
cie: std::mem::take(&mut self.cie_cache),
indexed: std::mem::take(&mut self.indexed_cache),
}
}
fn restore_resource_caches(&mut self, saved: ResourceCaches) {
self.font_cache = saved.font;
self.type3_cache = saved.type3;
self.pattern_cache = saved.pattern;
self.uncolored_tiling_cache = saved.uncolored_tiling;
self.tint_cache = saved.tint;
self.cie_cache = saved.cie;
self.indexed_cache = saved.indexed;
}
/// Resolve a `/Pattern` resource by name into a resolved [`SemColor`]
/// (shading pattern → table entry; tiling pattern → compiled cell).
/// `under` are the numeric operands preceding the name (the underlying
/// color for an uncolored tiling pattern). Returns `None` when the pattern
/// cannot be resolved so the caller falls back to the symbolic form.
///
/// The cache is by name, but an uncoloured tiling pattern's entry carries
/// the underlying colour of the use that compiled it. A later use with a
/// different colour gets its own entry, sharing the compiled cell (see
/// `uncolored_tiling_cache`).
fn resolve_pattern(&mut self, name: NameId, under: &[f64]) -> Option<SemColor> {
let Some(cached) = self.pattern_cache.get(&name).cloned() else {
let resolved = self.resolve_pattern_uncached(name, under);
self.pattern_cache.insert(name, resolved.clone());
return resolved;
};
let Some(SemColor::TilingPattern { tiling, matrix }) = cached else {
return cached;
};
let first = &self.tilings[tiling.0 as usize];
let under_color = under_rgba(under);
let bits = under_color.map(f32::to_bits);
if !first.uncolored || bits == first.under_color.map(f32::to_bits) {
return cached;
}
let id = match self.uncolored_tiling_cache.get(&(name, bits)) {
Some(&id) => id,
None => {
let recoloured = SemTiling {
under_color,
..first.clone()
};
let id = TilingId(self.tilings.len() as u32);
self.tilings.push(recoloured);
self.uncolored_tiling_cache.insert((name, bits), id);
id
}
};
Some(SemColor::TilingPattern { tiling: id, matrix })
}
fn resolve_pattern_uncached(&mut self, name: NameId, under: &[f64]) -> Option<SemColor> {
let patterns = self.resource_subdict(self.names.known.pattern)?;
let entry = patterns.as_dict()?.get(name)?.clone();
let object = entry.as_reference();
let obj = self.resolve_obj(&entry)?;
let dict = obj.as_dict()?.clone();
let pattern_type = dict_int(&dict, self.intern(b"PatternType")).unwrap_or(0);
// `/Matrix` maps pattern space to the *default space of the stream
// referencing the pattern* (§8.7.3.1) — compose that anchor in, so a
// pattern used inside a form or soft-mask group invoked under a CTM
// (skew, scale) lands where the group's content does. Identity for
// page-level content (`pattern_base` is identity there).
let matrix = read_matrix(&dict, self.intern(b"Matrix")).then(self.pattern_base);
match pattern_type {
2 => {
// Shading pattern: resolve its `/Shading` dictionary/stream.
let shading = self.resolve_obj(&dict.get(self.intern(b"Shading"))?.clone())?;
let kind = self.build_shading(&shading);
if matches!(kind, SemShadingKind::Unsupported { .. }) {
return None;
}
let bbox = self.shading_bbox(&shading);
let id = ShadingId(self.shadings.len() as u32);
self.shadings.push(SemShading { object, kind, bbox });
Some(SemColor::ShadingPattern {
shading: id,
matrix,
})
}
1 => {
// Tiling pattern: compile the cell content stream.
let PdfObject::Stream(stream) = &*obj else {
return None;
};
let tiling = self.compile_tiling(object, &stream.clone(), &dict, under)?;
let id = TilingId(self.tilings.len() as u32);
self.tilings.push(tiling);
Some(SemColor::TilingPattern { tiling: id, matrix })
}
_ => None,
}
}
/// Build a shading parameterization: axial/radial (types 2/3) with a
/// pre-sampled RGBA ramp, function-based (type 1) sampled on a grid,
/// and mesh shadings (types 4–7) decoded to triangles/patches;
/// unrecognized or malformed types degrade to a `/Background`-only hook.
/// The shading's `/BBox` (ISO 32000-1 §8.7.4.3): a temporary clip applied
/// when the shading is painted, in the shading's target coordinate space.
/// Normalized to `[x0, y0, x1, y1]` with `x0 ≤ x1`, `y0 ≤ y1`. Works for
/// both dictionary shadings (types 1–3) and stream shadings (mesh 4–7),
/// since `as_dict` yields a stream's dictionary too.
fn shading_bbox(&self, obj: &PdfObject) -> Option<[f32; 4]> {
let dict = obj.as_dict()?;
let r = read_rect(dict, self.intern(b"BBox"))?;
Some([
r[0].min(r[2]) as f32,
r[1].min(r[3]) as f32,
r[0].max(r[2]) as f32,
r[1].max(r[3]) as f32,
])
}
fn build_shading(&mut self, obj: &PdfObject) -> SemShadingKind {
let Some(dict) = obj.as_dict() else {
return SemShadingKind::Unsupported { background: None };
};
let dict = dict.clone();
let stype = dict_int(&dict, self.intern(b"ShadingType")).unwrap_or(0);
let domain = read_num_array(&dict, self.intern(b"Domain"))
.and_then(|a| (a.len() >= 2).then(|| [a[0], a[1]]))
.unwrap_or([0.0, 1.0]);
let extend = self.read_extend(&dict);
match stype {
1 => self.build_function_grid(&dict),
2 | 3 => {
let coords = read_num_array(&dict, self.intern(b"Coords")).unwrap_or_default();
let funcs = dict
.get(self.intern(b"Function"))
.cloned()
.and_then(|f| self.build_functions(&f))
.unwrap_or_default();
let ramp =
self.build_shading_ramp(&dict, &funcs, [domain[0] as f32, domain[1] as f32]);
let background = self.read_background(&dict);
if stype == 2 && coords.len() >= 4 {
SemShadingKind::Axial {
coords: [coords[0], coords[1], coords[2], coords[3]],
domain,
extend,
ramp,
background,
}
} else if stype == 3 && coords.len() >= 6 {
SemShadingKind::Radial {
coords: [
coords[0], coords[1], coords[2], coords[3], coords[4], coords[5],
],
domain,
extend,
ramp,
background,
}
} else {
SemShadingKind::Unsupported {
background: self.read_background(&dict),
}
}
}
4..=7 => {
// Mesh shadings live in a stream object (dict + packed data).
if let PdfObject::Stream(stream) = obj {
let stream = stream.clone();
self.build_mesh(stype, &stream, &dict)
} else {
SemShadingKind::Unsupported {
background: self.read_background(&dict),
}
}
}
_ => SemShadingKind::Unsupported {
background: self.read_background(&dict),
},
}
}
/// Sample a type 2/3 shading's `/Function` into a 256-entry RGBA ramp,
/// converting each sample through the shading's `/ColorSpace`. The function
/// outputs are components *in that space* (§8.7.4.5.3), so a
/// Separation/DeviceN shading emits colorant tints that must run through the
/// tint transform, and a CIE shading emits Lab/Cal components — exactly the
/// conversions the fill path (`eval_tint`/`eval_cie`) and the mesh path
/// (`cs_to_rgba`) already apply. Skipping this (the old `build_ramp`) fed
/// raw components to `comps_to_rgba`, which reads them by arity alone — a
/// 2-colorant DeviceN (e.g. `[/DeviceN [/Cyan /Black] …]`) then collapsed to
/// pure black, flooding whole-page background shadings.
fn build_shading_ramp(
&mut self,
dict: &Dictionary,
funcs: &[crate::function::Function],
domain: [f32; 2],
) -> Vec<[f32; 4]> {
let cs = dict
.get(self.intern(b"ColorSpace"))
.cloned()
.and_then(|o| self.resolve_shading_cs(&o));
const RAMP: usize = 256;
let mut ramp = Vec::with_capacity(RAMP);
for i in 0..RAMP {
let t = domain[0] + (i as f32 / (RAMP - 1) as f32) * (domain[1] - domain[0]);
let comps: Vec<f32> = funcs.iter().flat_map(|f| f.eval(t)).collect();
ramp.push(match &cs {
Some(ShadingCs::Tint(space)) => {
let vals: Vec<f64> = comps.iter().map(|v| *v as f64).collect();
let rgb = sem_color_to_rgb8(&self.eval_tint(space, &vals));
[
rgb[0] as f32 / 255.0,
rgb[1] as f32 / 255.0,
rgb[2] as f32 / 255.0,
1.0,
]
}
Some(ShadingCs::Cie(cie)) => {
let vals: Vec<f64> = comps.iter().map(|v| *v as f64).collect();
let rgb = sem_color_to_rgb8(&eval_cie(*cie, &vals));
[
rgb[0] as f32 / 255.0,
rgb[1] as f32 / 255.0,
rgb[2] as f32 / 255.0,
1.0,
]
}
Some(ShadingCs::Image(space)) => cs_to_rgba(space, &comps),
None => comps_to_rgba(&comps),
});
}
ramp
}
/// Classify a shading `/ColorSpace` for ramp conversion: Separation/DeviceN
/// carry a tint transform, CIE families carry conversion parameters, and
/// everything else (Device/ICCBased/Indexed) reduces to an image color
/// space that `cs_to_rgba` handles.
fn resolve_shading_cs(&mut self, obj: &PdfObject) -> Option<ShadingCs> {
let resolved = self.resolve_obj(obj)?;
if let PdfObject::Array(items) = &*resolved {
let items = items.clone();
if let Some(head) = items.first().and_then(PdfObject::as_name) {
match self.names.resolve(head).as_ref() {
b"Separation" | b"DeviceN" => {
if let Some(space) = self.build_tint_space_from_array(&items) {
return Some(ShadingCs::Tint(space));
}
}
b"Lab" | b"CalRGB" | b"CalGray" => {
if let Some(cie) = self.cie_space_from_items(&items) {
return Some(ShadingCs::Cie(cie));
}
}
_ => {}
}
}
}
self.resolve_image_colorspace(&resolved)
.map(ShadingCs::Image)
}
/// Type 1 (function-based) shading: sample the 2-in color function on a
/// fixed grid over `/Domain` (the backend interpolates cell-wise).
fn build_function_grid(&mut self, dict: &Dictionary) -> SemShadingKind {
let background = self.read_background(dict);
let domain = read_num_array(dict, self.intern(b"Domain"))
.and_then(|a| (a.len() >= 4).then(|| [a[0], a[1], a[2], a[3]]))
.unwrap_or([0.0, 1.0, 0.0, 1.0]);
let matrix = read_matrix(dict, self.intern(b"Matrix"));
let Some(funcs) = dict
.get(self.intern(b"Function"))
.cloned()
.and_then(|f| self.build_functions(&f))
.filter(|f| !f.is_empty())
else {
return SemShadingKind::Unsupported { background };
};
let cs = dict
.get(self.intern(b"ColorSpace"))
.cloned()
.and_then(|o| self.resolve_image_colorspace(&o));
// 64×64: fine enough that bilinear-free cell lookup is invisible at
// typical zoom, cheap enough to sample eagerly (4096 evaluations).
const GRID: u32 = 64;
let (gw, gh) = (GRID, GRID);
let mut colors = Vec::with_capacity((gw * gh) as usize);
for t in 0..gh {
for s in 0..gw {
let x = domain[0] + (s as f64 + 0.5) / gw as f64 * (domain[1] - domain[0]);
let y = domain[2] + (t as f64 + 0.5) / gh as f64 * (domain[3] - domain[2]);
let comps: Vec<f32> = funcs
.iter()
.flat_map(|f| f.eval_n(&[x as f32, y as f32]))
.collect();
colors.push(match &cs {
Some(c) => cs_to_rgba(c, &comps),
None => comps_to_rgba(&comps),
});
}
}
SemShadingKind::FunctionGrid {
domain,
matrix,
grid_w: gw,
grid_h: gh,
colors,
background,
}
}
/// Types 4–7: decode the mesh stream into triangles (4/5) or tensor
/// patches (6/7). Colors run through the optional `/Function` and the
/// shading's `/ColorSpace`, exactly like the type 2/3 ramp path.
fn build_mesh(
&mut self,
stype: i64,
stream: &crate::object::PdfStream,
dict: &Dictionary,
) -> SemShadingKind {
let background = self.read_background(dict);
let unsupported = SemShadingKind::Unsupported { background };
let Ok(data) = self.snapshot.decode_stream_data(stream, self.ctx) else {
return unsupported;
};
let funcs = dict
.get(self.intern(b"Function"))
.cloned()
.and_then(|f| self.build_functions(&f))
.unwrap_or_default();
let Some(cs) = dict
.get(self.intern(b"ColorSpace"))
.cloned()
.and_then(|o| self.resolve_image_colorspace(&o))
else {
return unsupported;
};
let ncomps = if funcs.is_empty() { cs.components() } else { 1 };
let Some(decode) = read_num_array(dict, self.intern(b"Decode")) else {
return unsupported;
};
if decode.len() < 4 + ncomps * 2 {
return unsupported;
}
let params = crate::content::mesh::MeshParams {
coord_bits: dict_int(dict, self.intern(b"BitsPerCoordinate"))
.unwrap_or(0)
.max(0) as u32,
component_bits: dict_int(dict, self.intern(b"BitsPerComponent"))
.unwrap_or(0)
.max(0) as u32,
flag_bits: dict_int(dict, self.intern(b"BitsPerFlag"))
.unwrap_or(0)
.max(0) as u32,
components: ncomps,
x: [decode[0] as f32, decode[1] as f32],
y: [decode[2] as f32, decode[3] as f32],
comp: (0..ncomps)
.map(|i| [decode[4 + 2 * i] as f32, decode[5 + 2 * i] as f32])
.collect(),
};
// Type 5 carries no flags; everything else requires a valid width.
if !params.valid(stype != 5) {
return unsupported;
}
let convert = |vals: &[f32]| -> [f32; 4] {
if funcs.is_empty() {
cs_to_rgba(&cs, vals)
} else {
let comps: Vec<f32> = funcs.iter().flat_map(|f| f.eval(vals[0])).collect();
cs_to_rgba(&cs, &comps)
}
};
match stype {
4 => {
let triangles = crate::content::mesh::read_free_triangles(&data, ¶ms, &convert);
if triangles.is_empty() {
unsupported
} else {
SemShadingKind::MeshTriangles {
shading_type: 4,
triangles,
background,
}
}
}
5 => {
let row = dict_int(dict, self.intern(b"VerticesPerRow")).unwrap_or(0);
if row < 2 {
return unsupported;
}
let triangles = crate::content::mesh::read_lattice_triangles(
&data,
¶ms,
row as usize,
&convert,
);
if triangles.is_empty() {
unsupported
} else {
SemShadingKind::MeshTriangles {
shading_type: 5,
triangles,
background,
}
}
}
6 | 7 => {
let patches =
crate::content::mesh::read_patches(&data, ¶ms, stype == 7, &convert);
if patches.is_empty() {
unsupported
} else {
SemShadingKind::MeshPatches {
shading_type: stype as u8,
patches,
background,
}
}
}
_ => unsupported,
}
}
fn read_extend(&mut self, dict: &Dictionary) -> [bool; 2] {
match dict.get(self.intern(b"Extend")) {
Some(PdfObject::Array(a)) if a.len() >= 2 => [
matches!(a[0], PdfObject::Boolean(true)),
matches!(a[1], PdfObject::Boolean(true)),
],
_ => [false, false],
}
}
fn read_background(&mut self, dict: &Dictionary) -> Option<[f32; 4]> {
let comps = read_num_array(dict, self.intern(b"Background"))?;
Some(comps_to_rgba(
&comps.iter().map(|v| *v as f32).collect::<Vec<_>>(),
))
}
/// Build the color function(s) of a shading: `/Function` may be a single
/// function or an array of single-output functions (one per component).
fn build_functions(&mut self, obj: &PdfObject) -> Option<Vec<crate::function::Function>> {
let resolved = self.resolve_obj(obj)?;
if let PdfObject::Array(items) = &*resolved {
let mut out = Vec::new();
for it in items.iter() {
out.push(self.build_function(it, 0)?);
}
Some(out)
} else {
Some(vec![self.build_function(obj, 0)?])
}
}
/// Build one PDF function. Handles Type 0 (sampled, both the 1-input
/// shading form → [`crate::function::Function::Sampled`] and the m-input
/// DeviceN form → `SampledN`), Type 2 (exponential), Type 3 (stitching)
/// and Type 4 (PostScript calculator → `PostScript`, falling back to
/// `Identity` on a malformed program). `depth` bounds Type 3 nesting so a
/// cyclic `/Functions` reference cannot recurse without limit
/// (malformed-resource guard).
fn build_function(&mut self, obj: &PdfObject, depth: u32) -> Option<crate::function::Function> {
if depth > self.limits.max_function_depth {
return None;
}
let resolved = self.resolve_obj(obj)?;
let dict = resolved.as_dict()?;
let ftype = dict_int(dict, self.intern(b"FunctionType"))?;
let domain = read_num_array(dict, self.intern(b"Domain"))
.and_then(|a| (a.len() >= 2).then(|| [a[0] as f32, a[1] as f32]))
.unwrap_or([0.0, 1.0]);
match ftype {
2 => {
let c0 = read_num_array(dict, self.intern(b"C0"))
.map(|v| v.iter().map(|x| *x as f32).collect())
.unwrap_or_else(|| vec![0.0]);
let c1 = read_num_array(dict, self.intern(b"C1"))
.map(|v| v.iter().map(|x| *x as f32).collect())
.unwrap_or_else(|| vec![1.0]);
let n = dict_num(dict, self.intern(b"N")).unwrap_or(1.0) as f32;
Some(crate::function::Function::Exponential { domain, c0, c1, n })
}
3 => {
let sub = dict.get(self.intern(b"Functions")).cloned()?;
let sub = self.resolve_obj(&sub)?;
let PdfObject::Array(items) = &*sub else {
return None;
};
let mut functions = Vec::new();
for it in items.iter() {
functions.push(self.build_function(it, depth + 1)?);
}
let bounds = read_num_array(dict, self.intern(b"Bounds"))
.map(|v| v.iter().map(|x| *x as f32).collect())
.unwrap_or_default();
let encode = read_num_array(dict, self.intern(b"Encode"))
.map(pairs_f32)
.unwrap_or_default();
Some(crate::function::Function::Stitching {
domain,
functions,
bounds,
encode,
})
}
0 => {
let PdfObject::Stream(stream) = &*resolved else {
return None;
};
let data = self.snapshot.decode_stream_data(stream, self.ctx).ok()?;
let sizes = read_num_array(dict, self.intern(b"Size"))?;
if sizes.is_empty() {
return None;
}
let bps = dict_int(dict, self.intern(b"BitsPerSample"))? as u32;
let range = read_num_array(dict, self.intern(b"Range")).map(pairs_f32)?;
let n_out = range.len();
if n_out == 0 {
return None;
}
if sizes.len() == 1 {
// ---- 1-input Type 0 (the shading hot path, unchanged) ----
let size = sizes[0] as usize;
// Bound the sample table against an absurd /Size (allocation
// guard): shadings only need modest resolution.
if size == 0 || size.saturating_mul(n_out) > MAX_SAMPLED_FN {
return None;
}
let encode = read_num_array(dict, self.intern(b"Encode"))
.and_then(|a| (a.len() >= 2).then(|| [a[0] as f32, a[1] as f32]))
.unwrap_or([0.0, (size.max(1) - 1) as f32]);
let decode = read_num_array(dict, self.intern(b"Decode"))
.map(pairs_f32)
.unwrap_or_else(|| range.clone());
let samples = decode_samples(&data, size, n_out, bps);
return Some(crate::function::Function::Sampled {
domain,
encode,
size,
n_out,
decode,
samples,
});
}
// ---- m-input Type 0 (DeviceN / tint transforms, §7.10.2) ----
// Samples are row-major with input 0 varying fastest, matching
// `Function::SampledN`; `decode_samples` reads them in stream
// order, which is exactly that layout.
let m = sizes.len();
let sizes: Vec<usize> = sizes.iter().map(|v| *v as usize).collect();
// Total grid points = product of the per-axis sizes. Fold with
// checked_mul so a corrupt /Size cannot overflow or over-allocate;
// then apply the same MAX_SAMPLED_FN cap as the 1-D path.
let mut points: usize = 1;
for &s in &sizes {
if s == 0 {
return None;
}
points = points.checked_mul(s)?;
}
if points.checked_mul(n_out).is_none_or(|t| t > MAX_SAMPLED_FN) {
return None;
}
// Per-axis /Domain and /Encode (2*m values each). Encode defaults
// per axis to `[0, size_i - 1]`, mirroring the 1-D convention.
let dom_pairs = read_num_array(dict, self.intern(b"Domain"))
.map(pairs_f32)
.unwrap_or_default();
let domain_n: Vec<[f32; 2]> = (0..m)
.map(|i| dom_pairs.get(i).copied().unwrap_or([0.0, 1.0]))
.collect();
let enc_pairs = read_num_array(dict, self.intern(b"Encode"))
.map(pairs_f32)
.unwrap_or_default();
let encode_n: Vec<[f32; 2]> = (0..m)
.map(|i| {
enc_pairs
.get(i)
.copied()
.unwrap_or([0.0, (sizes[i].max(1) - 1) as f32])
})
.collect();
let decode = read_num_array(dict, self.intern(b"Decode"))
.map(pairs_f32)
.unwrap_or_else(|| range.clone());
let samples = decode_samples(&data, points, n_out, bps);
Some(crate::function::Function::SampledN {
domain: domain_n,
encode: encode_n,
size: sizes,
n_out,
decode,
samples,
})
}
4 => {
// Type 4 (PostScript calculator, §7.10.5): a *stream* whose
// decoded bytes are the `{ … }` program. `/Range` is required
// (it fixes the output arity); without it we cannot build the
// function and return `None` for the caller to approximate.
let PdfObject::Stream(stream) = &*resolved else {
return None;
};
let range = read_num_array(dict, self.intern(b"Range")).map(pairs_f32)?;
if range.is_empty() {
return None;
}
let n_out = range.len();
let dom_pairs = read_num_array(dict, self.intern(b"Domain"))
.map(pairs_f32)
.unwrap_or_default();
let domain_n: Vec<[f32; 2]> = if dom_pairs.is_empty() {
vec![[0.0, 1.0]]
} else {
dom_pairs
};
let bytes = self.snapshot.decode_stream_data(stream, self.ctx).ok()?;
match crate::function::parse_postscript(&bytes) {
Some(program) => Some(crate::function::Function::PostScript {
domain: domain_n,
range,
program,
}),
// Malformed program text: fall back to Identity of the right
// arity so the page still compiles (tolerant).
None => Some(crate::function::Function::Identity { n_out }),
}
}
_ => None,
}
}
/// Compile a tiling pattern's (PatternType 1) cell content stream into a
/// nested [`SemanticPage`]. Reuses the same interpreter machinery under a
/// fresh graphics state, guarded by the shared recursion depth.
fn compile_tiling(
&mut self,
object: Option<ObjectId>,
stream: &PdfStream,
dict: &Dictionary,
under: &[f64],
) -> Option<SemTiling> {
if self.invoke_depth >= self.limits.max_invoke_depth {
return None;
}
let paint_type = dict_int(dict, self.intern(b"PaintType")).unwrap_or(1);
let uncolored = paint_type == 2;
let bbox = read_rect(dict, self.intern(b"BBox")).unwrap_or([0.0, 0.0, 1.0, 1.0]);
let x_step = dict_num(dict, self.intern(b"XStep")).unwrap_or(bbox[2] - bbox[0]);
let y_step = dict_num(dict, self.intern(b"YStep")).unwrap_or(bbox[3] - bbox[1]);
let under_color = under_rgba(under);
let content = self.snapshot.decode_stream_data(stream, self.ctx).ok()?;
let pattern_res = match stream.dict.get(self.names.known.resources).cloned() {
Some(res) => self.resolve_obj(&res),
None => self.resources.clone(),
};
// Compile the cell in a fresh sub-interpreter (its own state + tables);
// the recursion depth is shared to bound nested patterns/forms.
let mut sub = Interpreter::new(
self.snapshot,
self.ctx,
self.limits,
pattern_res,
self.system_fonts.clone(),
);
// The cell is a separate interpretation but the same document scope:
// it inherits the page's resources for categories its own pattern
// `/Resources` omits, exactly as a form does.
sub.page_resources = self.page_resources.clone();
sub.invoke_depth = self.invoke_depth + 1;
sub.ops
.push(SemanticOp::BeginPaintOrigin(PaintOrigin::TilingPatternCell));
let result = sub.run(&content);
sub.ops.push(SemanticOp::EndPaintOrigin);
if result.is_err() {
return None;
}
let cell = sub.finish(PageBounds {
crop: Rect {
x0: bbox[0],
y0: bbox[1],
x1: bbox[2],
y1: bbox[3],
},
rotate: 0,
});
Some(SemTiling {
object,
uncolored,
under_color,
bbox,
x_step,
y_step,
cell: Arc::new(cell),
})
}
// --- resource resolution ----------------------------------------------
/// Resolve a category sub-dictionary of the active resources (e.g.
/// `/Font`, `/XObject`), following an indirect reference if present.
fn resource_subdict(&mut self, category: NameId) -> Option<Arc<PdfObject>> {
if let Some(res) = self.resources.clone()
&& let Some(entry) = res.as_dict().and_then(|d| d.get(category)).cloned()
{
return self.resolve_obj(&entry);
}
// The active `/Resources` has no dictionary for this category at all:
// inherit the page's (PDFium `CPDF_StreamContentParser::
// FindResourceHolder`). Forms in the wild routinely carry a partial
// `/Resources` and expect the page's to fill the gaps — pdfjs/issue5939
// paints with patterns its form never declares.
//
// The fallback is per *category*, not per name: a form that does
// declare `/Pattern` owns that namespace completely, and a name it
// omits stays unresolved rather than reaching past it. That is what
// keeps pdfjs/issue8565 correct, where three scopes each define their
// own `/Sh1`.
let page = self.page_resources.clone()?;
let entry = page.as_dict()?.get(category)?.clone();
self.resolve_obj(&entry)
}
/// Resolve an object to a shared value: references go through the
/// repository; direct values are wrapped as-is.
/// Read an integer entry, following an indirect reference.
///
/// Image dictionaries do carry `/Height 5 0 R` in the wild (issue5592.pdf,
/// and the Edgerton scan). A direct-only read yields 0 there, which reaches
/// the codec as a zero dimension and drops the image, so the page renders
/// blank while every other viewer draws it.
fn dict_int_indirect(&mut self, dict: &Dictionary, key: NameId) -> Option<i64> {
let obj = dict.get(key)?.clone();
if let Some(v) = obj.as_int() {
return Some(v);
}
self.resolve_obj(&obj)?.as_int()
}
fn resolve_obj(&mut self, obj: &PdfObject) -> Option<Arc<PdfObject>> {
match obj {
PdfObject::Reference(id) => self
.snapshot
.objects()
.resolve(self.snapshot, *id, self.ctx)
.ok(),
direct => Some(Arc::new(direct.clone())),
}
}
}
/// Key of one resolved font resource: the font dictionary object plus the
/// system-font provider that would answer a substitution for it.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
struct FontCacheKey {
object: ObjectId,
provider: usize,
}
/// Document-scoped cache of resolved font resources, held in the snapshot's
/// extension slot (`DocumentSnapshot::extension`) so it outlives the per-page
/// interpreter and parse context.
///
/// Resolving a simple embedded font means inflating its `/FontFile` stream,
/// parsing the program (Type 1 charstrings, CFF, TrueType tables), and walking
/// all 256 codes of its encoding through the program's name and cmap lookups;
/// a composite font parses its CMap and `/W` arrays. None of that depends on
/// the page, yet every page compile used to redo it for every font it
/// selected — on a text-only page that was most of the compile time. The
/// cached `SemFont` carries only shared `Arc`s and small vectors, so a hit is
/// a clone. Type 3 fonts are not cached (their CharProcs are interpreted
/// inline and tracked per page); a font reached through a direct dictionary
/// has no object identity and is resolved as before.
///
/// Bounded by retained program bytes; on overflow the whole map is dropped,
/// which only costs the next page one re-resolution per font.
#[derive(Debug, Default)]
pub(crate) struct FontResourceCache {
inner: std::sync::Mutex<FontResourceCacheInner>,
}
#[derive(Debug, Default)]
struct FontResourceCacheInner {
fonts: HashMap<FontCacheKey, Arc<FontSlot>>,
/// Retained embedded-program bytes plus a per-entry allowance.
bytes: usize,
}
/// One font's cache entry: empty while its first resolver works, then set
/// once. `resolving` is held across that resolution so a concurrent compiler
/// of the same font waits for the result (a few milliseconds) rather than
/// parsing the program a second time; the map lock itself is never held
/// while resolving.
#[derive(Debug, Default)]
struct FontSlot {
font: std::sync::OnceLock<Arc<SemFont>>,
resolving: std::sync::Mutex<()>,
}
impl FontSlot {
fn get(&self) -> Option<&Arc<SemFont>> {
self.font.get()
}
/// Serialise resolvers of this font. A panic in a resolver poisons the
/// lock; the next resolver simply takes over.
fn resolving(&self) -> std::sync::MutexGuard<'_, ()> {
self.resolving
.lock()
.unwrap_or_else(|poisoned| poisoned.into_inner())
}
}
impl FontResourceCache {
/// Retained-bytes ceiling: a 300-page book of per-page subset fonts stays
/// well under this; a pathological document merely cycles the map.
const MAX_BYTES: usize = 64 << 20;
/// Per-entry allowance for the metrics, maps, and tables beside the
/// program bytes.
const ENTRY_OVERHEAD: usize = 16 << 10;
/// The entry for `key`, created empty if absent. The caller checks
/// [`FontSlot::get`], otherwise resolves under [`FontSlot::resolving`]
/// and publishes with [`FontResourceCache::insert`].
fn slot(&self, key: FontCacheKey) -> Arc<FontSlot> {
let mut inner = self
.inner
.lock()
.unwrap_or_else(|poisoned| poisoned.into_inner());
Arc::clone(inner.fonts.entry(key).or_default())
}
/// Publish a resolved font into its slot and charge its bytes. Type 3
/// fonts are never published, so their (empty) slot stays resolvable by
/// every page. On overflow the whole map is dropped; a slot an in-flight
/// resolver still holds is published into that detached slot only, and
/// the next page re-resolves the font into a fresh one.
fn insert(&self, key: FontCacheKey, slot: &Arc<FontSlot>, font: &SemFont) {
if font.subtype == b"Type3" {
return;
}
let charge =
font.program.as_ref().map_or(0, |program| program.len()) + Self::ENTRY_OVERHEAD;
let mut inner = self
.inner
.lock()
.unwrap_or_else(|poisoned| poisoned.into_inner());
if inner.bytes.saturating_add(charge) > Self::MAX_BYTES {
inner.fonts.clear();
inner.bytes = 0;
}
let published = slot.font.set(Arc::new(font.clone())).is_ok();
let mapped = inner
.fonts
.get(&key)
.is_some_and(|current| Arc::ptr_eq(current, slot));
if published && mapped {
inner.bytes += charge;
}
}
}
// --- free helpers ----------------------------------------------------------
/// Resolve a page-level concatenated offset to its source stream object and
/// stream-relative span. Segments are disjoint and ascending; an offset that
/// lands in no segment (only the `'\n'` separators between them, which never
/// start an operator) yields no stream and the span unadjusted.
fn segment_span(
segments: &[ContentSegment],
start: usize,
end: usize,
) -> (Option<ObjectId>, (usize, usize)) {
let count = segments.partition_point(|seg| seg.start <= start);
let Some(seg) = count.checked_sub(1).and_then(|i| segments.get(i)) else {
return (None, (start, end));
};
if start.saturating_sub(seg.start) >= seg.len {
return (None, (start, end));
}
(
seg.object,
(
start.saturating_sub(seg.start),
end.saturating_sub(seg.start),
),
)
}
fn get(nums: &[f64], i: usize) -> f64 {
nums.get(i).copied().unwrap_or(0.0)
}
/// Decode a PDF text string into the UTF-16 representation retained by the
/// semantic layer. UTF-16 BOM forms and PDFDocEncoding are decoded here while
/// the marked-content string is still available.
fn decode_pdf_text_string(bytes: &[u8]) -> Vec<u16> {
crate::object::decode_text_string(bytes)
}
/// Convert an alternate-space [`SemColor`] (as produced by `eval_tint`) to an
/// 8-bit sRGB triple, using the same `pdf_color` conversions as the fill path.
/// Only the device families `eval_tint` yields are handled; anything else
/// (which it never returns) falls back to black.
fn sem_color_to_rgb8(c: &SemColor) -> [u8; 3] {
let to = |v: f32| (v.clamp(0.0, 1.0) * 255.0).round() as u8;
let rgb = match c {
SemColor::DeviceGray(g) => crate::color::gray_to_rgb(*g as f32),
SemColor::DeviceRgb(r, g, b) => [*r as f32, *g as f32, *b as f32],
SemColor::DeviceCmyk(c, m, y, k) => {
crate::color::cmyk_to_rgb(*c as f32, *m as f32, *y as f32, *k as f32)
}
_ => [0.0, 0.0, 0.0],
};
[to(rgb[0]), to(rgb[1]), to(rgb[2])]
}
fn dict_int(dict: &Dictionary, key: NameId) -> Option<i64> {
dict.get(key).and_then(PdfObject::as_int)
}
fn dict_num(dict: &Dictionary, key: NameId) -> Option<f64> {
dict.get(key).and_then(PdfObject::as_number)
}
fn dict_bool(dict: &Dictionary, key: NameId) -> bool {
matches!(dict.get(key), Some(PdfObject::Boolean(true)))
}
/// Read a numeric array value (direct only — the arrays this reads, like
/// `/Coords`, `/Domain`, `/C0`, are always direct in practice).
fn read_num_array(dict: &Dictionary, key: NameId) -> Option<Vec<f64>> {
match dict.get(key) {
Some(PdfObject::Array(a)) => Some(a.iter().filter_map(PdfObject::as_number).collect()),
_ => None,
}
}
/// Group a flat numeric array into `[a, b]` pairs (drops a trailing odd item).
fn pairs_f32(v: Vec<f64>) -> Vec<[f32; 2]> {
v.chunks_exact(2)
.map(|c| [c[0] as f32, c[1] as f32])
.collect()
}
/// Whether a baked 256×RGB tint ramp is (near-)constant — i.e. the tint
/// transform's output does not meaningfully vary across the whole tint range.
/// Threshold 8/255 per channel: generous enough to admit real ramps into a
/// pale spot colour, tight enough to catch flat/errored/clamped bakes.
fn lut_is_degenerate(rgb: &[u8]) -> bool {
let mut min = [u8::MAX; 3];
let mut max = [u8::MIN; 3];
for px in rgb.chunks_exact(3) {
for c in 0..3 {
min[c] = min[c].min(px[c]);
max[c] = max[c].max(px[c]);
}
}
(0..3).all(|c| max[c] - min[c] < 8)
}
/// Read an inline image's `/DP` (`/DecodeParms`) operand into codec
/// parameters. The operand is a dict or an array of dicts parallel to the
/// filter list; keys inside the parms dict are the standard (unabbreviated)
/// names per Table 93. Mirrors `read_codec_parms` for the XObject path,
/// minus `/JBIG2Globals` (an indirect stream an inline image cannot carry).
fn inline_codec_parms(op: &Operand) -> Option<crate::page_ir::CodecParms> {
let dicts: Vec<&[(Vec<u8>, Operand)]> = match op {
Operand::Dict(d) => vec![d.as_slice()],
Operand::Array(items) => items
.iter()
.filter_map(|e| match e {
Operand::Dict(d) => Some(d.as_slice()),
_ => None,
})
.collect(),
_ => return None,
};
if dicts.is_empty() {
return None;
}
let mut out = crate::page_ir::CodecParms {
// The spec's CCITT defaults (ISO 32000-1 table 11).
columns: 1728,
end_of_block: true,
..Default::default()
};
for d in dicts {
for (key, value) in d {
match key.as_slice() {
b"K" => {
if let Some(k) = value.as_int() {
out.k = k as i32;
}
}
b"Columns" => {
if let Some(c) = value.as_int() {
out.columns = c.max(0) as u32;
}
}
b"Rows" => {
if let Some(r) = value.as_int() {
out.rows = r.max(0) as u32;
}
}
b"BlackIs1" => {
if let Operand::Bool(v) = value {
out.black_is_1 = *v;
}
}
b"EncodedByteAlign" => {
if let Operand::Bool(v) = value {
out.byte_align = *v;
}
}
b"EndOfLine" => {
if let Operand::Bool(v) = value {
out.end_of_line = *v;
}
}
b"EndOfBlock" => {
if let Operand::Bool(v) = value {
out.end_of_block = *v;
}
}
_ => {}
}
}
}
Some(out)
}
/// Build a color-key `/Mask` from an inline image's array operand. Same
/// validation as the XObject path (`2 × components` integer bounds within
/// `[0, 2^bpc − 1]`); a malformed array is ignored (→ `None`).
fn inline_color_key_mask(
op: &Operand,
color_space: Option<&ImageColorSpace>,
bpc: u8,
) -> Option<crate::page_ir::ImageMask> {
let Operand::Array(items) = op else {
return None;
};
let ncomp = color_space.map(ImageColorSpace::components).unwrap_or(1);
if items.len() != ncomp * 2 {
return None;
}
let max_raw: i64 = (1i64 << bpc.min(31)) - 1;
let mut ranges = Vec::with_capacity(ncomp);
for pair in items.chunks_exact(2) {
let lo = pair[0].as_int()?;
let hi = pair[1].as_int()?;
if lo < 0 || hi < 0 || lo > max_raw || hi > max_raw || lo > hi {
return None;
}
ranges.push([lo as u32, hi as u32]);
}
Some(crate::page_ir::ImageMask::ColorKey(Arc::from(ranges)))
}
/// Convert raw color components to straight RGBA by arity (the device
/// approximation used throughout — 1=gray, 3=rgb, 4=cmyk).
/// Convert color components in a resolved shading `/ColorSpace` to straight
/// RGBA — the mesh-shading counterpart of [`comps_to_rgba`], additionally
/// handling `Indexed` (palette lookup) and single-tint (`TintLut`) spaces.
fn cs_to_rgba(cs: &ImageColorSpace, comps: &[f32]) -> [f32; 4] {
match cs {
ImageColorSpace::Gray | ImageColorSpace::Rgb | ImageColorSpace::Cmyk => {
comps_to_rgba(comps)
}
ImageColorSpace::Indexed {
base,
hival,
lookup,
} => {
let n = base.components();
let idx = (comps.first().copied().unwrap_or(0.0).round().max(0.0) as u32).min(*hival)
as usize;
let vals: Vec<f32> = (0..n)
.map(|k| {
lookup
.get(idx * n + k)
.map(|b| *b as f32 / 255.0)
.unwrap_or(0.0)
})
.collect();
// Bounded recursion: a resolved Indexed base is never itself
// Indexed (the resolver flattens), and the tree is finite.
cs_to_rgba(base, &vals)
}
ImageColorSpace::TintLut { rgb } => {
let idx =
(comps.first().copied().unwrap_or(0.0).clamp(0.0, 1.0) * 255.0).round() as usize;
let at = |k: usize| {
rgb.get(idx * 3 + k)
.map(|b| *b as f32 / 255.0)
.unwrap_or(0.0)
};
[at(0), at(1), at(2), 1.0]
}
ImageColorSpace::IccRgb { trc, matrix } => {
let at = |k: usize| comps.get(k).copied().unwrap_or(0.0).clamp(0.0, 1.0);
let rgb = crate::color::icc::to_srgb_with(trc, matrix, [at(0), at(1), at(2)]);
[rgb[0], rgb[1], rgb[2], 1.0]
}
ImageColorSpace::IccCmyk { transform } => {
let at = |k: usize| comps.get(k).copied().unwrap_or(0.0).clamp(0.0, 1.0);
let rgb = crate::color::icc::cmyk_to_srgb_with(
transform.grid as usize,
[
&transform.input_tables[0],
&transform.input_tables[1],
&transform.input_tables[2],
&transform.input_tables[3],
],
&transform.clut,
[
&transform.output_tables[0],
&transform.output_tables[1],
&transform.output_tables[2],
],
[at(0), at(1), at(2), at(3)],
);
[rgb[0], rgb[1], rgb[2], 1.0]
}
ImageColorSpace::TintLut2 { rgb } => {
let ix = |k: usize| {
(comps.get(k).copied().unwrap_or(0.0).clamp(0.0, 1.0) * 255.0).round() as usize
};
let o = (ix(0).min(255) * 256 + ix(1).min(255)) * 3;
let at = |k: usize| rgb.get(o + k).map(|b| *b as f32 / 255.0).unwrap_or(0.0);
[at(0), at(1), at(2), 1.0]
}
ImageColorSpace::Lab { white_point, range } => {
// Mesh-shading components arrive in the space's own units, so L*
// and the signed a*/b* pass straight through.
let g = |k: usize| comps.get(k).copied().unwrap_or(0.0);
let rgb = crate::color::lab_to_rgb(g(0), g(1), g(2), *white_point, *range);
[rgb[0], rgb[1], rgb[2], 1.0]
}
}
}
/// The underlying colour of an uncoloured tiling pattern, from the numeric
/// operands that precede the pattern name in `scn`/`SCN`.
fn under_rgba(under: &[f64]) -> [f32; 4] {
comps_to_rgba(&under.iter().map(|v| *v as f32).collect::<Vec<_>>())
}
fn comps_to_rgba(comps: &[f32]) -> [f32; 4] {
let c = |v: f32| v.clamp(0.0, 1.0);
let [r, g, b] = match comps.len() {
1 => crate::color::gray_to_rgb(c(comps[0])),
3 => [c(comps[0]), c(comps[1]), c(comps[2])],
4 => crate::color::cmyk_to_rgb(c(comps[0]), c(comps[1]), c(comps[2]), c(comps[3])),
_ => [0.0, 0.0, 0.0],
};
[r, g, b, 1.0]
}
/// A type 2/3 shading `/ColorSpace`, classified for ramp conversion by
/// [`Interpreter::resolve_shading_cs`].
enum ShadingCs {
/// Separation / DeviceN: run function outputs through the tint transform.
Tint(Arc<TintSpace>),
/// CIE-based (Lab/CalRGB/CalGray): convert via the CIE math.
Cie(CieSpace),
/// Device / ICCBased / Indexed: `cs_to_rgba` handles it by arity.
Image(crate::page_ir::ImageColorSpace),
}
/// Decode a Type 0 sampled function's packed samples: `count = size * n_out`
/// values of `bps` bits each, MSB-first, normalized to `[0, 1]`.
fn decode_samples(data: &[u8], size: usize, n_out: usize, bps: u32) -> Vec<f32> {
let count = size.saturating_mul(n_out);
let max = ((1u64 << bps.min(32)) - 1).max(1) as f32;
let mut out = Vec::with_capacity(count);
let mut bit = 0usize;
for _ in 0..count {
let mut val: u64 = 0;
for _ in 0..bps {
let byte = bit / 8;
let shift = 7 - (bit % 8);
let b = data.get(byte).map(|v| (v >> shift) & 1).unwrap_or(0);
val = (val << 1) | b as u64;
bit += 1;
}
out.push(val as f32 / max);
}
out
}
/// Read a 6-element numeric array as a [`Matrix`], defaulting to identity.
fn read_matrix(dict: &Dictionary, key: NameId) -> Matrix {
match dict.get(key) {
Some(PdfObject::Array(a)) if a.len() >= 6 => {
let n = |i: usize| a[i].as_number();
match (n(0), n(1), n(2), n(3), n(4), n(5)) {
(Some(a0), Some(b), Some(c), Some(d), Some(e), Some(f)) => Matrix {
a: a0,
b,
c,
d,
e,
f,
},
_ => Matrix::IDENTITY,
}
}
_ => Matrix::IDENTITY,
}
}
/// Read a 4-element numeric array as `[x0, y0, x1, y1]`.
fn read_rect(dict: &Dictionary, key: NameId) -> Option<[f64; 4]> {
match dict.get(key) {
Some(PdfObject::Array(a)) if a.len() >= 4 => Some([
a[0].as_number()?,
a[1].as_number()?,
a[2].as_number()?,
a[3].as_number()?,
]),
_ => None,
}
}
/// Parse a CIDFont `/W` array into `(cid_start, cid_end, width)` ranges. Two
/// entry forms (ISO 32000-1 Table 117): `c [w1 … wn]` (consecutive CIDs from
/// `c`) and `c_first c_last w` (a shared-width range).
fn parse_cid_w(items: &[PdfObject]) -> Vec<(u32, u32, f32)> {
let mut ranges = Vec::new();
let mut i = 0;
while i < items.len() {
let Some(c) = items[i].as_int() else { break };
i += 1;
let Some(next) = items.get(i) else { break };
match next {
PdfObject::Array(ws) => {
for (j, w) in ws.iter().enumerate() {
if let Some(wn) = w.as_number() {
let cid = (c + j as i64).max(0) as u32;
ranges.push((cid, cid, wn as f32));
}
}
i += 1;
}
_ => {
let c_last = next.as_int();
let w = items.get(i + 1).and_then(PdfObject::as_number);
i += 2;
if let (Some(cl), Some(wn)) = (c_last, w) {
ranges.push((c.max(0) as u32, cl.max(0) as u32, wn as f32));
}
}
}
}
ranges
}
/// Parse a CIDFont `/W2` array into `(cid_start, cid_end, [w1y, vx, vy])`
/// ranges (ISO 32000-1 §9.7.4.3, mirroring [`parse_cid_w`]). Two entry forms:
/// `c [w1y vx vy …]` (triples for consecutive CIDs from `c`) and
/// `c_first c_last w1y vx vy` (a shared-metrics range).
fn parse_cid_w2(items: &[PdfObject]) -> Vec<(u32, u32, [f32; 3])> {
let mut ranges = Vec::new();
let mut i = 0;
while i < items.len() {
let Some(c) = items[i].as_int() else { break };
i += 1;
let Some(next) = items.get(i) else { break };
match next {
PdfObject::Array(ms) => {
for (j, triple) in ms.chunks(3).enumerate() {
if triple.len() < 3 {
break;
}
let nums: Vec<f32> = triple
.iter()
.filter_map(|v| v.as_number().map(|n| n as f32))
.collect();
if nums.len() == 3 {
let cid = (c + j as i64).max(0) as u32;
ranges.push((cid, cid, [nums[0], nums[1], nums[2]]));
}
}
i += 1;
}
_ => {
let c_last = next.as_int();
let w1y = items.get(i + 1).and_then(PdfObject::as_number);
let vx = items.get(i + 2).and_then(PdfObject::as_number);
let vy = items.get(i + 3).and_then(PdfObject::as_number);
i += 4;
if let (Some(cl), Some(w), Some(x), Some(y)) = (c_last, w1y, vx, vy) {
ranges.push((
c.max(0) as u32,
cl.max(0) as u32,
[w as f32, x as f32, y as f32],
));
}
}
}
}
ranges
}
/// Axis-aligned bounds of a `/BBox` rectangle mapped through `ctm`. All four
/// corners are transformed (the CTM may rotate/shear), then their extent is
/// taken.
fn group_bounds(bbox: Option<[f64; 4]>, ctm: Matrix) -> Rect {
let Some([x0, y0, x1, y1]) = bbox else {
return Rect::default();
};
let corners = [
ctm.apply(Point { x: x0, y: y0 }),
ctm.apply(Point { x: x1, y: y0 }),
ctm.apply(Point { x: x1, y: y1 }),
ctm.apply(Point { x: x0, y: y1 }),
];
let mut r = Rect {
x0: corners[0].x,
y0: corners[0].y,
x1: corners[0].x,
y1: corners[0].y,
};
for p in &corners[1..] {
r.x0 = r.x0.min(p.x);
r.y0 = r.y0.min(p.y);
r.x1 = r.x1.max(p.x);
r.y1 = r.y1.max(p.y);
}
r
}
/// The §12.5.5 appearance-fitting matrix `A`: the form's `/BBox` corners are
/// mapped through its `/Matrix`, their axis-aligned extent is taken, and `A`
/// is the translate+scale carrying that extent onto the annotation's `/Rect`.
/// `None` when either extent is degenerate (nothing sensible to paint —
/// PDFium's `CFX_Matrix::MatchRect` on an empty rect degenerates too).
fn appearance_matrix(bbox: Option<[f64; 4]>, matrix: Matrix, rect: [f64; 4]) -> Option<Matrix> {
let [rx0, ry0, rx1, ry1] = rect;
let (rw, rh) = (rx1 - rx0, ry1 - ry0);
if !(rw > 0.0 && rh > 0.0 && rw.is_finite() && rh.is_finite()) {
return None;
}
let [bx0, by0, bx1, by1] = bbox?;
let corners = [
matrix.apply(Point { x: bx0, y: by0 }),
matrix.apply(Point { x: bx1, y: by0 }),
matrix.apply(Point { x: bx1, y: by1 }),
matrix.apply(Point { x: bx0, y: by1 }),
];
let (mut tx0, mut ty0, mut tx1, mut ty1) =
(corners[0].x, corners[0].y, corners[0].x, corners[0].y);
for p in &corners[1..] {
tx0 = tx0.min(p.x);
ty0 = ty0.min(p.y);
tx1 = tx1.max(p.x);
ty1 = ty1.max(p.y);
}
let (tw, th) = (tx1 - tx0, ty1 - ty0);
if !(tw > 0.0 && th > 0.0 && tw.is_finite() && th.is_finite()) {
return None;
}
let sx = rw / tw;
let sy = rh / th;
Some(Matrix {
a: sx,
b: 0.0,
c: 0.0,
d: sy,
e: rx0 - tx0 * sx,
f: ry0 - ty0 * sy,
})
}
/// A closed rectangle path (`re` geometry): MoveTo, 3×LineTo, Close.
fn rect_path(x: f64, y: f64, w: f64, h: f64) -> PathData {
let verbs = [
PathVerb::MoveTo,
PathVerb::LineTo,
PathVerb::LineTo,
PathVerb::LineTo,
PathVerb::Close,
];
let points = [
Point { x, y },
Point { x: x + w, y },
Point { x: x + w, y: y + h },
Point { x, y: y + h },
];
PathData {
verbs: verbs.into(),
points: points.into(),
}
}
/// Map a `/BM` blend-mode name to the IR blend mode; unknown names fall back
/// to Normal (ISO 32000-1 §11.3.5).
fn map_blend_mode(name: &[u8]) -> BlendMode {
match name {
b"Multiply" => BlendMode::Multiply,
b"Screen" => BlendMode::Screen,
b"Overlay" => BlendMode::Overlay,
b"Darken" => BlendMode::Darken,
b"Lighten" => BlendMode::Lighten,
b"ColorDodge" => BlendMode::ColorDodge,
b"ColorBurn" => BlendMode::ColorBurn,
b"HardLight" => BlendMode::HardLight,
b"SoftLight" => BlendMode::SoftLight,
b"Difference" => BlendMode::Difference,
b"Exclusion" => BlendMode::Exclusion,
b"Hue" => BlendMode::Hue,
b"Saturation" => BlendMode::Saturation,
b"Color" => BlendMode::Color,
b"Luminosity" => BlendMode::Luminosity,
// "Normal", "Compatible", or anything unknown.
_ => BlendMode::Normal,
}
}
fn map_line_cap(v: f64) -> LineCap {
match v as i64 {
1 => LineCap::Round,
2 => LineCap::Square,
_ => LineCap::Butt,
}
}
fn map_line_join(v: f64) -> LineJoin {
match v as i64 {
1 => LineJoin::Round,
2 => LineJoin::Bevel,
_ => LineJoin::Miter,
}
}
fn initial_color(space: &ColorSpace) -> SemColor {
match space {
ColorSpace::DeviceGray => SemColor::DeviceGray(0.0),
ColorSpace::DeviceRgb => SemColor::DeviceRgb(0.0, 0.0, 0.0),
ColorSpace::DeviceCmyk => SemColor::DeviceCmyk(0.0, 0.0, 0.0, 1.0),
ColorSpace::Named(id) => SemColor::Components {
space: *id,
values: Vec::new(),
},
ColorSpace::Pattern(_) => SemColor::DeviceGray(0.0),
}
}
/// True for image-codec filters (DCT/JPX/JBIG2/CCITT) whose bytes this build
/// does not decode; such images carry no samples and are routed away by the
/// page's `NEEDS_*` feature.
/// Advance widths for a substituted simple font that supplies no `/Widths`.
///
/// ISO 32000-1 §9.6.2.1: such a font uses the standard-14 metrics. The
/// bundled faces are metric-compatible with those fonts, so reading each
/// code's glyph advance out of the face *is* the standard metric — no
/// separate AFM table needed. Advances are in 1/1000 text-space units, which
/// is the faces' own units-per-em.
fn standard_widths(
prog: &crate::font::FontProgram,
gids: &[u32; 256],
) -> crate::font::SimpleWidths {
let scale = 1000.0 / prog.units_per_em().max(1) as f32;
let widths: Vec<f32> = (0..256)
.map(|code| prog.advance(gids[code]).map(|w| w * scale).unwrap_or(0.0))
.collect();
crate::font::SimpleWidths::new(0, widths, 0.0)
}
/// Map a canonical codec filter name to its IR kind. `None` means the filter
/// is a general (non-codec) one — the stream-decode layer handled it.
fn codec_kind(name: &[u8]) -> Option<crate::page_ir::ImageCodecKind> {
use crate::page_ir::ImageCodecKind as K;
match name {
b"DCTDecode" => Some(K::Dct),
b"JPXDecode" => Some(K::Jpx),
b"JBIG2Decode" => Some(K::Jbig2),
b"CCITTFaxDecode" => Some(K::CcittFax),
_ => None,
}
}
fn collect_filters(value: &Operand) -> Vec<Vec<u8>> {
match value {
Operand::Name(n) => vec![canonical_filter(n)],
Operand::Array(a) => a
.iter()
.filter_map(Operand::as_name)
.map(canonical_filter)
.collect(),
_ => Vec::new(),
}
}
/// Expand the inline-image filter abbreviations to their canonical names.
fn canonical_filter(name: &[u8]) -> Vec<u8> {
match name {
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(),
other => other.to_vec(),
}
}
/// Gather a page's content bytes: a single content stream, or an array of
/// streams concatenated with a separating newline (ISO 32000-1 §7.8.2 — the
/// streams form one logical stream but a token must not span the boundary).
pub(crate) fn gather_content(
snapshot: &DocumentSnapshot,
contents: Option<&PdfObject>,
ctx: &mut ParseContext,
limits: &ContentLimits,
) -> Result<Vec<u8>, ContentError> {
let Some(contents) = contents else {
return Ok(Vec::new());
};
let mut out = Vec::new();
let mut sink = ContentSink {
out: &mut out,
segments: &mut None,
};
append_content(snapshot, contents, ctx, &mut sink, None, 0, limits)?;
Ok(out)
}
/// Like [`gather_content`], plus the per-stream segment map the audit trace
/// resolves page-level offsets through. The bytes are identical to what
/// [`gather_content`] produces for the same input.
pub(crate) fn gather_content_mapped(
snapshot: &DocumentSnapshot,
contents: Option<&PdfObject>,
ctx: &mut ParseContext,
limits: &ContentLimits,
) -> Result<(Vec<u8>, Vec<ContentSegment>), ContentError> {
let Some(contents) = contents else {
return Ok((Vec::new(), Vec::new()));
};
let mut out = Vec::new();
let mut segments = Some(Vec::new());
let mut sink = ContentSink {
out: &mut out,
segments: &mut segments,
};
append_content(snapshot, contents, ctx, &mut sink, None, 0, limits)?;
Ok((out, segments.unwrap_or_default()))
}
/// Where [`append_content`] accumulates: the concatenated bytes plus, for the
/// audit path only, the per-stream segment map.
struct ContentSink<'a> {
out: &'a mut Vec<u8>,
segments: &'a mut Option<Vec<ContentSegment>>,
}
fn append_content(
snapshot: &DocumentSnapshot,
obj: &PdfObject,
ctx: &mut ParseContext,
sink: &mut ContentSink<'_>,
current: Option<ObjectId>,
depth: usize,
limits: &ContentLimits,
) -> Result<(), ContentError> {
if depth > limits.max_content_depth {
return Ok(());
}
match obj {
PdfObject::Reference(id) => {
// A content object that fails to resolve is skipped, not fatal:
// the page renders whatever other content streams it has.
match snapshot.objects().resolve(snapshot, *id, ctx) {
Ok(resolved) => {
append_content(snapshot, &resolved, ctx, sink, Some(*id), depth + 1, limits)?
}
Err(e) => ctx.note_recovery(format!("page content object {id} unresolved: {e}")),
}
}
PdfObject::Array(items) => {
// Each item establishes its own stream identity; an array reached
// through a reference must not lend that id to a direct stream
// item, which has no object of its own.
for item in items.iter() {
append_content(snapshot, item, ctx, sink, None, depth + 1, limits)?;
}
}
PdfObject::Stream(stream) => {
// A truncated or corrupt content stream is skipped so the page
// renders what it can — blank if this was its only stream — rather
// than dropping the whole page. Viewers (Poppler/PDFium) do the
// same; a real book can carry deliberately-empty/malformed pages.
match snapshot.decode_stream_data(stream, ctx) {
Ok(bytes) => {
if !sink.out.is_empty() {
sink.out.push(b'\n');
}
let start = sink.out.len();
sink.out.extend_from_slice(&bytes);
if let Some(segs) = sink.segments.as_mut() {
segs.push(ContentSegment {
object: current,
start,
len: bytes.len(),
});
}
}
Err(e) => ctx.note_recovery(format!("content stream decode failed, skipped: {e}")),
}
}
_ => {}
}
Ok(())
}
/// Resolve a page's `/Resources` (possibly inherited, possibly indirect) into
/// a shared dictionary object.
pub(crate) fn resolve_resources(
snapshot: &DocumentSnapshot,
resources: Option<&PdfObject>,
ctx: &mut ParseContext,
) -> Option<Arc<PdfObject>> {
match resources? {
PdfObject::Reference(id) => snapshot.objects().resolve(snapshot, *id, ctx).ok(),
direct => Some(Arc::new(direct.clone())),
}
}
/// A resolved `/Separation` or `/DeviceN` space: how many tints it takes and
/// how they become a device colour.
#[derive(Debug)]
struct TintSpace {
/// Colorant count: 1 for Separation, N for DeviceN.
inputs: usize,
/// Component count of the alternate space the transform outputs into.
alt_arity: usize,
/// The tint transform (any function type, single- or multi-input). `None`
/// only when it would not build at all (malformed / unbuildable) — the
/// caller then approximates subtractively.
func: Option<crate::function::Function>,
/// The alternate space when it is CIE-based (Lab/CalRGB/CalGray): the
/// transform's outputs are components of *that* space — e.g. a PANTONE
/// `/Separation` whose alternate is Lab outputs L*a*b* on a 0..100 /
/// −128..127 scale, which clamped-as-DeviceRGB renders wildly wrong
/// (DS82's lavender band read as pure yellow). Mirrors PDFium's
/// `CPDF_SeparationCS::GetRGB` → `base_cs_->GetRGB(results)`.
alt_cie: Option<CieSpace>,
/// The alternate space when it is an `/ICCBased` **CMYK** press profile: the
/// transform's four outputs are device CMYK, but PDFium runs them through
/// the profile via LittleCMS rather than its frozen table (a PANTONE spot
/// whose alternate is the document's `/DefaultCMYK` press profile — the
/// Huser cover). Mirrors `base_cs_->GetRGB` where the base is ICCBased.
alt_icc_cmyk: Option<Arc<crate::color::icc::IccCmyk>>,
/// The `/None` colorant, which marks nothing. `/All` is *not* tracked —
/// see the construction site for why it must run the tint transform like
/// any other colorant name.
colorant_none: bool,
}
/// A CIE-based colour space's conversion parameters (ISO 32000-1 §8.6.5),
/// read once from its resource entry and cached. Conversion is pure math in
/// `exprim::color` (ported from PDFium's `cpdf_colorspace.cpp`).
#[derive(Debug, Clone, Copy)]
enum CieSpace {
Lab {
white_point: [f32; 3],
range: [f32; 4],
},
CalRgb(crate::color::CalRgbTransform),
CalGray {
gamma: f32,
},
}
/// Convert `sc`/`scn` operands through a CIE space into a device colour.
/// Operands arrive unclamped (Lab's L* ∈ [0,100], a*/b* ∈ /Range — the
/// operand path deliberately does not clamp to [0,1]); missing operands
/// default to 0.0, the spec's initial colour for these spaces.
fn eval_cie(space: CieSpace, values: &[f64]) -> SemColor {
let v = |i: usize| values.get(i).copied().unwrap_or(0.0) as f32;
match space {
CieSpace::Lab { white_point, range } => {
let [r, g, b] = crate::color::lab_to_rgb(v(0), v(1), v(2), white_point, range);
SemColor::DeviceRgb(r as f64, g as f64, b as f64)
}
CieSpace::CalRgb(transform) => {
let [r, g, b] = transform.apply([v(0), v(1), v(2)]);
SemColor::DeviceRgb(r as f64, g as f64, b as f64)
}
CieSpace::CalGray { gamma } => {
SemColor::DeviceGray(crate::color::calgray_to_gray(v(0), gamma) as f64)
}
}
}
/// One resolved Type 3 CharProc: its content stream plus the indirect
/// object it was reached through (`None` for a direct stream), retained so
/// the audit trace can name the glyph's source stream object.
#[derive(Debug, Clone)]
struct CharProc {
object: Option<ObjectId>,
stream: Arc<PdfStream>,
}
/// A parsed `/Type3` font: everything needed to draw its glyphs, which are
/// content streams rather than outlines (ISO 32000-1 §9.6.5).
#[derive(Debug)]
struct Type3Font {
/// Glyph space → text space (typically `[0.001 0 0 0.001 0 0]`).
font_matrix: Matrix,
/// Resources for CharProc execution (the font's `/Resources`, else the
/// resources active where the font is used).
resources: Option<Arc<PdfObject>>,
/// Per character-code CharProc content stream, resolved through
/// `/Encoding` + `/Differences`; `None` where the code names no glyph.
char_procs: [Option<CharProc>; 256],
/// Per character-code advance width in **glyph space** (`/Widths`); 0 where
/// absent. Transform through `font_matrix` for the text-space advance.
widths: [f64; 256],
/// Whether the font supplied a `/Widths` array at all; when it did not, the
/// CharProc's `d0`/`d1` `wx` is used as the advance instead.
has_widths: bool,
}
/// A font resolved by substitution: the program to draw with, plus which
/// bundled face the choice corresponds to (the caller needs that to know
/// whether a symbolic built-in encoding applies).
struct Substituted {
bytes: Arc<[u8]>,
program: crate::font::FontProgram,
face: crate::font::StandardFont,
/// The *requested* style — may exceed what `face` offers (the symbolic
/// faces have no bold/italic cuts); `crate::font::synthesis` derives the
/// shear/embolden to fake the difference.
want_bold: bool,
want_italic: bool,
/// Face index within a collection (.ttc); 0 for a plain font.
face_index: u32,
/// Resolved through the injected system-font provider (as opposed to a
/// bundled standard face). Only a system face can cover CJK, so only
/// then is the CID→Unicode→glyph bridge attempted — keeping the
/// provider-off default byte-for-byte deterministic.
system: bool,
}