pdf-inspector 1.21.0

Fast PDF inspection, classification, and text extraction with smart scanned vs text-based detection
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
//! Font width parsing, encoding, and text decoding.

use super::get_number;
use crate::glyph_names::glyph_to_char;
use crate::tounicode::FontCMaps;
use crate::types::{
    FontEncoding, FontEncodingMap, FontWidthInfo, PageFontEncodings, PageFontWidths,
};
use log::debug;
use lopdf::{Document, Encoding, Object, ObjectId};
use std::collections::HashMap;

#[derive(Debug, Copy, Clone, PartialEq, Eq)]
pub(crate) enum CMapChoice {
    Primary,
    Remapped,
}

#[derive(Debug, Default, Clone)]
pub(crate) struct CMapDecisionCache {
    decisions: HashMap<u32, CMapDecision>,
}

#[derive(Debug, Default, Clone)]
struct CMapDecision {
    primary_sample: String,
    remapped_sample: String,
    sample_bytes: usize,
    choice: Option<CMapChoice>,
}

impl CMapDecisionCache {
    pub(crate) fn new() -> Self {
        Self::default()
    }

    pub(crate) fn get_choice(&self, obj_num: u32) -> Option<CMapChoice> {
        self.decisions.get(&obj_num).and_then(|d| d.choice)
    }

    pub(crate) fn consider(
        &mut self,
        obj_num: u32,
        primary: &str,
        remapped: &str,
        bytes_len: usize,
    ) -> Option<CMapChoice> {
        const SAMPLE_TARGET_BYTES: usize = 240;

        let entry = self.decisions.entry(obj_num).or_default();
        entry.sample_bytes = entry.sample_bytes.saturating_add(bytes_len);
        entry.primary_sample.push_str(primary);
        entry.remapped_sample.push_str(remapped);

        if entry.choice.is_none() && entry.sample_bytes >= SAMPLE_TARGET_BYTES {
            let score_primary = score_text(&entry.primary_sample);
            let score_remap = score_text(&entry.remapped_sample);
            entry.choice = if score_remap > score_primary + 5 {
                Some(CMapChoice::Remapped)
            } else {
                Some(CMapChoice::Primary)
            };
        }

        entry.choice
    }
}

/// Resolve a PDF object reference to an array
pub(crate) fn resolve_array<'a>(doc: &'a Document, obj: &'a Object) -> Option<&'a Vec<Object>> {
    match obj {
        Object::Array(arr) => Some(arr),
        Object::Reference(r) => {
            if let Ok(Object::Array(arr)) = doc.get_object(*r) {
                Some(arr)
            } else {
                None
            }
        }
        _ => None,
    }
}

/// Resolve a PDF object reference to a dictionary
pub(crate) fn resolve_dict<'a>(
    doc: &'a Document,
    obj: &'a Object,
) -> Option<&'a lopdf::Dictionary> {
    match obj {
        Object::Dictionary(d) => Some(d),
        Object::Reference(r) => doc.get_dictionary(*r).ok(),
        _ => None,
    }
}

/// Build font width info for all fonts on a page
pub(crate) fn build_font_widths(
    doc: &Document,
    fonts: &std::collections::BTreeMap<Vec<u8>, &lopdf::Dictionary>,
) -> PageFontWidths {
    let mut widths = PageFontWidths::new();

    for (font_name, font_dict) in fonts {
        let resource_name = String::from_utf8_lossy(font_name).to_string();

        let subtype = font_dict
            .get(b"Subtype")
            .ok()
            .and_then(|o| o.as_name().ok())
            .map(|n| String::from_utf8_lossy(n).to_string())
            .unwrap_or_default();
        let base_font = font_dict
            .get(b"BaseFont")
            .ok()
            .and_then(|o| o.as_name().ok())
            .map(|n| String::from_utf8_lossy(n).to_string())
            .unwrap_or_default();
        let has_tounicode = font_dict.get(b"ToUnicode").is_ok();
        let has_descendants = font_dict.get(b"DescendantFonts").is_ok();
        let encoding_str = font_dict
            .get(b"Encoding")
            .ok()
            .map(|o| match o {
                Object::Name(n) => String::from_utf8_lossy(n).to_string(),
                Object::Reference(_) => "ref(dict)".to_string(),
                Object::Dictionary(_) => "dict".to_string(),
                _ => format!("{:?}", o),
            })
            .unwrap_or_else(|| "none".to_string());

        debug!(
            "font {:<10} sub={:<12} base={:<45} toUni={:<6} enc={:<20} cid={}",
            resource_name, subtype, base_font, has_tounicode, encoding_str, has_descendants
        );

        if let Some(info) = parse_font_widths(doc, font_dict) {
            widths.insert(resource_name, info);
        }
    }

    widths
}

/// Visual-size scale factors for Type3 fonts, keyed by resource name.
///
/// A Type3 font's glyph space maps to text space through FontMatrix, so the
/// visual height of its glyphs is `nominal_size × |matrix_y| × FontBBox
/// height`. For a well-behaved font (matrix 0.001, bbox ≈ 1000 units) that
/// factor is ≈ 1.0 and the nominal size is already right. TeX PK bitmap
/// fonts (dvips → Distiller) instead use FontMatrix [1 0 0 -1 0 0] with
/// nominal sizes like 0.12, which makes every downstream font-size heuristic
/// (drop caps, sub/superscripts, small-font tables, line heights) see
/// nonsense. Fonts without a usable FontBBox are omitted (treated as 1.0).
pub(crate) fn build_type3_scales(
    doc: &Document,
    fonts: &std::collections::BTreeMap<Vec<u8>, &lopdf::Dictionary>,
) -> HashMap<String, f32> {
    let mut scales = HashMap::new();
    for (font_name, font_dict) in fonts {
        let is_type3 = font_dict
            .get(b"Subtype")
            .ok()
            .and_then(|o| o.as_name().ok())
            .is_some_and(|n| n == b"Type3");
        if !is_type3 {
            continue;
        }
        // Array elements may themselves be indirect references per PDF
        // syntax — resolve before reading the numeric value.
        let num = |o: &Object| {
            let resolved = match o {
                Object::Reference(r) => match doc.get_object(*r) {
                    Ok(inner) => inner,
                    Err(_) => return 0.0,
                },
                other => other,
            };
            match resolved {
                Object::Integer(i) => *i as f32,
                Object::Real(r) => *r,
                _ => 0.0,
            }
        };
        let Some(matrix) = font_dict
            .get(b"FontMatrix")
            .ok()
            .and_then(|o| resolve_array(doc, o))
        else {
            continue;
        };
        let Some(bbox) = font_dict
            .get(b"FontBBox")
            .ok()
            .and_then(|o| resolve_array(doc, o))
        else {
            continue;
        };
        if matrix.len() < 4 || bbox.len() < 4 {
            continue;
        }
        let scale_y = (num(&matrix[2]).powi(2) + num(&matrix[3]).powi(2)).sqrt();
        let bbox_h = (num(&bbox[3]) - num(&bbox[1])).abs();
        let scale = bbox_h * scale_y;

        // `scale` is the glyph box measured in text-space units. For a
        // self-consistent font it lands near 1.0 — the FontMatrix is the
        // reciprocal of the glyph-space em by construction — so the Tf
        // operand is already the rendered size and must be left alone.
        // A modest deviation is normal and must NOT trigger rescaling:
        // FontBBox is the glyph bounding box, not the em box, so it is
        // routinely somewhat smaller (descender..ascender ≈ 0.7) or larger
        // (tall accents > 1.0).
        //
        // Only a wildly inconsistent font gets renormalized. dvips/PK
        // bitmap fonts declare [1 0 0 -1 0 0] with glyphs spanning
        // hundreds of units, giving scale ≈ 159 against a nominal size of
        // 0.12pt — there the declared size carries no information. The
        // band is deliberately wide so that only that class qualifies,
        // while any matrix scale (including non-standard ones like 0.005
        // with a full-em bbox, scale = 5.0) is judged on the product
        // rather than on the matrix alone.
        const CONSISTENT_LO: f32 = 0.25;
        const CONSISTENT_HI: f32 = 4.0;
        if scale.is_finite() && scale > 0.0 && !(CONSISTENT_LO..=CONSISTENT_HI).contains(&scale) {
            scales.insert(String::from_utf8_lossy(font_name).to_string(), scale);
        }
    }
    scales
}

/// Resource names of Type3 fonts whose `FontMatrix` mirrors the y axis
/// (`d < 0`). dvips/PK bitmap fonts declare `[1 0 0 -1 0 0]` and pair it with
/// a y-flipped text matrix so the glyphs render upright; the run geometry
/// must undo the flip when deciding which side of the baseline the glyph box
/// lies on (see `geometry::run_geometry`).
pub(crate) fn build_type3_y_flips(
    doc: &Document,
    fonts: &std::collections::BTreeMap<Vec<u8>, &lopdf::Dictionary>,
) -> std::collections::HashSet<String> {
    let mut flipped = std::collections::HashSet::new();
    for (font_name, font_dict) in fonts {
        let is_type3 = font_dict
            .get(b"Subtype")
            .ok()
            .and_then(|o| o.as_name().ok())
            .is_some_and(|n| n == b"Type3");
        if !is_type3 {
            continue;
        }
        let Some(matrix) = font_dict
            .get(b"FontMatrix")
            .ok()
            .and_then(|o| resolve_array(doc, o))
        else {
            continue;
        };
        let Some(d) = matrix.get(3) else {
            continue;
        };
        let d = match d {
            Object::Reference(r) => doc.get_object(*r).ok().and_then(|o| o.as_float().ok()),
            other => other.as_float().ok(),
        };
        if d.is_some_and(|d| d < 0.0) {
            flipped.insert(String::from_utf8_lossy(font_name).to_string());
        }
    }
    flipped
}

/// The name a `TextItem` carries for its font: the `/BaseFont` family name
/// ("ABCDEF+CMMI10"), which identifies the actual face, rather than the
/// arbitrary per-page resource tag ("F2").
///
/// Exception: resource names using Distiller's CID convention (`C2_0`,
/// `C0_1`) are kept as-is — `text_utils::is_cid_font` keys on that prefix
/// for micro-gap joining, and the family name carries no CID marker to
/// replace it. This is a known, deliberate wart: `TextItem::font` is the
/// face name except for this one producer convention. The clean fix is an
/// explicit CID flag on `TextItem`, which touches its ~29 construction
/// sites; do that migration when `TextItem` next changes shape, and delete
/// this carve-out with it.
pub(crate) fn item_font_name<'a>(resource_name: &'a str, base_font: &'a str) -> &'a str {
    if crate::text_utils::is_cid_font(resource_name) {
        resource_name
    } else {
        base_font
    }
}

/// Parse font widths from a font dictionary, dispatching by Subtype
pub(crate) fn parse_font_widths(
    doc: &Document,
    font_dict: &lopdf::Dictionary,
) -> Option<FontWidthInfo> {
    // Get the font subtype
    let subtype = font_dict.get(b"Subtype").ok()?;
    let subtype_name = subtype.as_name().ok()?;

    match subtype_name {
        b"Type0" => parse_type0_widths(doc, font_dict),
        b"Type1" | b"TrueType" | b"MMType1" => parse_simple_font_widths(doc, font_dict)
            .or_else(|| base14_fallback_widths(doc, font_dict)),
        b"Type3" => parse_simple_font_widths(doc, font_dict),
        _ => None,
    }
}

/// Fallback metrics for non-embedded base-14 fonts whose dictionary omits
/// `/FirstChar`/`/Widths` (legal per the PDF spec — the reader must supply
/// standard-font metrics). Without this, every glyph advances 0 and all
/// downstream gap-based logic (space synthesis, script detection, table
/// columns) collapses — common in 1990s dvips/Distiller PDFs.
///
/// Widths are resolved per code through the font's Differences encoding when
/// present, falling back to the same single-byte decode the text extractor
/// uses (cp1252-style smart punctuation for 0x80..=0x9F, Latin-1 elsewhere) —
/// so the width of a code always matches the char we extract for it.
fn base14_fallback_widths(doc: &Document, font_dict: &lopdf::Dictionary) -> Option<FontWidthInfo> {
    let base_font = font_dict
        .get(b"BaseFont")
        .ok()
        .and_then(|o| o.as_name().ok())
        .map(|n| String::from_utf8_lossy(n).to_string())?;
    if !crate::extractor::base14::is_base14_font(&base_font) {
        return None;
    }

    let enc_map = parse_font_encoding(doc, font_dict)
        .map(|r| r.map)
        .unwrap_or_default();

    let mut widths = HashMap::new();
    for code in 0u16..=255 {
        // Resolution order: Differences override, then the font's BUILT-IN
        // encoding (Symbol/ZapfDingbats glyphs live at positions unrelated
        // to cp1252 — the renderer draws α for Symbol 0x61 no matter how
        // the text decoder transliterates it, so the advance must be α's),
        // then the cp1252-style fallback used by the text decoder.
        let ch = enc_map
            .get(&(code as u8))
            .copied()
            .or_else(|| crate::extractor::base14::builtin_encoding_char(&base_font, code as u8))
            .unwrap_or_else(|| decode_single_byte_fallback_char(code as u8, true));
        if let Some(w) = crate::extractor::base14::base14_char_width(&base_font, ch) {
            widths.insert(code, w);
        }
    }
    let space_width = widths.get(&32).copied().unwrap_or(250);

    debug!(
        "  base14 fallback widths for {} ({} codes mapped)",
        base_font,
        widths.len()
    );

    Some(FontWidthInfo {
        widths,
        default_width: 500,
        space_width,
        is_cid: false,
        units_scale: 0.001,
        wmode: 0,
    })
}

/// Parse widths for simple fonts (Type1, TrueType, MMType1, Type3)
/// Reads FirstChar, LastChar, and Widths array.
/// For Type3 fonts, reads FontMatrix to determine the correct units_scale.
pub(crate) fn parse_simple_font_widths(
    doc: &Document,
    font_dict: &lopdf::Dictionary,
) -> Option<FontWidthInfo> {
    let first_char = font_dict.get(b"FirstChar").ok().and_then(|o| match o {
        Object::Integer(n) => Some(*n as u16),
        Object::Reference(r) => doc.get_object(*r).ok().and_then(|o| {
            if let Object::Integer(n) = o {
                Some(*n as u16)
            } else {
                None
            }
        }),
        _ => None,
    })?;

    let last_char = font_dict.get(b"LastChar").ok().and_then(|o| match o {
        Object::Integer(n) => Some(*n as u16),
        Object::Reference(r) => doc.get_object(*r).ok().and_then(|o| {
            if let Object::Integer(n) = o {
                Some(*n as u16)
            } else {
                None
            }
        }),
        _ => None,
    })?;

    let widths_obj = font_dict.get(b"Widths").ok()?;
    let widths_array = resolve_array(doc, widths_obj)?;

    let mut widths = HashMap::new();
    let mut space_width: u16 = 0;

    for (i, w_obj) in widths_array.iter().enumerate() {
        let code = first_char + i as u16;
        if code > last_char {
            break;
        }
        let w = match w_obj {
            Object::Integer(n) => *n as u16,
            Object::Real(n) => *n as u16,
            Object::Reference(r) => {
                if let Ok(obj) = doc.get_object(*r) {
                    match obj {
                        Object::Integer(n) => *n as u16,
                        Object::Real(n) => *n as u16,
                        _ => continue,
                    }
                } else {
                    continue;
                }
            }
            _ => continue,
        };
        if code == 32 {
            space_width = w;
        }
        widths.insert(code, w);
    }

    // Determine units_scale: for Type3 fonts, use FontMatrix[0]; for others, use 1/1000
    let units_scale = if let Ok(fm) = font_dict.get(b"FontMatrix") {
        if let Some(arr) = resolve_array(doc, fm) {
            if !arr.is_empty() {
                match &arr[0] {
                    Object::Real(r) => r.abs(),
                    Object::Integer(i) => (*i as f32).abs(),
                    _ => 0.001,
                }
            } else {
                0.001
            }
        } else {
            0.001
        }
    } else {
        0.001 // Standard 1000-unit system
    };

    // If space width wasn't found in the table, estimate from font metrics.
    // The default of 250 is calibrated for standard 1000-unit fonts (units_scale=0.001).
    // For Type3 fonts with different coordinate systems, use average glyph width instead.
    if space_width == 0 {
        if !widths.is_empty() && (units_scale - 0.001).abs() > 0.0005 {
            // Non-standard scale: estimate space as ~45% of average glyph width
            let sum: u32 = widths.values().map(|&w| w as u32).sum();
            let avg = sum as f32 / widths.len() as f32;
            space_width = (avg * 0.45).max(1.0) as u16;
        } else {
            space_width = 250;
        }
    }

    Some(FontWidthInfo {
        widths,
        default_width: 0,
        space_width,
        is_cid: false,
        units_scale,
        wmode: 0,
    })
}

/// Parse widths for Type0 (composite/CID) fonts
/// Reads DescendantFonts → CIDFont → W array and DW value
pub(crate) fn parse_type0_widths(
    doc: &Document,
    font_dict: &lopdf::Dictionary,
) -> Option<FontWidthInfo> {
    let desc_fonts_obj = font_dict.get(b"DescendantFonts").ok()?;
    let desc_fonts = resolve_array(doc, desc_fonts_obj)?;

    if desc_fonts.is_empty() {
        return None;
    }

    // Get the first descendant font dictionary
    let cid_font_dict = resolve_dict(doc, &desc_fonts[0])?;

    // Get DW (default width)
    let default_width = cid_font_dict
        .get(b"DW")
        .ok()
        .and_then(|o| match o {
            Object::Integer(n) => Some(*n as u16),
            Object::Real(n) => Some(*n as u16),
            _ => None,
        })
        .unwrap_or(1000);

    let mut widths = HashMap::new();

    // Parse W array if present
    if let Ok(w_obj) = cid_font_dict.get(b"W") {
        if let Some(w_array) = resolve_array(doc, w_obj) {
            parse_cid_w_array(doc, w_array, &mut widths);
        }
    }

    // Try to determine space width (CID 32 or CID 3 are common for space)
    let space_width = widths
        .get(&32)
        .or_else(|| widths.get(&3))
        .copied()
        .unwrap_or(if default_width > 0 {
            default_width / 4
        } else {
            250
        });

    let wmode = font_dict
        .get(b"WMode")
        .ok()
        .and_then(|o| match o {
            Object::Integer(n) => Some(*n as u8),
            _ => None,
        })
        .unwrap_or(0);

    Some(FontWidthInfo {
        widths,
        default_width,
        space_width,
        is_cid: true,
        units_scale: 0.001, // CID fonts use standard 1000-unit system
        wmode,
    })
}

/// Parse a CID W array into widths map
/// Format: [c [w1 w2 ...]] (consecutive from c) or [c_first c_last w] (range with same width)
pub(crate) fn parse_cid_w_array(
    doc: &Document,
    w_array: &[Object],
    widths: &mut HashMap<u16, u16>,
) {
    let mut i = 0;
    let mut assigned = 0usize;
    while i < w_array.len() {
        if assigned >= crate::tounicode::MAX_CID_W_EXPANSION {
            return;
        }
        let start_cid = match &w_array[i] {
            Object::Integer(n) => *n as u16,
            Object::Real(n) => *n as u16,
            _ => {
                i += 1;
                continue;
            }
        };
        i += 1;
        if i >= w_array.len() {
            break;
        }

        // Check if next element is an array (consecutive widths) or integer (range)
        match &w_array[i] {
            Object::Array(arr) => {
                // [c [w1 w2 ...]] — consecutive widths starting at c
                for (j, w_obj) in arr.iter().enumerate() {
                    if !assign_cid_width(
                        widths,
                        start_cid.wrapping_add(j as u16),
                        w_obj,
                        &mut assigned,
                    ) {
                        return;
                    }
                }
                i += 1;
            }
            Object::Reference(r) => {
                // Could be a reference to an array
                if let Ok(Object::Array(arr)) = doc.get_object(*r) {
                    for (j, w_obj) in arr.iter().enumerate() {
                        if !assign_cid_width(
                            widths,
                            start_cid.wrapping_add(j as u16),
                            w_obj,
                            &mut assigned,
                        ) {
                            return;
                        }
                    }
                    i += 1;
                } else {
                    // Treat as c_first c_last w
                    i += 1; // skip this
                }
            }
            Object::Integer(end_cid) => {
                // [c_first c_last w] — range with uniform width
                let end = *end_cid as u16;
                i += 1;
                if i >= w_array.len() {
                    break;
                }
                let w = match &w_array[i] {
                    Object::Integer(n) => *n as u16,
                    Object::Real(n) => *n as u16,
                    _ => {
                        i += 1;
                        continue;
                    }
                };
                if !assign_cid_width_range(widths, start_cid, end, w, &mut assigned) {
                    return;
                }
                i += 1;
            }
            Object::Real(end_cid) => {
                let end = *end_cid as u16;
                i += 1;
                if i >= w_array.len() {
                    break;
                }
                let w = match &w_array[i] {
                    Object::Integer(n) => *n as u16,
                    Object::Real(n) => *n as u16,
                    _ => {
                        i += 1;
                        continue;
                    }
                };
                if !assign_cid_width_range(widths, start_cid, end, w, &mut assigned) {
                    return;
                }
                i += 1;
            }
            _ => {
                i += 1;
            }
        }
    }
}

fn assign_cid_width(
    widths: &mut HashMap<u16, u16>,
    cid: u16,
    w_obj: &Object,
    assigned: &mut usize,
) -> bool {
    let w = match w_obj {
        Object::Integer(n) => *n as u16,
        Object::Real(n) => *n as u16,
        _ => return true,
    };
    if *assigned >= crate::tounicode::MAX_CID_W_EXPANSION {
        return false;
    }
    widths.insert(cid, w);
    *assigned += 1;
    true
}

fn assign_cid_width_range(
    widths: &mut HashMap<u16, u16>,
    start: u16,
    end: u16,
    w: u16,
    assigned: &mut usize,
) -> bool {
    if start > end {
        return true;
    }
    for cid in start..=end {
        if *assigned >= crate::tounicode::MAX_CID_W_EXPANSION {
            return false;
        }
        widths.insert(cid, w);
        *assigned += 1;
    }
    true
}

/// Compute the width of a string in text space units,
/// given raw bytes and font width info.
/// Returns width in text space units (font_units * units_scale * font_size).
///
/// `char_spacing` (Tc) is added per character and `word_spacing` (Tw) is added
/// per space character (byte 0x20), both in unscaled text-space units.
/// Per the PDF spec: tx = (w0 × Tfs + Tc + Tw_if_space) per glyph.
pub(crate) fn compute_string_width_ts(
    bytes: &[u8],
    font_info: &FontWidthInfo,
    font_size: f32,
    char_spacing: f32,
    word_spacing: f32,
) -> f32 {
    let mut total: f32 = 0.0;
    let mut num_spaces: usize = 0;
    let num_chars = if font_info.is_cid {
        // 2-byte (big-endian) character codes
        let mut j = 0;
        let mut count = 0usize;
        while j + 1 < bytes.len() {
            let cid = u16::from_be_bytes([bytes[j], bytes[j + 1]]);
            let w = font_info
                .widths
                .get(&cid)
                .copied()
                .unwrap_or(font_info.default_width);
            total += w as f32;
            // CID 32 = space in most CID fonts
            if cid == 32 {
                num_spaces += 1;
            }
            count += 1;
            j += 2;
        }
        count
    } else {
        // 1-byte character codes
        for &b in bytes {
            let code = b as u16;
            let w = font_info
                .widths
                .get(&code)
                .copied()
                .unwrap_or(font_info.default_width);
            total += w as f32;
            if b == 0x20 {
                num_spaces += 1;
            }
        }
        bytes.len()
    };
    // Convert from font units to text space using the font's scale factor
    // Then add Tc per character and Tw per space character
    total * font_info.units_scale * font_size
        + num_chars as f32 * char_spacing
        + num_spaces as f32 * word_spacing
}

/// Extract raw bytes from a PDF operand (String object)
pub(crate) fn get_operand_bytes(obj: &Object) -> Option<&[u8]> {
    if let Object::String(bytes, _) = obj {
        Some(bytes)
    } else {
        None
    }
}

/// Build encoding maps for all fonts on a page.
/// Returns `(encodings, has_gid_fonts)` where `has_gid_fonts` is true when
/// any font uses raw glyph ID names (gidNNNNN) that can't be decoded.
/// Gid names whose codes the font's own ToUnicode CMap maps are decodable
/// and do not set the flag (LibreOffice subsets write /gidNNNN Differences
/// names alongside a complete ToUnicode CMap).
pub(crate) fn build_font_encodings(
    doc: &Document,
    fonts: &std::collections::BTreeMap<Vec<u8>, &lopdf::Dictionary>,
    cmaps: &FontCMaps,
    font_cache: &mut FontStyleCache,
) -> (PageFontEncodings, bool) {
    let mut encodings = PageFontEncodings::new();
    let mut has_gid_fonts = false;

    for (font_name, font_dict) in fonts {
        let resource_name = String::from_utf8_lossy(font_name).to_string();

        let mut differences = FontEncodingMap::new();
        let mut identity_overrides = FontEncodingMap::new();
        if let Some(result) = parse_font_encoding(doc, font_dict) {
            if !result.gid_codes.is_empty()
                && !tounicode_maps_codes(font_dict, cmaps, &result.gid_codes)
            {
                has_gid_fonts = true;
            }
            if !result.map.is_empty() {
                identity_overrides = stale_identity_cmap_overrides(doc, font_dict, cmaps, &result);
                differences = result.map;
            }
        }
        let blank_codes = blank_glyph_codes(doc, font_dict, font_cache);
        if !differences.is_empty() || !blank_codes.is_empty() {
            encodings.insert(
                resource_name,
                FontEncoding {
                    differences,
                    identity_overrides,
                    blank_codes,
                },
            );
        }
    }

    (encodings, has_gid_fonts)
}

/// Whether `code`, decoded as `label`, is a blank glyph standing in for a
/// word space: the glyph paints nothing but advances. A tab or no-break
/// space label is spacing already and reads as a plain space too; labels
/// that are invisible formatting (soft hyphen, zero-width joiners, byte
/// order mark) keep their meaning, since a blank glyph is exactly what they
/// render as.
fn blank_glyph_reads_as_space(encoding: Option<&FontEncoding>, code: u8, label: &str) -> bool {
    encoding.is_some_and(|map| map.blank_codes.contains(&code))
        && label.chars().any(|c| !is_invisible_format(c))
}

/// Characters that render as nothing by design: soft hyphen, zero-width
/// spaces and joiners, bidi marks, embeddings and isolates, invisible math
/// operators, byte order mark. A blank glyph labelled with one of these is
/// the label's own rendering, not a stale space.
fn is_invisible_format(c: char) -> bool {
    matches!(
        c,
        '\u{00AD}'
            | '\u{200B}'..='\u{200F}'
            | '\u{202A}'..='\u{202E}'
            | '\u{2060}'..='\u{2064}'
            | '\u{2066}'..='\u{2069}'
            | '\u{FEFF}'
    )
}

/// Codes of a symbolic TrueType font whose glyph has no outline but a
/// positive advance. Painted, such a glyph leaves a gap and nothing else, so
/// the code reads as a space whatever the font's ToUnicode says. Word 2011
/// for Mac writes subsets whose ToUnicode labels the space glyph with the
/// code it landed on ("$", "!", "&"), turning every word space into
/// punctuation. Only symbolic fonts without an `/Encoding` are considered:
/// they map codes through their own `cmap`, which is the evidence used here.
/// A font with no outlined glyph at all (an invisible text layer) is left
/// alone. Results are cached per embedded font program.
fn blank_glyph_codes(
    doc: &Document,
    font_dict: &lopdf::Dictionary,
    font_cache: &mut FontStyleCache,
) -> std::collections::HashSet<u8> {
    use ttf_parser::PlatformId;

    let font_file = || -> Option<ObjectId> {
        if font_dict.get(b"Subtype").ok()?.as_name().ok()? != b"TrueType"
            || font_dict.get(b"Encoding").is_ok()
        {
            return None;
        }
        let descriptor = resolve_dict(doc, font_dict.get(b"FontDescriptor").ok()?)?;
        // Flags bit 3: symbolic. Non-symbolic fonts route codes through a
        // standard encoding, not their own cmap.
        if descriptor.get(b"Flags").ok()?.as_i64().ok()? & 4 == 0 {
            return None;
        }
        descriptor.get(b"FontFile2").ok()?.as_reference().ok()
    };
    let Some(ff_ref) = font_file() else {
        return Default::default();
    };
    if let Some(cached) = font_cache.blank_codes_by_font_file.get(&ff_ref) {
        return cached.clone();
    }
    let compute = || -> Option<std::collections::HashSet<u8>> {
        let data = font_file_data(doc, ff_ref)?;
        let face = ttf_parser::Face::parse(&data, 0).ok()?;
        let cmap = face.tables().cmap?;
        // Symbolic fonts address their glyphs through a (1,0) table by
        // code, or a (3,0) table by code in one of the private ranges
        // F000-F2FF, with the bare code as the last resort (PDF 32000-1,
        // 9.6.6.4).
        let glyph_for = |code: u8| -> Option<ttf_parser::GlyphId> {
            let code = u32::from(code);
            for subtable in cmap.subtables {
                let candidates: &[u32] = match (subtable.platform_id, subtable.encoding_id) {
                    (PlatformId::Macintosh, 0) => &[code],
                    (PlatformId::Windows, 0) => {
                        &[0xF000 + code, 0xF100 + code, 0xF200 + code, code]
                    }
                    _ => continue,
                };
                for &candidate in candidates {
                    if let Some(gid) = subtable.glyph_index(candidate) {
                        if gid.0 != 0 {
                            return Some(gid);
                        }
                    }
                }
            }
            None
        };
        let mut blank = std::collections::HashSet::new();
        let mut outlined = 0usize;
        let mut mapped = 0usize;
        // Control codes never carry a word space; Word's subsets start at
        // 0x21 and other producers keep 0x00-0x1F for genuinely blank
        // control glyphs.
        for code in 0x20u8..=255 {
            let Some(gid) = glyph_for(code) else {
                continue;
            };
            mapped += 1;
            if face.glyph_bounding_box(gid).is_some() {
                outlined += 1;
                continue;
            }
            // The glyph program's own advance keeps the result a property
            // of the font file, which is what the cache is keyed by.
            if face.glyph_hor_advance(gid).is_some_and(|w| w > 0) {
                blank.insert(code);
            }
        }
        // Word for Mac also writes a subset per run, so a space painted on
        // its own arrives as a font holding nothing but `.notdef` and that
        // blank glyph, with one code mapped. With no outline anywhere, at
        // most two mapped codes still read as such a space subset; more is
        // an invisible text layer, which keeps its text.
        if blank.is_empty() || (outlined == 0 && mapped > 2) {
            return None;
        }
        debug!(
            "blank glyph codes for {}: {:?}",
            font_dict
                .get(b"BaseFont")
                .ok()
                .and_then(|o| o.as_name().ok())
                .map(|n| String::from_utf8_lossy(n).into_owned())
                .unwrap_or_default(),
            {
                let mut codes: Vec<u8> = blank.iter().copied().collect();
                codes.sort_unstable();
                codes
            }
        );
        Some(blank)
    };
    let blank = compute().unwrap_or_default();
    font_cache
        .blank_codes_by_font_file
        .insert(ff_ref, blank.clone());
    blank
}

/// Some subset producers change the simple font's glyph encoding but retain
/// its original ToUnicode. Repair only corroborated ASCII identity entries:
/// at least three distinct letters move to ASCII slots, their Unicode values remain
/// elsewhere in the old CMap, and the embedded CFF contains those exact glyphs.
/// Other repairs need the same evidence, allowing a single-character case
/// counterpart in the old CMap once the exact matches establish staleness.
/// Keep repairs per font, since different encodings can share one CMap stream.
fn stale_identity_cmap_overrides(
    doc: &Document,
    font_dict: &lopdf::Dictionary,
    cmaps: &FontCMaps,
    encoding: &EncodingResult,
) -> FontEncodingMap {
    let verified = || -> Option<FontEncodingMap> {
        if font_dict.get(b"Subtype").ok()?.as_name().ok()? != b"Type1" {
            return None;
        }
        let cmap_ref = font_dict.get(b"ToUnicode").ok()?.as_reference().ok()?;
        let entry = cmaps.get_by_obj(cmap_ref.0)?;
        if entry.primary.code_byte_length != 1 || entry.remapped.is_some() {
            return None;
        }
        let elsewhere: std::collections::HashSet<String> = (0..=255)
            .filter_map(|code| entry.primary.lookup(code))
            .collect();
        let single_case_match =
            |case: String| case.chars().count() == 1 && elsewhere.contains(&case);
        let candidates: FontEncodingMap = encoding
            .map
            .iter()
            .filter_map(|(&code, &ch)| {
                (code.is_ascii_graphic()
                    && !ch.is_ascii()
                    && (ch.is_alphabetic() || ch == '\u{00a0}')
                    && entry.primary.lookup(code as u16).as_deref()
                        == Some(&(code as char).to_string())
                    && (elsewhere.contains(&ch.to_string())
                        || (ch.is_alphabetic()
                            && (single_case_match(ch.to_lowercase().to_string())
                                || single_case_match(ch.to_uppercase().to_string())))))
                .then_some((code, ch))
            })
            .collect();
        let exact_anchor_count = |map: &FontEncodingMap| {
            map.values()
                .copied()
                .filter(|ch| ch.is_alphabetic() && elsewhere.contains(&ch.to_string()))
                .collect::<std::collections::HashSet<char>>()
                .len()
        };
        if exact_anchor_count(&candidates) < 3 {
            return None;
        }
        let descriptor = resolve_dict(doc, font_dict.get(b"FontDescriptor").ok()?)?;
        let font_ref = descriptor.get(b"FontFile3").ok()?.as_reference().ok()?;
        let stream = doc.get_object(font_ref).ok()?.as_stream().ok()?;
        if stream.dict.get(b"Subtype").ok()?.as_name().ok()? != b"Type1C" {
            return None;
        }
        let data = font_file_data(doc, font_ref)?;
        let cff = ttf_parser::cff::Table::parse(&data)?;
        let overrides: FontEncodingMap = candidates
            .into_iter()
            .filter(|(code, _)| {
                encoding
                    .glyph_names
                    .get(code)
                    .is_some_and(|name| cff.glyph_index_by_name(name).is_some())
            })
            .collect();
        (exact_anchor_count(&overrides) >= 3).then_some(overrides)
    };
    verified().unwrap_or_default()
}

/// True when the font's ToUnicode CMap maps the gid-named character codes,
/// so the Differences entries still decode through the CMap.
fn tounicode_maps_codes(font_dict: &lopdf::Dictionary, cmaps: &FontCMaps, codes: &[u8]) -> bool {
    let Some(obj_ref) = font_dict
        .get(b"ToUnicode")
        .ok()
        .and_then(|o| o.as_reference().ok())
    else {
        return false;
    };
    let Some(entry) = cmaps.get_by_obj(obj_ref.0) else {
        return false;
    };
    // At least one gid code usably mapped means the CMap addresses these
    // codes; remaining unmapped codes are subset leftovers (e.g. the
    // component glyphs of an emoji ZWJ sequence mapped whole on its first
    // code). A mapping is usable only when extraction would accept it —
    // empty or U+FFFD results are rejected there as invalid. Fonts whose
    // CMap ignores the gid codes entirely stay flagged, and the downstream
    // garbage/encoding checks still catch partial damage.
    codes.iter().any(|&code| {
        entry
            .primary
            .lookup(code as u16)
            .is_some_and(|s| !s.is_empty() && !s.contains('\u{FFFD}'))
    })
}

/// Parse font encoding from a font dictionary
pub(crate) fn parse_font_encoding(
    doc: &Document,
    font_dict: &lopdf::Dictionary,
) -> Option<EncodingResult> {
    let encoding_obj = font_dict.get(b"Encoding").ok()?;
    let base_font_name = font_dict
        .get(b"BaseFont")
        .ok()
        .and_then(|o| o.as_name().ok())
        .map(|n| String::from_utf8_lossy(n).to_string());

    // Encoding can be a name or a dictionary
    match encoding_obj {
        Object::Name(_name) => {
            // Standard encoding name (e.g., MacRomanEncoding, WinAnsiEncoding)
            // For standard encodings, we can use the standard tables
            // But we still need to check for Differences
            None // Let lopdf handle standard encodings
        }
        Object::Reference(obj_ref) => {
            // Reference to encoding dictionary
            if let Ok(enc_dict) = doc.get_dictionary(*obj_ref) {
                parse_encoding_dictionary(doc, enc_dict, base_font_name.as_deref())
            } else {
                None
            }
        }
        Object::Dictionary(enc_dict) => {
            parse_encoding_dictionary(doc, enc_dict, base_font_name.as_deref())
        }
        _ => None,
    }
}

/// Result of parsing an encoding dictionary's Differences array.
pub(crate) struct EncodingResult {
    pub map: FontEncodingMap,
    glyph_names: HashMap<u8, String>,
    /// Character codes whose glyph names match the `gidNNNNN` pattern (raw
    /// glyph IDs). These reference the original font's glyph table and are
    /// only decodable when the font's ToUnicode CMap maps the code.
    pub gid_codes: Vec<u8>,
}

/// Parse an encoding dictionary with Differences array
pub(crate) fn parse_encoding_dictionary(
    doc: &Document,
    enc_dict: &lopdf::Dictionary,
    base_font_name: Option<&str>,
) -> Option<EncodingResult> {
    let differences = enc_dict.get(b"Differences").ok()?;

    let diff_array = match differences {
        Object::Array(arr) => arr.clone(),
        Object::Reference(obj_ref) => {
            if let Ok(Object::Array(arr)) = doc.get_object(*obj_ref) {
                arr.clone()
            } else {
                return None;
            }
        }
        _ => return None,
    };

    let mut encoding_map = FontEncodingMap::new();
    let mut glyph_names = HashMap::new();
    let mut current_code: u8 = 0;
    let mut ligature_count = 0u32;
    let mut gid_codes: Vec<u8> = Vec::new();

    for item in diff_array {
        match item {
            Object::Integer(n) => {
                // This sets the starting code for subsequent glyph names
                current_code = n as u8;
            }
            Object::Name(name) => {
                // Map current code to glyph name -> Unicode
                let glyph_name = String::from_utf8_lossy(&name).to_string();
                let mapped_char = glyph_to_char(&glyph_name)
                    .or_else(|| private_glyph_to_char(&glyph_name, base_font_name));
                if mapped_char.is_some_and(is_ligature_char) {
                    debug!(
                        "  Differences: code=0x{:02X} glyph={:?} (ligature)",
                        current_code, glyph_name
                    );
                    ligature_count += 1;
                }
                // Detect raw glyph ID names (e.g. "gid00053") that can't be
                // mapped to Unicode without the original font's cmap table.
                if glyph_name.starts_with("gid")
                    && glyph_name.len() >= 4
                    && glyph_name[3..].chars().all(|c| c.is_ascii_digit())
                {
                    gid_codes.push(current_code);
                }
                if let Some(ch) = mapped_char {
                    encoding_map.insert(current_code, ch);
                    glyph_names.insert(current_code, glyph_name);
                } else {
                    debug!(
                        "  Differences: code=0x{:02X} glyph={:?} (unmapped)",
                        current_code, glyph_name
                    );
                }
                current_code = current_code.wrapping_add(1);
            }
            _ => {}
        }
    }

    if ligature_count > 0 {
        debug!(
            "  Differences: {} total entries, {} ligatures",
            encoding_map.len(),
            ligature_count
        );
    }

    if !gid_codes.is_empty() {
        debug!(
            "  Differences: {} gid-encoded glyphs (decodable only via ToUnicode)",
            gid_codes.len()
        );
    }

    Some(EncodingResult {
        map: encoding_map,
        glyph_names,
        gid_codes,
    })
}

fn private_glyph_to_char(glyph_name: &str, base_font_name: Option<&str>) -> Option<char> {
    let base_font_name = strip_subset_prefix(base_font_name?);

    // Aptos CFF subsets from Office PDFs can expose the ff ligature as /g431
    // without a ToUnicode map. Keep this font-scoped because /gNNN names are private.
    if base_font_name.eq_ignore_ascii_case("Aptos") && glyph_name == "g431" {
        Some('\u{FB00}')
    } else {
        None
    }
}

fn strip_subset_prefix(font_name: &str) -> &str {
    font_name
        .split_once('+')
        .map_or(font_name, |(_, stripped)| stripped)
}

fn is_ligature_char(ch: char) -> bool {
    matches!(
        ch,
        '\u{FB00}' | '\u{FB01}' | '\u{FB02}' | '\u{FB03}' | '\u{FB04}'
    )
}

/// Get the CMap lookup key for an Identity-H/V CID font without ToUnicode.
/// Returns the object number used by `collect_cmaps_from_fonts` to store the CMap:
/// - FontFile2 or FontFile3 obj_num (for embedded font cmap)
/// - CIDFont dict obj_num (for predefined CIDSystemInfo-based mapping)
pub(crate) fn get_font_file2_obj_num(doc: &Document, font_dict: &lopdf::Dictionary) -> Option<u32> {
    let subtype = font_dict
        .get(b"Subtype")
        .ok()
        .and_then(|o| o.as_name().ok());

    // Type0 (CID) fonts
    if subtype == Some(b"Type0") {
        let encoding = font_dict.get(b"Encoding").ok()?.as_name().ok()?;
        if encoding != b"Identity-H" && encoding != b"Identity-V" {
            return None;
        }
        let desc_fonts_obj = font_dict.get(b"DescendantFonts").ok()?;
        let desc_fonts = resolve_array(doc, desc_fonts_obj)?;
        if desc_fonts.is_empty() {
            return None;
        }
        let cid_font_dict = resolve_dict(doc, &desc_fonts[0])?;
        let font_descriptor_obj = cid_font_dict.get(b"FontDescriptor").ok()?;
        let font_descriptor = resolve_dict(doc, font_descriptor_obj)?;

        // Try FontFile2 (TrueType), then FontFile3 (OpenType/CFF)
        if let Some(ff_ref) = font_descriptor
            .get(b"FontFile2")
            .ok()
            .and_then(|o| o.as_reference().ok())
            .or_else(|| {
                font_descriptor
                    .get(b"FontFile3")
                    .ok()
                    .and_then(|o| o.as_reference().ok())
            })
        {
            return Some(ff_ref.0);
        }

        // Fallback: use DescendantFonts[0] obj_num (for predefined CIDSystemInfo mapping)
        if let Object::Reference(r) = &desc_fonts[0] {
            return Some(r.0);
        }
        return None;
    }

    // Simple fonts: use embedded font file if available
    let font_descriptor_obj = font_dict.get(b"FontDescriptor").ok()?;
    let font_descriptor = resolve_dict(doc, font_descriptor_obj)?;
    font_descriptor
        .get(b"FontFile2")
        .ok()
        .and_then(|o| o.as_reference().ok())
        .or_else(|| {
            font_descriptor
                .get(b"FontFile3")
                .ok()
                .and_then(|o| o.as_reference().ok())
        })
        .map(|r| r.0)
}

/// Document-scoped memo of facts read from embedded font programs, keyed
/// by the FontFile2/FontFile3 stream's object id: style flags, and the
/// blank-glyph codes of `blank_glyph_codes`. The same font program is
/// referenced from every page that uses the font, and decompressing +
/// parsing it dominates `font_style` — without the memo that
/// cost repeats per page whenever the descriptor leaves a flag unset
/// (the common case: regular fonts report neither italic nor bold).
#[derive(Debug, Default)]
pub(crate) struct FontStyleCache {
    by_font_file: HashMap<ObjectId, FontStyle>,
    /// Blank-glyph codes per embedded font program (see `blank_glyph_codes`),
    /// so a font shared across pages is scanned once.
    blank_codes_by_font_file: HashMap<ObjectId, std::collections::HashSet<u8>>,
}

impl FontStyleCache {
    pub(crate) fn new() -> Self {
        Self::default()
    }
}

/// Style of a font resource: italic and bold, and the weight class.
///
/// The flags survive subset fonts whose BaseFont names are opaque tags
/// ("Tc1", "ABCDEF+F1") that defeat the name-based bold/italic heuristics.
/// Italic: `ItalicAngle` beyond a few degrees, or Flags bit 7 (Italic,
/// value 64). Bold: Flags bit 19 (ForceBold, value 1<<18). The small
/// ItalicAngle threshold skips fonts that declare a token slant.
///
/// `weight` is the 100..=900 weight class, read in this order: the embedded
/// font program's OS/2 `usWeightClass` (the weight word of the PostScript
/// name for a bare CFF program, which has no OS/2 table), the descriptor's
/// `/FontWeight`, then the weight word of the `/BaseFont` name (see
/// `text_utils::font_weight_from_name`). `None` when none of them says, and
/// for anything but an ordinary text font (Type0, Type1, MMType1,
/// TrueType): a Type3 font is a set of glyph procedures whose name and
/// descriptor say nothing about the ink they draw.
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
pub(crate) struct FontStyle {
    pub(crate) italic: bool,
    pub(crate) bold: bool,
    pub(crate) weight: Option<u16>,
}

impl FontStyle {
    /// `(italic, bold)`.
    pub(crate) fn flags(self) -> (bool, bool) {
        (self.italic, self.bold)
    }
}

/// The [`FontStyle`] of a font resource, from its descriptor, its embedded
/// program and its name.
pub(crate) fn font_style(
    doc: &Document,
    font_dict: &lopdf::Dictionary,
    style_cache: &mut FontStyleCache,
) -> FontStyle {
    let has_weight_class = is_ordinary_text_font(font_dict);
    let name_weight = font_dict
        .get(b"BaseFont")
        .ok()
        .filter(|_| has_weight_class)
        .and_then(|obj| obj.as_name().ok())
        .and_then(|name| crate::text_utils::font_weight_from_name(&String::from_utf8_lossy(name)));
    let descriptor = font_dict
        .get(b"FontDescriptor")
        .ok()
        .and_then(|obj| resolve_dict(doc, obj))
        .or_else(|| {
            // Type0 fonts hang the descriptor off DescendantFonts[0].
            let desc_fonts = font_dict.get(b"DescendantFonts").ok()?;
            let desc_fonts = resolve_array(doc, desc_fonts)?;
            let cid_font_dict = resolve_dict(doc, desc_fonts.first()?)?;
            resolve_dict(doc, cid_font_dict.get(b"FontDescriptor").ok()?)
        });
    let Some(descriptor) = descriptor else {
        return FontStyle {
            weight: name_weight,
            ..FontStyle::default()
        };
    };

    let italic_angle = descriptor
        .get(b"ItalicAngle")
        .ok()
        .and_then(get_number)
        .unwrap_or(0.0);
    let flags = descriptor
        .get(b"Flags")
        .ok()
        .and_then(|obj| obj.as_i64().ok())
        .unwrap_or(0);

    let mut style = FontStyle {
        italic: italic_angle.abs() >= 4.0 || flags & (1 << 6) != 0,
        bold: flags & (1 << 18) != 0,
        weight: None,
    };

    // Descriptors lie: subset generators write ItalicAngle 0 for genuinely
    // italic faces. The embedded font file keeps the truth — OS/2
    // fsSelection (via `Face::is_italic`) and the post table's italicAngle —
    // and it alone carries the weight class.
    if let Some(ff_ref) = font_file_ref(descriptor) {
        let embedded = *style_cache
            .by_font_file
            .entry(ff_ref)
            .or_insert_with(|| embedded_style(doc, ff_ref));
        style.italic |= embedded.italic;
        style.bold |= embedded.bold;
        style.weight = embedded.weight;
    }
    style.weight = if has_weight_class {
        style
            .weight
            .or_else(|| {
                descriptor
                    .get(b"FontWeight")
                    .ok()
                    .and_then(|obj| resolve_number(doc, obj))
                    .and_then(weight_class)
            })
            .or(name_weight)
    } else {
        None
    };
    style
}

/// Whether a font dictionary is an ordinary text font — Type0, Type1,
/// MMType1 or TrueType — as opposed to a Type3 font or an unknown subtype.
fn is_ordinary_text_font(font_dict: &lopdf::Dictionary) -> bool {
    font_dict
        .get(b"Subtype")
        .ok()
        .and_then(|obj| obj.as_name().ok())
        .is_some_and(|subtype| matches!(subtype, b"Type0" | b"Type1" | b"MMType1" | b"TrueType"))
}

/// A number from an integer or real object, following an indirect reference.
fn resolve_number(doc: &Document, obj: &Object) -> Option<f32> {
    match obj {
        Object::Reference(id) => doc.get_object(*id).ok().and_then(get_number),
        direct => get_number(direct),
    }
}

/// A weight class value from `usWeightClass` or `/FontWeight`, clamped into
/// the 100..=900 scale; `None` for zero, negative or non-numeric values,
/// which both fields use for "unset".
fn weight_class(value: f32) -> Option<u16> {
    if !value.is_finite() || value < 1.0 {
        return None;
    }
    Some(value.round().clamp(100.0, 900.0) as u16)
}

/// Style parsed from an embedded font program stream.
fn embedded_style(doc: &Document, ff_ref: ObjectId) -> FontStyle {
    let Some(data) = font_file_data(doc, ff_ref) else {
        return FontStyle::default();
    };
    if let Ok(face) = ttf_parser::Face::parse(&data, 0) {
        // PDF subsetters can remove OS/2 while retaining the bold bit in
        // head.macStyle. Face::is_bold only reads OS/2; use the legacy flag
        // when that table is unavailable, without overriding an explicit
        // regular OS/2 face. The parsed face has already validated head.
        let os2 = face.tables().os2;
        let mac_bold = os2.is_none()
            && face
                .raw_face()
                .table(ttf_parser::Tag::from_bytes(b"head"))
                .and_then(|head| head.get(44..46))
                .is_some_and(|bytes| u16::from_be_bytes([bytes[0], bytes[1]]) & 1 != 0);
        FontStyle {
            italic: face.is_italic() || face.italic_angle().abs() >= 4.0,
            bold: face.is_bold() || mac_bold,
            weight: os2.and_then(|os2| weight_class(f32::from(os2.weight().to_number()))),
        }
    } else if let Some(name) = cff_font_name(&data) {
        // FontFile3 is bare CFF (no sfnt container) — ttf_parser
        // can't open it, but the CFF Name INDEX keeps the real
        // PostScript name ("XXXXXX+Amplitude-LightItalic") even
        // when the descriptor was rewritten to claim upright.
        FontStyle {
            italic: crate::text_utils::is_italic_font(&name),
            bold: crate::text_utils::is_bold_font(&name),
            weight: crate::text_utils::font_weight_from_name(&name),
        }
    } else {
        FontStyle::default()
    }
}

/// First PostScript name from a bare CFF font's Name INDEX (CFF spec §7).
fn cff_font_name(data: &[u8]) -> Option<String> {
    // Header: major(1) minor(1) hdrSize(1) offSize(1); major must be 1.
    if data.len() < 4 || data[0] != 1 {
        return None;
    }
    let hdr_size = data[2] as usize;
    // Name INDEX: count(u16) offSize(u8) offsets[count+1] data
    let count = u16::from_be_bytes([*data.get(hdr_size)?, *data.get(hdr_size + 1)?]) as usize;
    if count == 0 {
        return None;
    }
    let off_size = *data.get(hdr_size + 2)? as usize;
    if !(1..=4).contains(&off_size) {
        return None;
    }
    let read_offset = |idx: usize| -> Option<usize> {
        let at = hdr_size + 3 + idx * off_size;
        let bytes = data.get(at..at + off_size)?;
        let mut v = 0usize;
        for b in bytes {
            v = (v << 8) | *b as usize;
        }
        Some(v)
    };
    let start = read_offset(0)?;
    let end = read_offset(1)?;
    if start == 0 || end < start {
        return None;
    }
    // Offsets are 1-based from the byte before the object data.
    let objects_base = hdr_size + 3 + (count + 1) * off_size - 1;
    let name = data.get(objects_base + start..objects_base + end)?;
    Some(String::from_utf8_lossy(name).to_string())
}

/// FontFile2/FontFile3 stream reference from a FontDescriptor.
fn font_file_ref(descriptor: &lopdf::Dictionary) -> Option<ObjectId> {
    descriptor
        .get(b"FontFile2")
        .ok()
        .and_then(|o| o.as_reference().ok())
        .or_else(|| {
            descriptor
                .get(b"FontFile3")
                .ok()
                .and_then(|o| o.as_reference().ok())
        })
}

/// Decompressed embedded font program bytes.
fn font_file_data(doc: &Document, ff_ref: ObjectId) -> Option<Vec<u8>> {
    let stream = doc
        .get_object(ff_ref)
        .and_then(lopdf::Object::as_stream)
        .ok()?;
    Some(
        stream
            .decompressed_content()
            .unwrap_or_else(|_| stream.content.clone()),
    )
}

/// Decode a PDF string and record whether legacy symbol cleanup changed a character.
#[allow(clippy::too_many_arguments)]
pub(crate) fn extract_text_from_operand(
    obj: &Object,
    current_font: &str,
    base_font_name: Option<&str>,
    font_cmaps: &FontCMaps,
    font_tounicode_refs: &std::collections::HashMap<String, u32>,
    inline_cmaps: &std::collections::HashMap<String, crate::tounicode::CMapEntry>,
    font_encodings: &PageFontEncodings,
    encoding_cache: &HashMap<String, Encoding<'_>>,
    cmap_decisions: &mut CMapDecisionCache,
    font_widths: &PageFontWidths,
) -> Option<(String, bool)> {
    let is_type0_cid_font = font_widths
        .get(current_font)
        .is_some_and(|info| info.is_cid);
    let use_cp1252_fallback =
        should_use_cp1252_single_byte_fallback(base_font_name, is_type0_cid_font);
    let result = (|| -> Option<String> {
        if let Object::String(bytes, _) = obj {
            let mut decode_with_entry = |entry: &crate::tounicode::CMapEntry| -> Option<String> {
                // For single-byte CMaps, merge CMap + Differences at the byte level:
                // try CMap first, then Differences, then Latin-1 fallback per byte.
                // This prevents partial CMap results from blocking the Differences path.
                if entry.primary.code_byte_length == 1 {
                    let encoding_map = font_encodings.get(current_font);
                    let decode_byte = |b: u8| -> Option<String> {
                        let code = b as u16;
                        // 1. Primary CMap
                        if let Some(s) = entry.primary.lookup(code) {
                            if !s.contains('\u{FFFD}') {
                                if s == (b as char).to_string() {
                                    if let Some(&ch) =
                                        encoding_map.and_then(|map| map.identity_overrides.get(&b))
                                    {
                                        return Some(ch.to_string());
                                    }
                                }
                                return Some(s);
                            }
                        }
                        // 2. Fallback CMap (embedded font cmap)
                        if let Some(fb) = entry.fallback.as_ref().and_then(|c| c.lookup(code)) {
                            if !fb.contains('\u{FFFD}') {
                                return Some(fb);
                            }
                        }
                        // 3. Differences mapped it? Use Differences result
                        if let Some(map) = encoding_map {
                            if let Some(&ch) = map.differences.get(&b) {
                                return Some(ch.to_string());
                            }
                        }
                        // 4. Printable single-byte fallback
                        if b >= 0x20 {
                            return Some(
                                decode_single_byte_fallback_char(b, use_cp1252_fallback)
                                    .to_string(),
                            );
                        }
                        None
                    };
                    let decoded: String = bytes
                        .iter()
                        .filter_map(|&b| {
                            let label = decode_byte(b)?;
                            // A glyph with no outline paints a gap, whatever
                            // its label says.
                            if blank_glyph_reads_as_space(encoding_map, b, &label) {
                                return Some(" ".to_string());
                            }
                            Some(label)
                        })
                        .collect();
                    if !decoded.is_empty() {
                        return Some(decoded);
                    }
                    return None;
                }

                // 2-byte CMap: use standard decode_cids path
                if bytes.len() % 2 == 1 {
                    // Some PDFs emit 1-byte codes even for Type0 fonts; try per-byte lookup
                    let lookups = entry.primary.lookup_bytes(bytes);
                    let decoded: String = lookups
                        .iter()
                        .filter_map(|&(_b, ref cmap_result)| cmap_result.clone())
                        .collect();
                    if !decoded.is_empty() {
                        return Some(decoded);
                    }
                }
                let decoded_primary = entry.primary.decode_cids(bytes);
                if let Some(remapped) = entry.remapped.as_ref() {
                    let decoded_remap = remapped.decode_cids(bytes);
                    let decoded_fallback = entry.fallback.as_ref().map(|c| c.decode_cids(bytes));

                    if let Some(choice) = cmap_decisions
                        .get_choice(font_tounicode_refs.get(current_font).copied().unwrap_or(0))
                    {
                        let decoded = match choice {
                            CMapChoice::Primary => decoded_primary.clone(),
                            CMapChoice::Remapped => decoded_remap.clone(),
                        };
                        if !decoded.is_empty() {
                            return Some(decoded);
                        }
                    }

                    let choice = cmap_decisions.consider(
                        font_tounicode_refs.get(current_font).copied().unwrap_or(0),
                        &decoded_primary,
                        &decoded_remap,
                        bytes.len(),
                    );
                    let mut decoded = match choice {
                        Some(CMapChoice::Primary) => decoded_primary,
                        Some(CMapChoice::Remapped) => decoded_remap,
                        None => choose_best_cmap_decode(decoded_primary, decoded_remap),
                    };
                    if let Some(fb) = decoded_fallback {
                        let expected = bytes.len() / 2;
                        let decoded_len = decoded.chars().count();
                        let prefer_fallback = (!fb.is_empty() && decoded.is_empty())
                            || (!fb.is_empty() && expected > 0 && decoded_len * 2 < expected);
                        if prefer_fallback || score_text(&fb) > score_text(&decoded) + 3 {
                            decoded = fb;
                        }
                    }
                    if !decoded.is_empty() {
                        return Some(decoded);
                    }
                } else if !decoded_primary.is_empty() {
                    if let Some(fb) = entry.fallback.as_ref().map(|c| c.decode_cids(bytes)) {
                        let expected = bytes.len() / 2;
                        let decoded_len = decoded_primary.chars().count();
                        let prefer_fallback = (!fb.is_empty() && decoded_primary.is_empty())
                            || (!fb.is_empty() && expected > 0 && decoded_len * 2 < expected);
                        if prefer_fallback || score_text(&fb) > score_text(&decoded_primary) + 3 {
                            return Some(fb);
                        }
                    }
                    return Some(decoded_primary);
                }

                None
            };

            let mut has_cmap = false;
            if let Some(entry) = inline_cmaps.get(current_font) {
                has_cmap = true;
                if let Some(decoded) = decode_with_entry(entry) {
                    return Some(decoded);
                }
            }

            // Look up CMap by ToUnicode object reference
            if let Some(&obj_num) = font_tounicode_refs.get(current_font) {
                if let Some(entry) = font_cmaps.get_by_obj(obj_num) {
                    has_cmap = true;
                    if let Some(decoded) = decode_with_entry(entry) {
                        return Some(decoded);
                    }
                }
            }

            // CID fonts with a CMap that couldn't decode: the CID is genuinely
            // unmapped. Don't fall through to text-interpretation fallbacks
            // (Latin-1, UTF-16, etc.) which would misinterpret CID bytes as
            // character codes (e.g. CID 0x01A9 → Latin-1 "©").
            if is_type0_cid_font && bytes.iter().any(|&b| b > 0x7F) {
                // 2-byte CIDs (Identity-H) are by far the common case; for
                // an odd byte count we still emit at least one marker so
                // detection downstream fires.
                let cid_count = (bytes.len() / 2).max(1);
                return Some("\u{FFFD}".repeat(cid_count));
            }

            // Try our custom encoding map from Differences arrays.
            // The Differences array overrides specific codes in a base encoding (typically
            // WinAnsiEncoding). We must combine Differences entries with the base encoding
            // rather than using filter_map which silently drops unmapped bytes.
            if let Some(encoding) = font_encodings.get(current_font) {
                let encoding_map = &encoding.differences;
                let has_diff_match = bytes
                    .iter()
                    .any(|b| encoding_map.contains_key(b) || encoding.blank_codes.contains(b));
                if has_diff_match {
                    let decoded: String = bytes
                        .iter()
                        .filter_map(|&b| {
                            let label = if let Some(&ch) = encoding_map.get(&b) {
                                Some(ch)
                            } else if b >= 0x20 {
                                // Base encoding fallback for printable bytes.
                                // Most PDFs with simple fonts use WinAnsi/PDFDocEncoding
                                // semantics, not ISO-8859-1 C1 controls.
                                Some(decode_single_byte_fallback_char(b, use_cp1252_fallback))
                            } else {
                                None // Skip unmapped control characters
                            }?;
                            // A glyph with no outline paints a gap, whatever
                            // its label says.
                            if blank_glyph_reads_as_space(Some(encoding), b, &label.to_string()) {
                                return Some(' ');
                            }
                            Some(label)
                        })
                        .collect();
                    if !decoded.is_empty() {
                        return Some(decoded);
                    }
                }
            }

            // Fallback: try UTF-16BE then Latin-1
            if bytes.len() >= 2 && bytes[0] == 0xFE && bytes[1] == 0xFF {
                let utf16: Vec<u16> = bytes[2..]
                    .as_chunks::<2>()
                    .0
                    .iter()
                    .map(|chunk| u16::from_be_bytes(*chunk))
                    .collect();
                let text = String::from_utf16_lossy(&utf16);
                if text.contains('\u{FFFD}') {
                    debug!(
                        "utf16 loss produced replacement for font={} bytes_len={}",
                        current_font,
                        bytes.len()
                    );
                }
                return Some(text);
            }

            // Heuristic UTF-16BE decode when bytes look like UTF-16 (even length, null-heavy)
            if bytes.len() >= 4 && bytes.len() % 2 == 0 {
                let nulls = bytes.iter().filter(|&&b| b == 0).count();
                if nulls * 4 > bytes.len() {
                    let utf16: Vec<u16> = bytes
                        .as_chunks::<2>()
                        .0
                        .iter()
                        .map(|chunk| u16::from_be_bytes(*chunk))
                        .collect();
                    let text = String::from_utf16_lossy(&utf16);
                    if score_text(&text) > 0 {
                        return Some(text);
                    }
                }
            }

            // Check for UTF-8 encoded strings before single-byte encoding decoding.
            // Some PDFs incorrectly embed UTF-8 bytes in single-byte encoded fonts
            // (e.g. "José" as UTF-8 [C3 A9] instead of WinAnsi [E9]).
            if bytes.iter().any(|&b| b > 0x7F) {
                if let Ok(text) = std::str::from_utf8(bytes) {
                    return Some(text.to_string());
                }
            }

            // Try to decode using cached font encoding from lopdf
            if let Some(encoding) = encoding_cache.get(current_font) {
                if let Ok(text) = Document::decode_text(encoding, bytes) {
                    let text = normalize_cp1252_controls(text, use_cp1252_fallback);
                    if text.contains('\u{FFFD}') {
                        debug!(
                            "decode_text produced replacement for font={} bytes_len={}",
                            current_font,
                            bytes.len()
                        );
                        if bytes.len() <= 8 {
                            let hex: String = bytes.iter().map(|b| format!("{:02X}", b)).collect();
                            debug!(
                                "decode_text replacement bytes font={} base={:?} hex={}",
                                current_font, base_font_name, hex
                            );
                        }
                        if bytes.iter().all(|&b| (0x20..=0x7E).contains(&b)) {
                            return Some(bytes.iter().map(|&b| b as char).collect());
                        }
                        if let Some(symbol_text) = decode_symbol_fallback(bytes, base_font_name) {
                            return Some(symbol_text);
                        }
                        // For CID fonts (have ToUnicode CMap), the CID is
                        // genuinely unmapped — return None to avoid Latin-1
                        // fallback misinterpreting CID bytes as characters.
                        if has_cmap || font_tounicode_refs.contains_key(current_font) {
                            return None;
                        }
                        // Non-CID fonts: fall through to other methods
                    } else {
                        return Some(text);
                    }
                }
            }

            if let Some(symbol_text) = decode_symbol_fallback(bytes, base_font_name) {
                return Some(symbol_text);
            }

            // Non-CID (Type1 / TrueType / Type3) fonts use single-byte
            // encodings. In practice the fallback should follow WinAnsi for
            // 0x80..=0x9F so bytes like 0x92 become smart punctuation instead
            // of C1 controls that look like CID mojibake.
            Some(decode_single_byte_fallback(bytes, use_cp1252_fallback))
        } else {
            None
        }
    })();
    result.map(|text| {
        let (text, legacy_symbol_rewrite) = clean_symbol_pua(text);
        let text = remap_texcm_math_symbols(text, base_font_name);
        (
            normalize_cp1252_controls(text, use_cp1252_fallback),
            legacy_symbol_rewrite,
        )
    })
}

/// Fix a known producer bug in "TeXCMMathsSymbols" subset fonts (IntechOpen
/// and sibling academic pipelines): the Computer Modern symbol glyphs are
/// misnamed after Latin lookalikes (equal → /onequarter, plus → /thorn, …)
/// and the generated ToUnicode faithfully propagates the wrong names. The
/// remap applies only to text decoded from that font, keyed on the glyphs'
/// observed misnames.
fn remap_texcm_math_symbols(text: String, base_font_name: Option<&str>) -> String {
    let is_texcm = base_font_name.is_some_and(|n| {
        let n = n.rsplit_once('+').map_or(n, |(_, s)| s);
        n.eq_ignore_ascii_case("TeXCMMathsSymbols")
    });
    if !is_texcm {
        return text;
    }
    text.chars()
        .map(|c| match c {
            '¼' => '=',
            '½' => '-',
            'þ' => '+',
            'ð' => '(',
            'Þ' => ')',
            _ => c,
        })
        .collect()
}

fn decode_single_byte_fallback(bytes: &[u8], use_cp1252_fallback: bool) -> String {
    bytes
        .iter()
        .map(|&b| decode_single_byte_fallback_char(b, use_cp1252_fallback))
        .collect()
}

fn decode_single_byte_fallback_char(byte: u8, use_cp1252_fallback: bool) -> char {
    if !use_cp1252_fallback {
        return byte as char;
    }

    match byte {
        0x80 => '\u{20AC}',
        0x82 => '\u{201A}',
        0x83 => '\u{0192}',
        0x84 => '\u{201E}',
        0x85 => '\u{2026}',
        0x86 => '\u{2020}',
        0x87 => '\u{2021}',
        0x88 => '\u{02C6}',
        0x89 => '\u{2030}',
        0x8A => '\u{0160}',
        0x8B => '\u{2039}',
        0x8C => '\u{0152}',
        0x8E => '\u{017D}',
        0x91 => '\u{2018}',
        0x92 => '\u{2019}',
        0x93 => '\u{201C}',
        0x94 => '\u{201D}',
        0x95 => '\u{2022}',
        0x96 => '\u{2013}',
        0x97 => '\u{2014}',
        0x98 => '\u{02DC}',
        0x99 => '\u{2122}',
        0x9A => '\u{0161}',
        0x9B => '\u{203A}',
        0x9C => '\u{0153}',
        0x9E => '\u{017E}',
        0x9F => '\u{0178}',
        _ => byte as char,
    }
}

fn normalize_cp1252_controls(text: String, use_cp1252_fallback: bool) -> String {
    if !use_cp1252_fallback {
        return text;
    }
    if !text
        .chars()
        .any(|ch| ('\u{0080}'..='\u{009F}').contains(&ch))
    {
        return text;
    }

    text.chars()
        .map(|ch| {
            if ('\u{0080}'..='\u{009F}').contains(&ch) {
                decode_single_byte_fallback_char(ch as u8, true)
            } else {
                ch
            }
        })
        .collect()
}

fn should_use_cp1252_single_byte_fallback(
    base_font_name: Option<&str>,
    is_type0_cid_font: bool,
) -> bool {
    if is_type0_cid_font {
        return false;
    }

    let Some(base_font_name) = base_font_name else {
        return true;
    };
    let font_name = base_font_name
        .rsplit_once('+')
        .map_or(base_font_name, |(_, stripped)| stripped)
        .to_ascii_lowercase();

    // TeX/Computer Modern and math/symbol fonts often place ligatures or
    // symbols in the C1 byte range. Treating those bytes as Windows-1252 makes
    // words like "deficiente" become "de…ciente" and "fluid" become "‡uid".
    let non_cp1252_prefixes = [
        "cmr", "cmb", "cmmi", "cmsy", "cmex", "cmtt", "cmss", "cmti", "ecrm", "ecbx", "ecti",
        "tcrm", "tctt", "msam", "msbm", "ttdc",
    ];
    if non_cp1252_prefixes
        .iter()
        .any(|prefix| font_name.starts_with(prefix))
    {
        return false;
    }

    let non_cp1252_names = ["math", "symbol", "dingbat", "emoji"];
    !non_cp1252_names.iter().any(|name| font_name.contains(name))
}

/// Apply the existing private-use cleanup without changing its output.
/// The boolean records an actual heuristic rewrite, not a proven Unicode alias.
fn clean_symbol_pua(text: String) -> (String, bool) {
    if !text.chars().any(|c| ('\u{F000}'..='\u{F0FF}').contains(&c)) {
        return (text, false);
    }
    let mut rewritten = false;
    let text = text
        .chars()
        .map(|c| {
            let code = c as u32;
            if !(0xF000..=0xF0FF).contains(&code) {
                return c;
            }
            let low = code - 0xF000;
            let replacement = match low {
                // Common bullets
                0xA1 | 0xA7 | 0xB7 => '\u{2022}',
                // Checkmark
                0xFC => '\u{2713}',
                // Printable ASCII range and Latin-1 above: strip F000 offset
                0x20..=0xFF => char::from_u32(low).unwrap_or(c),
                _ => c,
            };
            rewritten |= replacement != c;
            replacement
        })
        .collect();
    (text, rewritten)
}

fn decode_symbol_fallback(bytes: &[u8], base_font_name: Option<&str>) -> Option<String> {
    let name = base_font_name?.to_ascii_lowercase();
    if !name.contains("symbol") && !name.contains("wingdings") && !name.contains("zapfdingbats") {
        return None;
    }
    let mut out = String::new();
    for &b in bytes {
        if b < 0x20 {
            continue;
        }
        if let Some(ch) = char::from_u32(0xF000 + b as u32) {
            out.push(ch);
        }
    }
    if out.is_empty() {
        None
    } else {
        Some(out)
    }
}

fn choose_best_cmap_decode(primary: String, remapped: String) -> String {
    if primary.is_empty() {
        return remapped;
    }
    if remapped.is_empty() {
        return primary;
    }
    let score_primary = score_text(&primary);
    let score_remap = score_text(&remapped);
    if score_remap > score_primary + 3 {
        remapped
    } else {
        primary
    }
}

fn score_text(text: &str) -> i32 {
    const COMMON_WORDS: [&str; 22] = [
        "the", "and", "of", "to", "in", "a", "is", "that", "for", "with", "on", "as", "by", "from",
        "this", "be", "are", "at", "or", "not", "it", "our",
    ];

    let mut letters = 0i32;
    let mut spaces = 0i32;
    let mut digits = 0i32;
    let mut other = 0i32;
    let mut word_hits = 0i32;

    let mut current = String::new();
    for ch in text.chars() {
        if ch.is_ascii_alphabetic() {
            letters += 1;
            current.push(ch.to_ascii_lowercase());
        } else {
            if !current.is_empty() {
                if COMMON_WORDS.iter().any(|w| *w == current) {
                    word_hits += 1;
                }
                current.clear();
            }
            if ch == ' ' {
                spaces += 1;
            } else if ch.is_ascii_digit() {
                digits += 1;
            } else if ch.is_control() || ch == '\u{FFFD}' {
                other += 3;
            } else if ('\u{4E00}'..='\u{9FFF}').contains(&ch)
                || ('\u{3040}'..='\u{309F}').contains(&ch)
                || ('\u{30A0}'..='\u{30FF}').contains(&ch)
                || ('\u{3400}'..='\u{4DBF}').contains(&ch)
                || ('\u{F900}'..='\u{FAFF}').contains(&ch)
            {
                letters += 1; // CJK ideographs / kana count as valid text
            } else {
                other += 1;
            }
        }
    }
    if !current.is_empty() && COMMON_WORDS.iter().any(|w| *w == current) {
        word_hits += 1;
    }

    let mut score = word_hits * 10 + letters + spaces * 2 + digits - other * 2;
    if letters > 15 && word_hits == 0 {
        score -= 15;
    }
    score
}

#[cfg(test)]
mod tests {

    #[test]
    fn item_font_name_prefers_family_over_resource_tag() {
        use super::item_font_name;
        assert_eq!(item_font_name("F2", "ABCDEF+CMMI10"), "ABCDEF+CMMI10");
        assert_eq!(item_font_name("T22", "Times-Roman"), "Times-Roman");
        // Distiller CID-convention resources keep the resource name:
        // is_cid_font keys on the C2_/C0_ prefix for micro-gap joining.
        assert_eq!(item_font_name("C2_0", "ABCDEE+SimSun"), "C2_0");
        assert_eq!(item_font_name("C0_1", "ABCDEE+MSMincho"), "C0_1");
    }

    #[test]
    fn type3_scale_resolves_indirect_matrix_and_bbox_numbers() {
        use lopdf::{dictionary, Document, Object};
        // FontMatrix/FontBBox elements may be indirect references per PDF
        // syntax; the scale must use their resolved values, not zero.
        let mut doc = Document::with_version("1.4");
        let matrix_d = doc.add_object(Object::Real(-1.0));
        let bbox_top = doc.add_object(Object::Integer(3));
        let font_dict = dictionary! {
            "Type" => "Font",
            "Subtype" => "Type3",
            "FontMatrix" => vec![
                Object::Integer(1),
                Object::Integer(0),
                Object::Integer(0),
                Object::Reference(matrix_d),
                Object::Integer(0),
                Object::Integer(0),
            ],
            "FontBBox" => vec![
                Object::Integer(1),
                Object::Integer(-156),
                Object::Integer(37),
                Object::Reference(bbox_top),
            ],
        };
        let mut fonts = std::collections::BTreeMap::new();
        fonts.insert(b"T2".to_vec(), &font_dict);
        let scales = super::build_type3_scales(&doc, &fonts);
        let scale = scales.get("T2").copied().unwrap_or(1.0);
        // bbox height 159 x |matrix_y| 1.0
        assert!(
            (scale - 159.0).abs() < 0.5,
            "scale should use resolved indirect values, got {scale}"
        );
    }

    /// Build a one-font Type3 document and return its computed scale, if any.
    #[cfg(test)]
    fn type3_scale_for(matrix_y: f32, bbox_lo: i64, bbox_hi: i64) -> Option<f32> {
        use lopdf::{dictionary, Document, Object};
        let doc = Document::with_version("1.4");
        let font_dict = dictionary! {
            "Type" => "Font",
            "Subtype" => "Type3",
            "FontMatrix" => vec![
                Object::Real(matrix_y), Object::Integer(0), Object::Integer(0),
                Object::Real(matrix_y), Object::Integer(0), Object::Integer(0),
            ],
            "FontBBox" => vec![
                Object::Integer(0), Object::Integer(bbox_lo),
                Object::Integer(600), Object::Integer(bbox_hi),
            ],
        };
        let mut fonts = std::collections::BTreeMap::new();
        fonts.insert(b"T9".to_vec(), &font_dict);
        super::build_type3_scales(&doc, &fonts).get("T9").copied()
    }

    #[test]
    fn type3_scale_skips_self_consistent_fonts() {
        // Conventional 1/1000 matrix with a descender..ascender bbox of 700
        // units: scale 0.7. The Tf operand is already the rendered size, so
        // renormalizing would report every size at 0.7x.
        assert_eq!(type3_scale_for(0.001, -200, 500), None);
        // Tall-accent bbox slightly over the em (1100 units, scale 1.1).
        assert_eq!(type3_scale_for(0.001, -100, 1000), None);
    }

    #[test]
    fn type3_scale_applies_to_inconsistent_fonts_at_any_matrix_scale() {
        // Non-standard but valid matrix (0.005) with a full-em bbox:
        // scale 5.0, so the declared size is off by 5x and must be fixed.
        let s = type3_scale_for(0.005, 0, 1000).expect("0.005 matrix should rescale");
        assert!((s - 5.0).abs() < 0.01, "got {s}");
        // dvips/PK bitmap pattern: unit matrix, glyphs spanning ~159 units.
        let s = type3_scale_for(1.0, -156, 3).expect("PK pattern should rescale");
        assert!((s - 159.0).abs() < 0.5, "got {s}");
    }

    #[test]
    fn type3_scale_ignores_degenerate_bbox() {
        // [0 0 0 0] is legal and carries no size information.
        assert_eq!(type3_scale_for(0.001, 0, 0), None);
    }

    #[test]
    fn texcm_math_symbols_remap() {
        assert_eq!(
            super::remap_texcm_math_symbols("S ¼ kB þ 1".into(), Some("EEKVNO+TeXCMMathsSymbols")),
            "S = kB + 1"
        );
        // Other fonts keep their genuine fractions/thorns.
        assert_eq!(
            super::remap_texcm_math_symbols("¼ cup þorn".into(), Some("Times-Roman")),
            "¼ cup þorn"
        );
        assert_eq!(super::remap_texcm_math_symbols("¼".into(), None), "¼");
    }

    use super::*;
    use lopdf::dictionary;

    fn make_font_info(widths: &[(u16, u16)], default_width: u16, is_cid: bool) -> FontWidthInfo {
        FontWidthInfo {
            widths: widths.iter().copied().collect(),
            default_width,
            space_width: widths
                .iter()
                .find(|(k, _)| *k == 32)
                .map(|(_, v)| *v)
                .unwrap_or(default_width),
            is_cid,
            units_scale: 0.001,
            wmode: 0,
        }
    }

    fn doc_with_descriptor(descriptor: lopdf::Dictionary) -> (Document, lopdf::Dictionary) {
        let mut doc = Document::with_version("1.4");
        let desc_id = doc.add_object(descriptor);
        let font_dict = dictionary! {
            "Type" => "Font",
            "Subtype" => "TrueType",
            "BaseFont" => "Tc1",
            "FontDescriptor" => desc_id,
        };
        (doc, font_dict)
    }

    #[test]
    fn descriptor_italic_angle_sets_italic() {
        // Subset font with an opaque BaseFont name ("Tc1") — the name
        // heuristic sees nothing, the descriptor carries the truth.
        let (doc, font_dict) = doc_with_descriptor(dictionary! {
            "Type" => "FontDescriptor",
            "FontName" => "Tc1",
            "ItalicAngle" => -12,
            "Flags" => 32,
        });
        assert_eq!(
            font_style(&doc, &font_dict, &mut FontStyleCache::new()).flags(),
            (true, false)
        );
    }

    #[test]
    fn descriptor_italic_flag_bit_sets_italic() {
        let (doc, font_dict) = doc_with_descriptor(dictionary! {
            "Type" => "FontDescriptor",
            "FontName" => "Tc1",
            "ItalicAngle" => 0,
            "Flags" => 64, // bit 7: Italic
        });
        assert_eq!(
            font_style(&doc, &font_dict, &mut FontStyleCache::new()).flags(),
            (true, false)
        );
    }

    #[test]
    fn descriptor_force_bold_flag_sets_bold() {
        let (doc, font_dict) = doc_with_descriptor(dictionary! {
            "Type" => "FontDescriptor",
            "FontName" => "Tc1",
            "ItalicAngle" => 0,
            "Flags" => 1 << 18, // ForceBold
        });
        assert_eq!(
            font_style(&doc, &font_dict, &mut FontStyleCache::new()).flags(),
            (false, true)
        );
    }

    #[test]
    fn tiny_italic_angle_is_not_italic() {
        // A token 1-degree slant is optical correction, not italic.
        let (doc, font_dict) = doc_with_descriptor(dictionary! {
            "Type" => "FontDescriptor",
            "FontName" => "Tc1",
            "ItalicAngle" => lopdf::Object::Real(-1.0),
            "Flags" => 32,
        });
        assert_eq!(
            font_style(&doc, &font_dict, &mut FontStyleCache::new()).flags(),
            (false, false)
        );
    }

    #[test]
    fn missing_descriptor_yields_no_flags() {
        let doc = Document::with_version("1.4");
        let font_dict = dictionary! { "Type" => "Font", "BaseFont" => "Tc1" };
        assert_eq!(
            font_style(&doc, &font_dict, &mut FontStyleCache::new()).flags(),
            (false, false)
        );
    }

    /// Synthetic sfnt containing just the tables needed to parse a face.
    /// No source-document font bytes are needed for these style tests.
    fn sfnt_with_style(mac_style: u16, os2_selection: Option<u16>) -> Vec<u8> {
        sfnt_with_style_and_weight(mac_style, os2_selection.map(|selection| (selection, 0)))
    }

    /// [`sfnt_with_style`] whose OS/2 table also carries a `usWeightClass`.
    fn sfnt_with_style_and_weight(mac_style: u16, os2: Option<(u16, u16)>) -> Vec<u8> {
        let mut head = vec![0u8; 54];
        head[18..20].copy_from_slice(&1000u16.to_be_bytes()); // unitsPerEm
        head[44..46].copy_from_slice(&mac_style.to_be_bytes());
        let hhea = vec![0u8; 36];
        let mut maxp = vec![0u8; 6];
        maxp[..4].copy_from_slice(&0x00005000u32.to_be_bytes());
        maxp[4..6].copy_from_slice(&1u16.to_be_bytes()); // numGlyphs
        let mut tables = vec![(*b"head", head), (*b"hhea", hhea), (*b"maxp", maxp)];
        if let Some((selection, weight_class)) = os2 {
            let mut os2 = vec![0u8; 78]; // version 0
            os2[4..6].copy_from_slice(&weight_class.to_be_bytes()); // usWeightClass
            os2[62..64].copy_from_slice(&selection.to_be_bytes()); // fsSelection
            tables.push((*b"OS/2", os2));
        }
        tables.sort_by_key(|(tag, _)| *tag);
        let count = tables.len();
        let mut data = vec![0u8; 12 + count * 16];
        data[..4].copy_from_slice(&0x00010000u32.to_be_bytes());
        data[4..6].copy_from_slice(&(count as u16).to_be_bytes());
        for (i, (tag, table)) in tables.into_iter().enumerate() {
            let offset = data.len() as u32;
            let record = 12 + i * 16;
            data[record..record + 4].copy_from_slice(&tag);
            data[record + 8..record + 12].copy_from_slice(&offset.to_be_bytes());
            data[record + 12..record + 16].copy_from_slice(&(table.len() as u32).to_be_bytes());
            data.extend_from_slice(&table);
            while !data.len().is_multiple_of(4) {
                data.push(0);
            }
        }
        data
    }

    fn descriptor_flags_from_sfnt(mac_style: u16, os2_selection: Option<u16>) -> (bool, bool) {
        let mut doc = Document::with_version("1.4");
        let font_file = doc.add_object(lopdf::Stream::new(
            dictionary! {},
            sfnt_with_style(mac_style, os2_selection),
        ));
        let descriptor = doc.add_object(dictionary! {
            "Type" => "FontDescriptor",
            "FontName" => "ABCDEF+OpaqueFace",
            "Flags" => 4,
            "ItalicAngle" => 0,
            "FontFile2" => font_file,
        });
        let font_dict = dictionary! {
            "Type" => "Font",
            "Subtype" => "TrueType",
            "BaseFont" => "ABCDEF+OpaqueFace",
            "FontDescriptor" => descriptor,
        };
        font_style(&doc, &font_dict, &mut FontStyleCache::new()).flags()
    }

    #[test]
    fn embedded_mac_bold_without_os2_survives_opaque_subset_names() {
        assert_eq!(descriptor_flags_from_sfnt(1, None), (false, true));
        assert_eq!(descriptor_flags_from_sfnt(0, None), (false, false));
        // Italic and other macStyle bits must not imply bold.
        assert_eq!(descriptor_flags_from_sfnt(2, None), (false, false));
    }

    #[test]
    fn embedded_os2_bold_remains_authoritative() {
        assert_eq!(descriptor_flags_from_sfnt(0, Some(1 << 5)), (false, true));
        assert_eq!(descriptor_flags_from_sfnt(1, Some(1 << 6)), (false, false));
    }

    /// A TrueType font dictionary embedding `font_file`, with the given
    /// BaseFont and descriptor entries on top of the plain flags.
    fn embedded_font(
        base_font: &str,
        font_file: Vec<u8>,
        descriptor_extra: lopdf::Dictionary,
    ) -> (Document, lopdf::Dictionary) {
        let mut doc = Document::with_version("1.4");
        let font_file = doc.add_object(lopdf::Stream::new(dictionary! {}, font_file));
        let mut descriptor = dictionary! {
            "Type" => "FontDescriptor",
            "FontName" => base_font,
            "Flags" => 4,
            "ItalicAngle" => 0,
            "FontFile2" => font_file,
        };
        for (key, value) in descriptor_extra.into_iter() {
            descriptor.set(key.clone(), value.clone());
        }
        let descriptor = doc.add_object(descriptor);
        let font_dict = dictionary! {
            "Type" => "Font",
            "Subtype" => "TrueType",
            "BaseFont" => base_font,
            "FontDescriptor" => descriptor,
        };
        (doc, font_dict)
    }

    #[test]
    fn weight_class_comes_from_the_embedded_os2_table_first() {
        // usWeightClass 700 on a face whose fsSelection bold bit is unset,
        // whose descriptor claims /FontWeight 400 and whose name says
        // nothing: the embedded table wins, and it does not make the font
        // bold on its own.
        let (doc, font_dict) = embedded_font(
            "ABCDEF+OpaqueFace",
            sfnt_with_style_and_weight(0, Some((0, 700))),
            dictionary! { "FontWeight" => 400 },
        );
        assert_eq!(
            font_style(&doc, &font_dict, &mut FontStyleCache::new()),
            FontStyle {
                italic: false,
                bold: false,
                weight: Some(700),
            }
        );
    }

    #[test]
    fn weight_class_falls_back_to_the_descriptor_then_the_name() {
        // No OS/2 table: the descriptor's /FontWeight decides ...
        let (doc, font_dict) = embedded_font(
            "ABCDEF+Face-Bold",
            sfnt_with_style_and_weight(0, None),
            dictionary! { "FontWeight" => 300 },
        );
        assert_eq!(
            font_style(&doc, &font_dict, &mut FontStyleCache::new()).weight,
            Some(300)
        );
        // ... and without one the weight word of the BaseFont name does.
        let (doc, font_dict) = embedded_font(
            "ABCDEF+Face-Bold",
            sfnt_with_style_and_weight(0, None),
            dictionary! {},
        );
        assert_eq!(
            font_style(&doc, &font_dict, &mut FontStyleCache::new()).weight,
            Some(700)
        );
        // An OS/2 table that leaves usWeightClass at 0 says nothing.
        let (doc, font_dict) = embedded_font(
            "ABCDEF+Face-Md",
            sfnt_with_style_and_weight(0, Some((0, 0))),
            dictionary! {},
        );
        assert_eq!(
            font_style(&doc, &font_dict, &mut FontStyleCache::new()).weight,
            Some(500)
        );
    }

    #[test]
    fn descriptor_font_weight_is_clamped_to_the_scale() {
        for (value, expected) in [
            (lopdf::Object::Integer(700), Some(700)),
            (lopdf::Object::Real(500.0), Some(500)),
            (lopdf::Object::Integer(1000), Some(900)),
            (lopdf::Object::Integer(0), None),
            (lopdf::Object::Integer(-1), None),
            (lopdf::Object::Name(b"Bold".to_vec()), None),
        ] {
            let (doc, font_dict) = doc_with_descriptor(dictionary! {
                "Type" => "FontDescriptor",
                "FontName" => "Tc1",
                "Flags" => 32,
                "FontWeight" => value.clone(),
            });
            assert_eq!(
                font_style(&doc, &font_dict, &mut FontStyleCache::new()).weight,
                expected,
                "{value:?}"
            );
        }
    }

    #[test]
    fn indirect_font_weight_is_resolved() {
        let mut doc = Document::with_version("1.4");
        let weight_id = doc.add_object(lopdf::Object::Integer(600));
        let desc_id = doc.add_object(dictionary! {
            "Type" => "FontDescriptor",
            "FontName" => "Tc1",
            "Flags" => 32,
            "ItalicAngle" => 0,
            "FontWeight" => weight_id,
        });
        let font_dict = dictionary! {
            "Type" => "Font",
            "Subtype" => "TrueType",
            "BaseFont" => "Tc1",
            "FontDescriptor" => desc_id,
        };
        assert_eq!(
            font_style(&doc, &font_dict, &mut FontStyleCache::new()).weight,
            Some(600)
        );
    }

    #[test]
    fn type3_fonts_carry_no_weight_class() {
        // A Type3 font's glyph procedures draw whatever they like: neither a
        // weight word in its name nor a /FontWeight in its descriptor says
        // how heavy that ink is, while its style flags stay as they were.
        let mut doc = Document::with_version("1.4");
        let desc_id = doc.add_object(dictionary! {
            "Type" => "FontDescriptor",
            "FontName" => "Glyphs-Bold",
            "Flags" => 4 | (1 << 18),
            "ItalicAngle" => 0,
            "FontWeight" => 700,
        });
        let font_dict = dictionary! {
            "Type" => "Font",
            "Subtype" => "Type3",
            "BaseFont" => "Glyphs-Bold",
            "FontDescriptor" => desc_id,
        };
        assert_eq!(
            font_style(&doc, &font_dict, &mut FontStyleCache::new()),
            FontStyle {
                italic: false,
                bold: true,
                weight: None,
            }
        );
        // The same holds for a font dictionary without a subtype at all.
        let font_dict = dictionary! { "Type" => "Font", "BaseFont" => "Anything-Bold" };
        assert_eq!(
            font_style(&doc, &font_dict, &mut FontStyleCache::new()).weight,
            None
        );
    }

    #[test]
    fn name_weight_needs_no_descriptor() {
        let doc = Document::with_version("1.4");
        let font_dict = dictionary! {
            "Type" => "Font",
            "Subtype" => "Type1",
            "BaseFont" => "Helvetica-Light",
        };
        assert_eq!(
            font_style(&doc, &font_dict, &mut FontStyleCache::new()),
            FontStyle {
                italic: false,
                bold: false,
                weight: Some(300),
            }
        );
    }

    #[test]
    fn type0_descendant_descriptor_is_resolved() {
        let mut doc = Document::with_version("1.4");
        let desc_id = doc.add_object(dictionary! {
            "Type" => "FontDescriptor",
            "FontName" => "ABCDEF+F1",
            "ItalicAngle" => -15,
        });
        let cid_id = doc.add_object(dictionary! {
            "Type" => "Font",
            "Subtype" => "CIDFontType2",
            "FontDescriptor" => desc_id,
        });
        let font_dict = dictionary! {
            "Type" => "Font",
            "Subtype" => "Type0",
            "BaseFont" => "ABCDEF+F1",
            "DescendantFonts" => vec![lopdf::Object::Reference(cid_id)],
        };
        assert_eq!(
            font_style(&doc, &font_dict, &mut FontStyleCache::new()).flags(),
            (true, false)
        );
    }

    /// Bare CFF: header + Name INDEX only — enough for `cff_font_name`.
    fn bare_cff_with_name(name: &str) -> Vec<u8> {
        let mut data = vec![1, 0, 4, 1]; // major, minor, hdrSize, offSize
        data.extend_from_slice(&1u16.to_be_bytes()); // Name INDEX count
        data.push(1); // offSize
        data.push(1); // offset of first name
        data.push(1 + name.len() as u8); // offset past last name
        data.extend_from_slice(name.as_bytes());
        data
    }

    #[test]
    fn bare_cff_name_weight_outranks_the_descriptor() {
        // A Type1C program's own PostScript name carries the style
        // abbreviation; the descriptor's /FontWeight and the opaque
        // BaseFont say nothing useful.
        let mut doc = Document::with_version("1.4");
        let ff_id = doc.add_object(lopdf::Object::Stream(lopdf::Stream::new(
            dictionary! {},
            bare_cff_with_name("ABCDEF+Face-Md"),
        )));
        let desc_id = doc.add_object(dictionary! {
            "Type" => "FontDescriptor",
            "FontName" => "ABCDEF+Face-Md",
            "ItalicAngle" => 0,
            "Flags" => 32,
            "FontWeight" => 400,
            "FontFile3" => ff_id,
        });
        let font_dict = dictionary! {
            "Type" => "Font",
            "Subtype" => "Type1",
            "BaseFont" => "Tc1",
            "FontDescriptor" => desc_id,
        };
        assert_eq!(
            font_style(&doc, &font_dict, &mut FontStyleCache::new()),
            FontStyle {
                italic: false,
                bold: false,
                weight: Some(500),
            }
        );
    }

    #[test]
    fn embedded_font_style_is_cached_by_font_file_object() {
        use lopdf::{Object, Stream};

        let mut doc = Document::with_version("1.4");
        let ff_id = doc.add_object(Object::Stream(Stream::new(
            dictionary! {},
            bare_cff_with_name("ABCDEF+Test-BoldItalic"),
        )));
        let desc_id = doc.add_object(dictionary! {
            "Type" => "FontDescriptor",
            "FontName" => "ABCDEF+Test-BoldItalic",
            "ItalicAngle" => 0,
            "Flags" => 32,
            "FontFile3" => ff_id,
        });
        let font_dict = dictionary! {
            "Type" => "Font",
            "Subtype" => "Type1",
            "BaseFont" => "Tc1",
            "FontDescriptor" => desc_id,
        };

        let mut cache = FontStyleCache::new();
        assert_eq!(
            font_style(&doc, &font_dict, &mut cache).flags(),
            (true, true)
        );
        assert_eq!(cache.by_font_file.len(), 1);

        // Replace the font program with garbage: a repeat call must serve
        // the memo instead of re-reading the stream — repeated per-page
        // decompression is exactly what the cache exists to avoid.
        doc.objects.insert(
            ff_id,
            Object::Stream(Stream::new(dictionary! {}, vec![0u8; 4])),
        );
        assert_eq!(
            font_style(&doc, &font_dict, &mut cache).flags(),
            (true, true)
        );
        // A cold cache parses the (now garbage) stream, proving the warm
        // call above answered from the memo.
        assert_eq!(
            font_style(&doc, &font_dict, &mut FontStyleCache::new()).flags(),
            (false, false)
        );
    }

    #[test]
    fn compute_string_width_ts_no_tc_tw() {
        // Without Tc/Tw (both 0), width = glyph widths only
        let fi = make_font_info(&[(72, 500), (101, 400), (108, 300)], 600, false);
        let bytes = b"Hello"; // H=500, e=400, l=300, l=300, o=600(default)
        let w = compute_string_width_ts(bytes, &fi, 10.0, 0.0, 0.0);
        // (500+400+300+300+600) * 0.001 * 10 = 21.0
        assert!((w - 21.0).abs() < 0.01);
    }

    #[test]
    fn compute_string_width_ts_with_positive_tc() {
        // Positive Tc adds char_spacing per character
        let fi = make_font_info(&[], 500, false);
        let bytes = b"ab"; // 2 chars, each 500 default
        let w = compute_string_width_ts(bytes, &fi, 10.0, 0.5, 0.0);
        // glyph: (500+500)*0.001*10 = 10.0, Tc: 2*0.5 = 1.0, total = 11.0
        assert!((w - 11.0).abs() < 0.01);
    }

    #[test]
    fn compute_string_width_ts_with_negative_tc() {
        // Negative Tc (tight tracking) reduces width
        let fi = make_font_info(&[], 500, false);
        let bytes = b"ab";
        let w = compute_string_width_ts(bytes, &fi, 10.0, -0.3, 0.0);
        // glyph: 10.0, Tc: 2*(-0.3) = -0.6, total = 9.4
        assert!((w - 9.4).abs() < 0.01);
    }

    #[test]
    fn compute_string_width_ts_with_tw() {
        // Tw applies only to space characters (byte 0x20)
        let fi = make_font_info(&[(32, 250)], 500, false);
        let bytes = b"a b"; // 'a'=500, ' '=250, 'b'=500
        let w = compute_string_width_ts(bytes, &fi, 10.0, 0.0, 0.8);
        // glyph: (500+250+500)*0.001*10 = 12.5, Tw: 1*0.8 = 0.8, total = 13.3
        assert!((w - 13.3).abs() < 0.01);
    }

    #[test]
    fn compute_string_width_ts_with_tc_and_tw() {
        // Both Tc and Tw
        let fi = make_font_info(&[(32, 250)], 500, false);
        let bytes = b"a b"; // 3 chars, 1 space
        let w = compute_string_width_ts(bytes, &fi, 10.0, 0.1, 0.5);
        // glyph: 12.5, Tc: 3*0.1 = 0.3, Tw: 1*0.5 = 0.5, total = 13.3
        assert!((w - 13.3).abs() < 0.01);
    }

    #[test]
    fn compute_string_width_ts_cid_font() {
        // CID font: 2-byte codes, space is CID 32
        let fi = make_font_info(&[(65, 500), (32, 250)], 600, true);
        // "A " in CID: [0,65, 0,32]
        let bytes = &[0u8, 65, 0, 32];
        let w = compute_string_width_ts(bytes, &fi, 12.0, 0.2, 0.3);
        // glyph: (500+250)*0.001*12 = 9.0, Tc: 2*0.2 = 0.4, Tw: 1*0.3 = 0.3
        assert!((w - 9.7).abs() < 0.01);
    }

    #[test]
    fn compute_string_width_ts_large_tc() {
        // Large Tc (character-spreading) is applied in full
        let fi = make_font_info(&[], 500, false);
        let bytes = b"abc"; // 3 chars
        let w = compute_string_width_ts(bytes, &fi, 10.0, 5.0, 0.0);
        // glyph: (500*3)*0.001*10 = 15.0, Tc: 3*5.0 = 15.0, total = 30.0
        assert!((w - 30.0).abs() < 0.01);
    }

    #[test]
    fn score_text_cjk() {
        // Correct Japanese text should score well
        let japanese = "2026年9月期 1Q 業績報告";
        // Garbled output (random CJK from wrong remap)
        let garbled = "\u{FFFD}\u{FFFD}\u{FFFD}";

        let s_jp = score_text(japanese);
        let s_garbled = score_text(garbled);
        assert!(
            s_jp > s_garbled,
            "Japanese text ({s_jp}) should score higher than garbled ({s_garbled})"
        );
    }

    #[test]
    fn score_text_cjk_vs_ascii_garbage() {
        // Real CJK text
        let cjk = "株式会社の業績についてご報告いたします";
        // Ascii garbage of similar length
        let garbage = "}{|~`^@#$%&*()!<>[];:',./";

        let s_cjk = score_text(cjk);
        let s_garbage = score_text(garbage);
        assert!(
            s_cjk > s_garbage,
            "CJK text ({s_cjk}) should score higher than garbage ({s_garbage})"
        );
    }

    #[test]
    fn score_text_english_still_works() {
        let good = "the quick brown fox and the lazy dog";
        let bad = "###!!!@@@$$$";
        assert!(score_text(good) > score_text(bad));
    }

    fn doc_with_private_differences() -> (Document, lopdf::ObjectId) {
        let mut doc = Document::with_version("1.7");
        let encoding_id = doc.add_object(dictionary! {
            "Differences" => Object::Array(vec![
                Object::Integer(0x88),
                Object::Name(b"g431".to_vec()),
                Object::Name(b"fi".to_vec()),
                Object::Integer(0xAD),
                Object::Name(b"fl".to_vec()),
            ]),
        });

        (doc, encoding_id)
    }

    #[test]
    fn aptos_private_g431_maps_to_ff_ligature() {
        let (doc, encoding_id) = doc_with_private_differences();
        let font_dict = dictionary! {
            "BaseFont" => Object::Name(b"NJEQOD+Aptos".to_vec()),
            "Encoding" => Object::Reference(encoding_id),
        };

        let result = parse_font_encoding(&doc, &font_dict).expect("encoding should parse");

        assert_eq!(result.map.get(&0x88u8), Some(&'\u{FB00}'));
        assert_eq!(result.map.get(&0x89u8), Some(&'\u{FB01}'));
        assert_eq!(result.map.get(&0xADu8), Some(&'\u{FB02}'));
    }

    #[test]
    fn private_g431_does_not_map_for_unrelated_fonts() {
        let (doc, encoding_id) = doc_with_private_differences();
        let font_dict = dictionary! {
            "BaseFont" => Object::Name(b"ABCDEF+OtherFont".to_vec()),
            "Encoding" => Object::Reference(encoding_id),
        };

        let result = parse_font_encoding(&doc, &font_dict).expect("encoding should parse");

        assert!(!result.map.contains_key(&0x88u8));
        assert_eq!(result.map.get(&0x89u8), Some(&'\u{FB01}'));
        assert_eq!(result.map.get(&0xADu8), Some(&'\u{FB02}'));
    }

    #[test]
    fn cid_font_with_unparseable_cmap_does_not_emit_latin1_mojibake() {
        // Type0/CID font (font_widths reports `is_cid=true`) where the
        // ToUnicode CMap couldn't be parsed (FontCMaps doesn't have the
        // obj_num). Bytes are a 2-byte CID stream containing high bytes
        // that aren't valid UTF-8 — exactly the case in the production
        // samples (Identity-H text where the ToUnicode CMap was missing
        // or malformed, scrape_id 019de78c-..., e.g. "Í Ù Z)¿").
        //
        // Without the guard, the function falls through to the byte-by-byte
        // Latin-1 fallback and produces "ÍÙ" (U+00CD U+00D9). The correct
        // behavior is to emit U+FFFD per CID so downstream
        // `detect_encoding_issues` flags the page for OCR.
        let bytes = vec![0xCD_u8, 0xD9, 0xCD, 0xD9];
        let obj = Object::String(bytes, lopdf::StringFormat::Hexadecimal);

        let font_cmaps = FontCMaps::default();
        let mut font_tounicode_refs: HashMap<String, u32> = HashMap::new();
        font_tounicode_refs.insert("F0".to_string(), 999);
        let inline_cmaps = HashMap::new();
        let font_encodings: PageFontEncodings = HashMap::new();
        let encoding_cache: HashMap<String, Encoding<'_>> = HashMap::new();
        let mut decisions = CMapDecisionCache::new();
        let mut font_widths: PageFontWidths = HashMap::new();
        font_widths.insert("F0".to_string(), make_font_info(&[], 1000, true));

        let result = extract_text_from_operand(
            &obj,
            "F0",
            None,
            &font_cmaps,
            &font_tounicode_refs,
            &inline_cmaps,
            &font_encodings,
            &encoding_cache,
            &mut decisions,
            &font_widths,
        );

        let (text, _) = result.expect("CID font fallback should still emit a marker");
        assert!(
            !text.contains('\u{00CD}') && !text.contains('\u{00D9}'),
            "CID font with unparseable CMap leaked Latin-1 mojibake: {text:?}"
        );
        assert!(
            text.contains('\u{FFFD}'),
            "CID font with unparseable CMap should emit U+FFFD so detect_encoding_issues fires: {text:?}"
        );
    }

    #[test]
    fn simple_font_single_byte_fallback_passes_high_bytes_through() {
        // A Type1/TrueType simple font (is_cid=false) with a `/ToUnicode`
        // reference but no usable CMap and no `/Differences` map.
        // Per-byte fallback is the canonical interpretation here — these
        // bytes are character codes, not CIDs. The CID guard must NOT strip
        // them. Reproduces the false positive that an earlier version of the
        // guard introduced for fonts in PDFs like pdf-evals/Navigating-
        // Artificial-Intelligence-..., where bytes like 0xB6 are legitimate
        // single-byte character codes.
        let bytes = vec![0x24_u8, 0x47, 0xB6, 0x56]; // "$G¶V"
        let obj = Object::String(bytes, lopdf::StringFormat::Hexadecimal);

        let font_cmaps = FontCMaps::default();
        let mut font_tounicode_refs: HashMap<String, u32> = HashMap::new();
        font_tounicode_refs.insert("F1".to_string(), 999);
        let inline_cmaps = HashMap::new();
        let font_encodings: PageFontEncodings = HashMap::new();
        let encoding_cache: HashMap<String, Encoding<'_>> = HashMap::new();
        let mut decisions = CMapDecisionCache::new();
        let mut font_widths: PageFontWidths = HashMap::new();
        font_widths.insert("F1".to_string(), make_font_info(&[], 1000, false));

        let (text, _) = extract_text_from_operand(
            &obj,
            "F1",
            None,
            &font_cmaps,
            &font_tounicode_refs,
            &inline_cmaps,
            &font_encodings,
            &encoding_cache,
            &mut decisions,
            &font_widths,
        )
        .expect("simple font should round-trip Latin-1 bytes");
        assert_eq!(text, "$G\u{00B6}V");
        assert!(
            !text.contains('\u{FFFD}'),
            "simple font fallback must not stamp FFFD over legitimate bytes: {text:?}"
        );
    }

    #[test]
    fn legacy_cleanup_evidence_tracks_changes_without_changing_aliases() {
        for (source, expected, rewritten) in [
            ("AΩμ$•✓", "AΩμ$•✓", false),
            ("\u{f057}\u{f0b7}\u{f0fc}", "W•✓", true),
            ("\u{f010}\u{e123}", "\u{f010}\u{e123}", false),
            ("Price \u{f024}", "Price $", true),
        ] {
            assert_eq!(
                clean_symbol_pua(source.to_string()),
                (expected.to_string(), rewritten)
            );
        }
    }

    #[test]
    fn simple_font_single_byte_fallback_maps_cp1252_punctuation() {
        let bytes = vec![b'l', 0x92_u8, b'a', b'c', b'a', b'd'];
        let obj = Object::String(bytes, lopdf::StringFormat::Hexadecimal);

        let font_cmaps = FontCMaps::default();
        let font_tounicode_refs: HashMap<String, u32> = HashMap::new();
        let inline_cmaps = HashMap::new();
        let font_encodings: PageFontEncodings = HashMap::new();
        let encoding_cache: HashMap<String, Encoding<'_>> = HashMap::new();
        let mut decisions = CMapDecisionCache::new();
        let font_widths: PageFontWidths = HashMap::new();

        let (text, _) = extract_text_from_operand(
            &obj,
            "F1",
            None,
            &font_cmaps,
            &font_tounicode_refs,
            &inline_cmaps,
            &font_encodings,
            &encoding_cache,
            &mut decisions,
            &font_widths,
        )
        .expect("simple font should decode CP1252 punctuation");

        assert_eq!(text, "l’acad");
    }

    #[test]
    fn cached_encoding_decode_normalizes_cp1252_controls() {
        let text = normalize_cp1252_controls("d\u{92}un \u{96} test".to_string(), true);
        assert_eq!(text, "d’un – test");
    }

    #[test]
    fn tex_font_decode_keeps_c1_ligature_bytes_unmodified() {
        let text = normalize_cp1252_controls("de\u{85}ciente \u{87}uid".to_string(), false);
        assert_eq!(text, "de\u{85}ciente \u{87}uid");
        assert!(!should_use_cp1252_single_byte_fallback(
            Some("TTdcr10"),
            false
        ));
        assert!(!should_use_cp1252_single_byte_fallback(
            Some("cmr10"),
            false
        ));
    }

    #[test]
    fn winansi_text_font_uses_cp1252_fallback() {
        assert!(should_use_cp1252_single_byte_fallback(
            Some("BJPQNQ+Times-Roman"),
            false
        ));
    }

    fn gid_font_doc(bfchar: Option<&str>) -> (Document, lopdf::ObjectId) {
        use lopdf::Stream;
        let mut doc = Document::with_version("1.4");
        let cmap = format!(
            "/CIDInit /ProcSet findresource begin
12 dict begin
begincmap
1 begincodespacerange
<00> <FF>
endcodespacerange
1 beginbfchar
{}
endbfchar
endcmap
CMapName currentdict /CMap defineresource pop
end
end",
            bfchar.unwrap_or_default()
        );
        let tounicode_id = doc.add_object(Object::Stream(Stream::new(
            dictionary! {},
            cmap.into_bytes(),
        )));
        let enc_id = doc.add_object(dictionary! {
            "Type" => "Encoding",
            "Differences" => vec![
                1.into(),
                Object::Name(b"gid1283".to_vec()),
                Object::Name(b"gid1464".to_vec()),
            ],
        });
        let mut font = dictionary! {
            "Type" => "Font",
            "Subtype" => "TrueType",
            "BaseFont" => "ABCDEF+OpenSymbol",
            "Encoding" => Object::Reference(enc_id),
        };
        if bfchar.is_some() {
            font.set("ToUnicode", Object::Reference(tounicode_id));
        }
        let font_id = doc.add_object(font);
        let page_id = doc.add_object(dictionary! {
            "Type" => "Page",
            "Resources" => dictionary! {
                "Font" => dictionary! { "F1" => Object::Reference(font_id) },
            },
            "MediaBox" => vec![0.into(), 0.into(), 612.into(), 792.into()],
        });
        let pages_id = doc.add_object(dictionary! {
            "Type" => "Pages",
            "Count" => Object::Integer(1),
            "Kids" => vec![Object::Reference(page_id)],
        });
        let catalog_id = doc.add_object(dictionary! {
            "Type" => "Catalog",
            "Pages" => Object::Reference(pages_id),
        });
        doc.trailer.set("Root", Object::Reference(catalog_id));
        (doc, page_id)
    }

    fn gid_flagged(bfchar: Option<&str>) -> bool {
        let (doc, page_id) = gid_font_doc(bfchar);
        let cmaps = FontCMaps::from_doc(&doc);
        let fonts = doc.get_page_fonts(page_id).unwrap();
        let (_, has_gid_fonts) =
            build_font_encodings(&doc, &fonts, &cmaps, &mut FontStyleCache::new());
        has_gid_fonts
    }

    #[test]
    fn gid_differences_with_covering_tounicode_are_not_flagged() {
        // LibreOffice subsets write /gidNNNN Differences names alongside a
        // ToUnicode CMap that decodes those codes; the page must not be
        // flagged as unresolvable (which would suppress the whole document's
        // markdown when every page carries such a font).
        assert!(!gid_flagged(Some("<01> <2022>\n<02> <25E6>")));
    }

    #[test]
    fn gid_differences_with_partial_tounicode_are_not_flagged() {
        // An emoji ZWJ sequence maps whole on its first code; the remaining
        // component-glyph codes are subset leftovers, not damage.
        assert!(!gid_flagged(Some(
            "<01> <D83DDC68200DD83DDC69200DD83DDC67>"
        )));
    }

    #[test]
    fn gid_differences_without_tounicode_are_flagged() {
        assert!(
            gid_flagged(None),
            "gid glyphs without ToUnicode are unresolvable"
        );
    }

    #[test]
    fn gid_differences_with_disjoint_tounicode_are_flagged() {
        // A ToUnicode that never addresses the gid codes leaves them
        // unresolvable.
        assert!(gid_flagged(Some("<10> <0041>")));
    }

    #[test]
    fn gid_differences_with_replacement_char_tounicode_are_flagged() {
        // A mapping to U+FFFD is not usable — extraction rejects it as an
        // invalid CMap result — so it must not clear the gid flag.
        assert!(gid_flagged(Some("<01> <FFFD>\n<02> <FFFD>")));
    }

    #[test]
    fn parse_cid_w_array_range_and_consecutive() {
        use super::parse_cid_w_array;
        use lopdf::{Document, Object};
        use std::collections::HashMap;

        let doc = Document::new();
        let mut widths = HashMap::new();
        let w = vec![
            Object::Integer(10),
            Object::Integer(12),
            Object::Integer(500),
            Object::Integer(20),
            Object::Array(vec![Object::Integer(100), Object::Integer(200)]),
        ];
        parse_cid_w_array(&doc, &w, &mut widths);
        assert_eq!(widths.get(&10), Some(&500));
        assert_eq!(widths.get(&11), Some(&500));
        assert_eq!(widths.get(&12), Some(&500));
        assert_eq!(widths.get(&20), Some(&100));
        assert_eq!(widths.get(&21), Some(&200));
    }

    #[test]
    fn parse_cid_w_array_repeated_full_ranges_stay_bounded() {
        use super::parse_cid_w_array;
        use crate::tounicode::MAX_CID_W_EXPANSION;
        use lopdf::{Document, Object};
        use std::collections::HashMap;

        let doc = Document::new();
        let mut widths = HashMap::new();
        let mut w = Vec::new();
        for _ in 0..5_000 {
            w.push(Object::Integer(0));
            w.push(Object::Integer(65535));
            w.push(Object::Integer(500));
        }
        parse_cid_w_array(&doc, &w, &mut widths);
        assert!(widths.len() <= MAX_CID_W_EXPANSION);
        assert_eq!(widths.get(&0), Some(&500));
        assert_eq!(widths.get(&65535), Some(&500));
    }
}

#[cfg(test)]
#[path = "stale_cmap_tests.rs"]
mod stale_cmap_tests;

#[cfg(test)]
#[path = "blank_glyph_tests.rs"]
mod blank_glyph_tests;