pdfrum 0.1.0

A composable PDF library built in Rust
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
//! `DocEdit::embed_font` and `DocEdit::standard_font`: what a loaded font
//! writes into the file, and what comes back out of it.
//!
//! Ports PDFium's `FPDFText_LoadFont` / `FPDFText_LoadStandardFont` embedder
//! cases (`fpdfsdk/fpdf_edittext_embeddertest.cpp`,
//! `fpdfsdk/fpdf_edit_embeddertest.cpp`) onto
//! `DocEdit::embed_font(bytes, FontEncoding::{Simple, Composite})` and
//! `DocEdit::standard_font(StandardFont)`. Each test asserts what its C++
//! counterpart asserts in substance — the dictionary shape the load produces,
//! the text that extracts back through `/ToUnicode`, the ink the page gains,
//! and that the oracle reopens the result — rather than only that the call
//! returned `Ok`.
//!
//! The five subsetting cases live in `load_font_subset.rs`; the two files
//! duplicate their five helpers rather than share a module, because STYLE §4
//! forbids a test module named `common`/`util`/`helpers` and the repo has no
//! `#[path]` convention to reach for instead.

#![allow(
    clippy::expect_used,
    clippy::panic,
    reason = "a test that cannot open its own fixture has nothing to report but a panic"
)]

use std::path::{Path, PathBuf};
use std::process::Command;
use std::sync::Arc;

use pdfrum::{
    Affine, Dict, Document, FontEncoding, ObjRef, Point, RenderOptions, Resolve, SaveOptions,
    StandardFont, TextBuilder, VelloCpuBackend,
};
use pdfrum_object::Name;

const HELLO_PDF: &[u8] = include_bytes!("fixtures/hello_world.pdf");
const ROBOTO: &[u8] = include_bytes!("fixtures/roboto.ttf");
const BUG_2094: &[u8] = include_bytes!("fixtures/bug_2094.ttf");
const BUG_377948405: &[u8] = include_bytes!("fixtures/bug_377948405.ttf");
/// A real Type 1 program. The oracle's `LoadSimpleType1Font` /
/// `LoadCIDType0Font` hand `FPDFText_LoadFont` a *stock* font's span, which
/// under the hermetic test-fonts config is a TrueType substitute — so the
/// Type 1 path those two cases name is only reachable here with an actual
/// Type 1 program. `pdfrum-type1`'s fixture is one, and is not duplicated
/// into this directory.
const FOXIT_SERIF_MM: &[u8] = include_bytes!("../../pdfrum-font/fontdata/FoxitSerifMM.pfb");
/// The font `FPDFEditEmbedderTest.LoadCidType2FontCustom` loads: eleven
/// glyphs, real advances, and no cmap worth speaking of — which is the point,
/// since the caller's `/CIDToGIDMap` is what reaches its glyphs.
const NOTO_SANS_SC: &[u8] = include_bytes!("fixtures/noto_sans_sc_subset.otf");

fn scratch_dir() -> std::path::PathBuf {
    let dir = std::env::temp_dir().join("pdfrum-load-font");
    std::fs::create_dir_all(&dir).expect("scratch");
    dir
}

fn fetch_dict(doc: &Document, reference: ObjRef) -> Dict {
    doc.parser()
        .fetch(reference)
        .expect("fetches")
        .as_dict()
        .expect("dict")
        .clone()
}

/// The `/Length1` of the first `/FontFile2` stream in `pdf`.
fn length1_of(pdf: &[u8]) -> i64 {
    let needle = b"/Length1 ";
    let mut i = 0;
    while i + needle.len() < pdf.len() {
        if pdf.get(i..i + needle.len()) == Some(needle.as_slice()) {
            let rest = pdf.get(i + needle.len()..).unwrap_or_default();
            let digits: String = rest
                .iter()
                .take_while(|b| b.is_ascii_digit())
                .map(|b| char::from(*b))
                .collect();
            if let Ok(n) = digits.parse::<i64>() {
                return n;
            }
        }
        i += 1;
    }
    panic!("no /Length1 in the saved file");
}

fn extracted(bytes: &[u8]) -> String {
    let doc = Document::from_bytes(Arc::from(bytes)).expect("opens");
    doc.page(0).expect("page").text().to_string()
}

fn pixels(bytes: &[u8]) -> (u32, u32, Vec<u8>) {
    let doc = Document::from_bytes(Arc::from(bytes)).expect("opens");
    let pix = doc
        .page(0)
        .expect("page")
        .render(&VelloCpuBackend::new(), &RenderOptions::default())
        .expect("renders");
    (pix.width(), pix.height(), pix.data().to_vec())
}

fn dark_pixels(data: &[u8]) -> usize {
    data.as_chunks::<4>()
        .0
        .iter()
        .filter(|&&[r, g, b, a]| a > 0 && (u16::from(r) + u16::from(g) + u16::from(b)) < 600)
        .count()
}

/// The oracle's `pdfium_test`, when this machine has one.
///
/// One place, two inputs: `$PDFRUM_ORACLE_BIN`, else
/// `$PDFRUM_ORACLE_CHECKOUT/out/Release/pdfium_test`, whose own default is the
/// sibling `../pdfium-c++` directory README.md names. Same defaults as
/// the conformance harness.
///
/// Six lines rather than a shared module: forbids a `common`,
/// `util` or `helpers` module name, an integration test cannot reach another
/// crate's test code, and the one sibling that wants this
/// (`load_font_subset.rs`) carries the same six lines with the same comment.
fn oracle_bin() -> Option<PathBuf> {
    let bin = std::env::var_os("PDFRUM_ORACLE_BIN").map_or_else(
        || {
            let checkout = std::env::var_os("PDFRUM_ORACLE_CHECKOUT").map_or_else(
                || Path::new(env!("CARGO_MANIFEST_DIR")).join("../../../pdfium-c++"),
                PathBuf::from,
            );
            checkout.join("out/Release/pdfium_test")
        },
        PathBuf::from,
    );
    bin.is_file().then_some(bin)
}

fn oracle_md5(path: &Path) -> Result<String, String> {
    let Some(bin) = oracle_bin() else {
        return Err("pdfium_test binary is absent; skip oracle reopen".into());
    };
    let out = Command::new(bin)
        .args(["--md5", "--png", "--pages=0"])
        .arg(path)
        .output()
        .map_err(|e| e.to_string())?;
    if !out.status.success() {
        return Err(format!(
            "pdfium_test --md5 exited {}: {}",
            out.status,
            String::from_utf8_lossy(&out.stderr)
        ));
    }
    Ok(String::from_utf8_lossy(&out.stdout).into_owned())
}

#[test]
fn embed_composite_writes_hello_extracts_and_renders() {
    let doc = Document::from_bytes(Arc::from(HELLO_PDF)).expect("opens");
    let original = doc
        .page(0)
        .expect("page")
        .render(&VelloCpuBackend::new(), &RenderOptions::default())
        .expect("renders");
    let original_dark = dark_pixels(original.data());

    let mut edit = doc.edit();
    let font = edit
        .embed_font(ROBOTO, FontEncoding::Composite)
        .expect("embeds Roboto");
    let mut page = doc.page(0).expect("page").edit();
    page.push(
        TextBuilder {
            position: pdfrum::Point::new(20.0, 40.0),
            ..TextBuilder::new(font.encode("Hello"), font.object(), 24.0)
        }
        .build(),
    );

    let dir = scratch_dir();
    let out = dir.join("hello_roboto.pdf");
    edit.save_pages(&out, &[page], &SaveOptions::default())
        .expect("saves");
    let saved = std::fs::read(&out).expect("reads");

    let text = extracted(&saved);
    assert!(
        text.contains("Hello"),
        "extracted text should contain Hello via /ToUnicode, got {text:?}"
    );

    let (_, _, pix) = pixels(&saved);
    let after_dark = dark_pixels(&pix);
    assert!(
        after_dark > original_dark,
        "placed text should add ink ({after_dark} dark pixels vs original {original_dark})"
    );

    let before = length1_of(&saved);

    // The first save wrote the font as new without subsetting. A second
    // save of the same construction with `subset_new_fonts` should shrink
    // the program.
    let mut edit_first = doc.edit();
    let font = edit_first
        .embed_font(ROBOTO, FontEncoding::Composite)
        .expect("embeds");
    let mut page = doc.page(0).expect("page").edit();
    page.push(
        TextBuilder {
            position: pdfrum::Point::new(20.0, 40.0),
            ..TextBuilder::new(font.encode("Hello"), font.object(), 24.0)
        }
        .build(),
    );
    let subset_path = dir.join("hello_roboto_subset.pdf");
    edit_first
        .save_pages(&subset_path, &[page], &{
            let mut __o = SaveOptions::default();
            __o.subset_new_fonts = true;
            __o
        })
        .expect("subset save");
    let subset_bytes = std::fs::read(&subset_path).expect("reads subset");
    let after = length1_of(&subset_bytes);
    assert!(
        after < before,
        "subsetted /FontFile2 Length1 {after} should be smaller than {before}"
    );

    let subset_text = extracted(&subset_bytes);
    assert!(
        subset_text.contains("Hello"),
        "subsetted file still extracts Hello, got {subset_text:?}"
    );
    let (_, _, subset_pix) = pixels(&subset_bytes);
    assert!(
        dark_pixels(&subset_pix) > original_dark,
        "subsetted file still draws the new text"
    );

    match oracle_md5(&out) {
        Ok(stdout) => {
            assert!(
                stdout.contains("MD5:"),
                "pdfium_test --md5 should print a page hash, got {stdout:?}"
            );
        }
        Err(msg) => {
            eprintln!("skipping oracle reopen: {msg}");
        }
    }
    match oracle_md5(&subset_path) {
        Ok(stdout) => {
            assert!(
                stdout.contains("MD5:"),
                "oracle should reopen the subsetted file, got {stdout:?}"
            );
        }
        Err(msg) => {
            eprintln!("skipping oracle reopen (subset): {msg}");
        }
    }
}

#[test]
fn standard_fourteen_round_trips_hello() {
    let doc = Document::from_bytes(Arc::from(HELLO_PDF)).expect("opens");
    let original_dark = dark_pixels(
        doc.page(0)
            .expect("page")
            .render(&VelloCpuBackend::new(), &RenderOptions::default())
            .expect("renders")
            .data(),
    );

    let mut edit = doc.edit();
    let font = edit
        .standard_font(StandardFont::Helvetica)
        .expect("Helvetica");
    let mut page = doc.page(0).expect("page").edit();
    page.push(
        TextBuilder {
            position: pdfrum::Point::new(20.0, 60.0),
            ..TextBuilder::new(font.encode("Hello"), font.object(), 18.0)
        }
        .build(),
    );
    let dir = scratch_dir();
    let out = dir.join("hello_helvetica.pdf");
    edit.save_pages(&out, &[page], &SaveOptions::default())
        .expect("saves");
    let saved = std::fs::read(&out).expect("reads");
    let text = extracted(&saved);
    assert!(
        text.contains("Hello"),
        "standard-14 WinAnsi text should extract, got {text:?}"
    );
    let (_, _, pix) = pixels(&saved);
    assert!(
        dark_pixels(&pix) > original_dark,
        "standard-14 text should add ink"
    );
}

#[test]
fn add_standard_font_text_extracts_and_renders() {
    // Ports FPDFEditEmbedderTest.AddStandardFontText and AddStandardFontText2.
    let doc = Document::from_bytes(Arc::from(HELLO_PDF)).expect("opens");
    let original_dark = dark_pixels(&pixels(HELLO_PDF).2);

    let mut edit = doc.edit();
    let font = edit
        .standard_font(StandardFont::Helvetica)
        .expect("Helvetica");
    let mut page = doc.page(0).expect("page").edit();
    page.push(
        TextBuilder {
            position: Point::new(20.0, 20.0),
            ..TextBuilder::new(font.encode("This is some text."), font.object(), 12.0)
        }
        .build(),
    );

    let dir = scratch_dir();
    let out = dir.join("add_standard_font.pdf");
    edit.save_pages(&out, &[page], &SaveOptions::default())
        .expect("saves");
    let saved = std::fs::read(&out).expect("reads");

    let saved_doc = Document::from_bytes(Arc::from(saved.as_slice())).expect("reopens");
    let font_obj = fetch_dict(&saved_doc, font.object());
    assert_eq!(
        font_obj.name(&Name::from("Type")).map(Name::as_bytes),
        Some(&b"Font"[..])
    );
    assert_eq!(
        font_obj.name(&Name::from("Subtype")).map(Name::as_bytes),
        Some(&b"Type1"[..])
    );
    assert_eq!(
        font_obj.name(&Name::from("BaseFont")).map(Name::as_bytes),
        Some(&b"Helvetica"[..])
    );
    assert_eq!(
        font_obj.name(&Name::from("Encoding")).map(Name::as_bytes),
        Some(&b"WinAnsiEncoding"[..])
    );
    assert!(font_obj.raw(&Name::from("Widths")).is_none());
    assert!(font_obj.raw(&Name::from("FontDescriptor")).is_none());

    let text = extracted(&saved);
    assert!(
        text.contains("This is some text."),
        "extracted text should contain added text, got {text:?}"
    );

    let (_, _, pix) = pixels(&saved);
    let after_dark = dark_pixels(&pix);
    assert!(
        after_dark > original_dark,
        "standard font text should add ink"
    );

    match oracle_md5(&out) {
        Ok(stdout) => {
            assert!(stdout.contains("MD5:"));
        }
        Err(msg) => {
            eprintln!("skipping oracle reopen: {msg}");
        }
    }
}

#[test]
fn standard_fonts_encode_winansi_and_unmappable() {
    // Ports FPDFEditEmbedderTest.LoadStandardFonts and CharCodeFromUnicode WinAnsi mapping.
    let doc = Document::from_bytes(Arc::from(HELLO_PDF)).expect("opens");
    let mut edit = doc.edit();

    let helvetica = edit
        .standard_font(StandardFont::Helvetica)
        .expect("sans: Helvetica");
    let times = edit
        .standard_font(StandardFont::Times)
        .expect("serif: Times-Roman");
    let courier = edit
        .standard_font(StandardFont::Courier)
        .expect("fixed-pitch: Courier");

    for font in [&helvetica, &times, &courier] {
        // Non-ASCII WinAnsi characters:
        // '€' (U+20AC) -> WinAnsi 0x80 (128)
        assert_eq!(font.encode(""), vec![128]);
        // 'é' (U+00E9) -> WinAnsi 0xE9 (233)
        assert_eq!(font.encode("é"), vec![233]);
        // Combined string
        assert_eq!(
            font.encode("Café €"),
            vec![b'C', b'a', b'f', 233, b' ', 128]
        );
        // Unmappable characters -> code 0 (CharCodeFromUnicode)
        assert_eq!(font.encode("\u{0100}"), vec![0]);
        assert_eq!(font.encode("\u{4e00}"), vec![0]);
    }

    let mut page = doc.page(0).expect("page").edit();
    page.push(
        TextBuilder {
            position: Point::new(20.0, 30.0),
            ..TextBuilder::new(
                helvetica.encode("Helvetica Café €"),
                helvetica.object(),
                12.0,
            )
        }
        .build(),
    );
    page.push(
        TextBuilder {
            position: Point::new(20.0, 50.0),
            ..TextBuilder::new(times.encode("Times Café €"), times.object(), 12.0)
        }
        .build(),
    );
    page.push(
        TextBuilder {
            position: Point::new(20.0, 70.0),
            ..TextBuilder::new(courier.encode("Courier Café €"), courier.object(), 12.0)
        }
        .build(),
    );

    let dir = scratch_dir();
    let out = dir.join("standard_14_winansi.pdf");
    edit.save_pages(&out, &[page], &SaveOptions::default())
        .expect("saves");
    let saved = std::fs::read(&out).expect("reads");

    let saved_doc = Document::from_bytes(Arc::from(saved.as_slice())).expect("reopens");
    for (obj, expected_name) in [
        (helvetica.object(), &b"Helvetica"[..]),
        (times.object(), &b"Times-Roman"[..]),
        (courier.object(), &b"Courier"[..]),
    ] {
        let dict = fetch_dict(&saved_doc, obj);
        assert_eq!(
            dict.name(&Name::from("Subtype")).map(Name::as_bytes),
            Some(&b"Type1"[..])
        );
        assert_eq!(
            dict.name(&Name::from("BaseFont")).map(Name::as_bytes),
            Some(expected_name)
        );
        assert_eq!(
            dict.name(&Name::from("Encoding")).map(Name::as_bytes),
            Some(&b"WinAnsiEncoding"[..])
        );
    }

    let text = extracted(&saved);
    assert!(text.contains("Helvetica"));
    assert!(text.contains("Times"));
    assert!(text.contains("Courier"));

    match oracle_md5(&out) {
        Ok(stdout) => {
            assert!(stdout.contains("MD5:"));
        }
        Err(msg) => {
            eprintln!("skipping oracle reopen: {msg}");
        }
    }
}

#[test]
fn font_encoding_variants_encode_ascii_non_ascii_and_unmappable() {
    // Ports FontEncoding::{Simple, Composite} CharCodeFromUnicode and Identity-H mappings.
    let doc = Document::from_bytes(Arc::from(HELLO_PDF)).expect("opens");
    let mut edit = doc.edit();

    let simple = edit
        .embed_font(ROBOTO, FontEncoding::Simple)
        .expect("embeds simple");
    assert_eq!(simple.encode("Hello"), b"Hello".to_vec());
    assert_eq!(simple.encode("é"), vec![233]);
    assert_eq!(simple.encode("\u{0100}"), vec![0]);
    assert_eq!(simple.encode("\u{4e00}"), vec![0]);

    let composite = edit
        .embed_font(ROBOTO, FontEncoding::Composite)
        .expect("embeds composite");
    let encoded_hello = composite.encode("Hello");
    assert_eq!(
        encoded_hello.len(),
        10,
        "2 bytes per character for composite"
    );
    assert_eq!(composite.encode("\u{1f600}"), vec![0, 0]);
}

#[test]
fn add_truetype_font_simple_encoding_extracts_and_renders() {
    // Ports FPDFEditEmbedderTest.AddTrueTypeFontText.
    let doc = Document::from_bytes(Arc::from(HELLO_PDF)).expect("opens");
    let original_dark = dark_pixels(&pixels(HELLO_PDF).2);

    let mut edit = doc.edit();
    let font = edit
        .embed_font(ROBOTO, FontEncoding::Simple)
        .expect("embeds simple Roboto");
    let mut page = doc.page(0).expect("page").edit();
    page.push(
        TextBuilder {
            position: Point::new(40.0, 40.0),
            ..TextBuilder::new(font.encode("This is some text."), font.object(), 12.0)
        }
        .build(),
    );
    page.push(
        TextBuilder {
            position: Point::new(40.0, 80.0),
            ..TextBuilder::new(font.encode("Bigger font size"), font.object(), 15.0)
        }
        .build(),
    );

    let dir = scratch_dir();
    let out = dir.join("add_truetype_simple.pdf");
    edit.save_pages(&out, &[page], &SaveOptions::default())
        .expect("saves");
    let saved = std::fs::read(&out).expect("reads");

    let saved_doc = Document::from_bytes(Arc::from(saved.as_slice())).expect("reopens");
    let font_dict = fetch_dict(&saved_doc, font.object());
    assert_eq!(
        font_dict.name(&Name::from("Type")).map(Name::as_bytes),
        Some(&b"Font"[..])
    );
    assert_eq!(
        font_dict.name(&Name::from("Subtype")).map(Name::as_bytes),
        Some(&b"TrueType"[..])
    );
    assert_eq!(
        font_dict.name(&Name::from("BaseFont")).map(Name::as_bytes),
        Some(&b"Roboto-Regular"[..])
    );

    let first = font_dict
        .direct_int(&Name::from("FirstChar"))
        .expect("FirstChar");
    let last = font_dict
        .direct_int(&Name::from("LastChar"))
        .expect("LastChar");
    assert!(last >= first);

    let widths_ref = font_dict.reference(&Name::from("Widths")).expect("Widths");
    let widths = saved_doc
        .parser()
        .fetch(widths_ref)
        .expect("widths")
        .as_array()
        .expect("array")
        .clone();
    assert_eq!(
        widths.len(),
        usize::try_from(last - first + 1).expect("fits")
    );

    let desc_ref = font_dict
        .reference(&Name::from("FontDescriptor"))
        .expect("FontDescriptor");
    let desc = fetch_dict(&saved_doc, desc_ref);
    let file2_ref = desc.reference(&Name::from("FontFile2")).expect("FontFile2");
    let file2 = saved_doc
        .parser()
        .fetch(file2_ref)
        .expect("file2")
        .as_stream()
        .expect("stream")
        .clone();
    let length1 = file2
        .dict
        .direct_int(&Name::from("Length1"))
        .expect("Length1");
    assert_eq!(length1, i64::try_from(ROBOTO.len()).expect("fits"));

    let text = extracted(&saved);
    assert!(text.contains("This is some text."));
    assert!(text.contains("Bigger font size"));

    let (_, _, pix) = pixels(&saved);
    assert!(dark_pixels(&pix) > original_dark);

    match oracle_md5(&out) {
        Ok(stdout) => {
            assert!(stdout.contains("MD5:"));
        }
        Err(msg) => {
            eprintln!("skipping oracle reopen: {msg}");
        }
    }
}

#[test]
fn load_simple_truetype_font_descriptor_and_widths_shape() {
    // Ports FPDFEditEmbedderTest.LoadSimpleTrueTypeFont.
    let doc = Document::from_bytes(Arc::from(HELLO_PDF)).expect("opens");
    let mut edit = doc.edit();
    let font = edit
        .embed_font(ROBOTO, FontEncoding::Simple)
        .expect("embeds simple Roboto");
    let mut page = doc.page(0).expect("page").edit();
    page.push(
        TextBuilder {
            position: Point::new(20.0, 30.0),
            ..TextBuilder::new(font.encode("Courier Cousine Test"), font.object(), 12.0)
        }
        .build(),
    );

    let dir = scratch_dir();
    let out = dir.join("load_simple_truetype_shape.pdf");
    edit.save_pages(&out, &[page], &SaveOptions::default())
        .expect("saves");
    let saved = std::fs::read(&out).expect("reads");

    let saved_doc = Document::from_bytes(Arc::from(saved.as_slice())).expect("reopens");
    let font_dict = fetch_dict(&saved_doc, font.object());
    assert_eq!(
        font_dict.name(&Name::from("Type")).map(Name::as_bytes),
        Some(&b"Font"[..])
    );
    assert_eq!(
        font_dict.name(&Name::from("Subtype")).map(Name::as_bytes),
        Some(&b"TrueType"[..])
    );
    assert_eq!(
        font_dict.name(&Name::from("BaseFont")).map(Name::as_bytes),
        Some(&b"Roboto-Regular"[..])
    );

    let first = font_dict
        .direct_int(&Name::from("FirstChar"))
        .expect("FirstChar");
    let last = font_dict
        .direct_int(&Name::from("LastChar"))
        .expect("LastChar");
    assert!(first <= 32, "first char code <= 32, got {first}");
    assert!(last >= 126);

    let widths_ref = font_dict.reference(&Name::from("Widths")).expect("Widths");
    let widths = saved_doc
        .parser()
        .fetch(widths_ref)
        .expect("widths")
        .as_array()
        .expect("array")
        .clone();
    assert_eq!(
        widths.len(),
        usize::try_from(last - first + 1).expect("fits")
    );
    let non_zero_count = widths
        .iter()
        .filter_map(|o| o.as_int().and_then(|w| (w > 0).then_some(())))
        .count();
    assert!(
        non_zero_count > 100,
        "expected over 100 positive glyph advances, got {non_zero_count}"
    );

    let desc_ref = font_dict
        .reference(&Name::from("FontDescriptor"))
        .expect("FontDescriptor");
    let desc = fetch_dict(&saved_doc, desc_ref);
    assert_eq!(
        desc.name(&Name::from("Type")).map(Name::as_bytes),
        Some(&b"FontDescriptor"[..])
    );
    let flags = desc.direct_int(&Name::from("Flags")).expect("Flags");
    assert_eq!(flags & (1 << 5), 1 << 5, "NonSymbolic flag bit 6");
    assert!(desc.raw(&Name::from("FontBBox")).is_some());
    assert!(desc.raw(&Name::from("Ascent")).is_some());
    assert!(desc.raw(&Name::from("Descent")).is_some());
    assert!(desc.raw(&Name::from("CapHeight")).is_some());
    assert!(desc.raw(&Name::from("StemV")).is_some());
}

#[test]
#[allow(clippy::too_many_lines)]
fn load_cid_type2_font_dictionary_structure() {
    // Ports FPDFEditEmbedderTest.LoadCIDType2Font.
    let doc = Document::from_bytes(Arc::from(HELLO_PDF)).expect("opens");
    let mut edit = doc.edit();
    let font = edit
        .embed_font(ROBOTO, FontEncoding::Composite)
        .expect("embeds composite Roboto");
    let mut page = doc.page(0).expect("page").edit();
    page.push(
        TextBuilder {
            position: Point::new(20.0, 40.0),
            ..TextBuilder::new(font.encode("CID Type 2"), font.object(), 14.0)
        }
        .build(),
    );

    let dir = scratch_dir();
    let out = dir.join("load_cid_type2.pdf");
    edit.save_pages(&out, &[page], &SaveOptions::default())
        .expect("saves");
    let saved = std::fs::read(&out).expect("reads");

    let saved_doc = Document::from_bytes(Arc::from(saved.as_slice())).expect("reopens");
    let font_dict = fetch_dict(&saved_doc, font.object());
    assert_eq!(
        font_dict.name(&Name::from("Type")).map(Name::as_bytes),
        Some(&b"Font"[..])
    );
    assert_eq!(
        font_dict.name(&Name::from("Subtype")).map(Name::as_bytes),
        Some(&b"Type0"[..])
    );
    assert_eq!(
        font_dict.name(&Name::from("BaseFont")).map(Name::as_bytes),
        Some(&b"Roboto-Regular"[..])
    );
    assert_eq!(
        font_dict.name(&Name::from("Encoding")).map(Name::as_bytes),
        Some(&b"Identity-H"[..])
    );

    let descendants = font_dict
        .array(&Name::from("DescendantFonts"), saved_doc.parser())
        .expect("DescendantFonts");
    assert_eq!(descendants.len(), 1);
    let cid_ref = descendants.reference_at(0).expect("cid ref");
    let cid_dict = fetch_dict(&saved_doc, cid_ref);
    assert_eq!(
        cid_dict.name(&Name::from("Type")).map(Name::as_bytes),
        Some(&b"Font"[..])
    );
    assert_eq!(
        cid_dict.name(&Name::from("Subtype")).map(Name::as_bytes),
        Some(&b"CIDFontType2"[..])
    );
    assert_eq!(
        cid_dict.name(&Name::from("BaseFont")).map(Name::as_bytes),
        Some(&b"Roboto-Regular"[..])
    );

    let cid_info = cid_dict
        .dict(&Name::from("CIDSystemInfo"), saved_doc.parser())
        .expect("CIDSystemInfo");
    assert_eq!(
        cid_info.byte_string(&Name::from("Registry"), saved_doc.parser()),
        Some(b"Adobe".to_vec())
    );
    assert_eq!(
        cid_info.byte_string(&Name::from("Ordering"), saved_doc.parser()),
        Some(b"Identity".to_vec())
    );
    assert_eq!(cid_info.direct_int(&Name::from("Supplement")), Some(0));

    let w_ref = cid_dict.reference(&Name::from("W")).expect("W");
    let w = saved_doc
        .parser()
        .fetch(w_ref)
        .expect("w")
        .as_array()
        .expect("array")
        .clone();
    assert!(!w.is_empty(), "CID widths array should not be empty");

    let tu = font_dict
        .stream(&Name::from("ToUnicode"), saved_doc.parser())
        .expect("ToUnicode");
    let tu_bytes = pdfrum_filters::decode_chain(
        &tu,
        0,
        saved_doc.parser(),
        &pdfrum_common::Limits::default(),
        &mut pdfrum_common::Diagnostics::default(),
    )
    .data;
    assert!(tu_bytes.windows(9).any(|w| w == b"begincmap"));
    assert!(tu_bytes.windows(7).any(|w| w == b"endcmap"));

    let desc_ref = cid_dict
        .reference(&Name::from("FontDescriptor"))
        .expect("FontDescriptor");
    let desc = fetch_dict(&saved_doc, desc_ref);
    let file2_ref = desc.reference(&Name::from("FontFile2")).expect("FontFile2");
    let file2 = saved_doc
        .parser()
        .fetch(file2_ref)
        .expect("file2")
        .as_stream()
        .expect("stream")
        .clone();
    assert!(file2.dict.direct_int(&Name::from("Length1")).is_some());
}

#[test]
fn add_cid_font_text_extracts_and_renders() {
    // Ports FPDFEditEmbedderTest.AddCIDFontText and FPDFEditEmbedderTest.EmbedNotoSansSCFont.
    let doc = Document::from_bytes(Arc::from(HELLO_PDF)).expect("opens");
    let original_dark = dark_pixels(&pixels(HELLO_PDF).2);

    let mut edit = doc.edit();
    let font = edit
        .embed_font(ROBOTO, FontEncoding::Composite)
        .expect("embeds composite Roboto");
    let mut page = doc.page(0).expect("page").edit();
    page.push(
        TextBuilder {
            position: Point::new(20.0, 50.0),
            ..TextBuilder::new(font.encode("Hello world, Café naïve!"), font.object(), 14.0)
        }
        .build(),
    );

    let dir = scratch_dir();
    let out = dir.join("add_cid_font_text.pdf");
    edit.save_pages(&out, &[page], &SaveOptions::default())
        .expect("saves");
    let saved = std::fs::read(&out).expect("reads");

    let text = extracted(&saved);
    assert!(
        text.contains("Hello world, Café naïve!"),
        "ToUnicode CMap must recover exact unicode string, got {text:?}"
    );

    let (_, _, pix) = pixels(&saved);
    assert!(dark_pixels(&pix) > original_dark);

    match oracle_md5(&out) {
        Ok(stdout) => {
            assert!(stdout.contains("MD5:"));
        }
        Err(msg) => {
            eprintln!("skipping oracle reopen: {msg}");
        }
    }
}

#[test]
fn embed_composite_font_direct_charcodes_extracts_and_renders() {
    // Ports FPDFEditEmbedderTest.EmbedNotoSansSCFontWithCharcodes.
    let doc = Document::from_bytes(Arc::from(HELLO_PDF)).expect("opens");
    let original_dark = dark_pixels(&pixels(HELLO_PDF).2);

    let mut edit = doc.edit();
    let font = edit
        .embed_font(ROBOTO, FontEncoding::Composite)
        .expect("embeds");

    let codes = font.encode("Hello direct");
    let mut page = doc.page(0).expect("page").edit();
    page.push(
        TextBuilder {
            position: Point::new(20.0, 140.0),
            ..TextBuilder::new(codes, font.object(), 16.0)
        }
        .build(),
    );

    let dir = scratch_dir();
    let out = dir.join("direct_charcodes.pdf");
    edit.save_pages(&out, &[page], &SaveOptions::default())
        .expect("saves");
    let saved = std::fs::read(&out).expect("reads");

    let text = extracted(&saved);
    assert!(text.contains("Hello direct"));

    let (_, _, pix) = pixels(&saved);
    assert!(dark_pixels(&pix) > original_dark);

    match oracle_md5(&out) {
        Ok(stdout) => {
            assert!(stdout.contains("MD5:"));
        }
        Err(msg) => {
            eprintln!("skipping oracle reopen: {msg}");
        }
    }
}

/// Ports `FPDFEditEmbedderTest.Bug2094`.
///
/// The C++ case is one line — `EXPECT_TRUE(font)` — because the bug was a
/// crash while *building* the font, on a program whose tables are degenerate.
/// A Rust `Result` makes "did not crash" free, so the port has to say more to
/// be worth its fixture: it pins the whole composite shape this program
/// produces, including the two facts that made the bug reachable — the font
/// names itself `Test` and its cmap covers **nothing**, so every code maps to
/// `.notdef` and `/W` collapses to one run at CID 0.
#[test]
fn embed_bug_2094_ttf_composite_succeeds() {
    let doc = Document::from_bytes(Arc::from(HELLO_PDF)).expect("opens");
    let mut edit = doc.edit();
    let font = edit
        .embed_font(BUG_2094, FontEncoding::Composite)
        .expect("embeds bug_2094.ttf");

    // The program has no usable Unicode cmap, so `char_maps`'s fallback runs
    // and every character encodes to two zero bytes.
    assert_eq!(font.encode("A"), vec![0, 0]);

    let mut page = doc.page(0).expect("page").edit();
    page.push(
        TextBuilder {
            position: Point::new(20.0, 40.0),
            ..TextBuilder::new(font.encode("Test"), font.object(), 16.0)
        }
        .build(),
    );

    let dir = scratch_dir();
    let out = dir.join("bug_2094.pdf");
    edit.save_pages(&out, &[page], &SaveOptions::default())
        .expect("saves");
    let saved = std::fs::read(&out).expect("reads");

    let saved_doc = Document::from_bytes(Arc::from(saved.as_slice())).expect("reopens");
    let font_dict = fetch_dict(&saved_doc, font.object());
    assert_eq!(
        font_dict.name(&Name::from("Type")).map(Name::as_bytes),
        Some(&b"Font"[..])
    );
    assert_eq!(
        font_dict.name(&Name::from("Subtype")).map(Name::as_bytes),
        Some(&b"Type0"[..])
    );
    assert_eq!(
        font_dict.name(&Name::from("Encoding")).map(Name::as_bytes),
        Some(&b"Identity-H"[..])
    );
    // The program's own PostScript name, degenerate as it is, is what
    // `/BaseFont` carries — not a placeholder.
    assert_eq!(
        font_dict.name(&Name::from("BaseFont")).map(Name::as_bytes),
        Some(&b"Test"[..])
    );

    let descendants = font_dict
        .array(&Name::from("DescendantFonts"), saved_doc.parser())
        .expect("DescendantFonts");
    assert_eq!(descendants.len(), 1);
    let cid_dict = fetch_dict(&saved_doc, descendants.reference_at(0).expect("cid ref"));
    assert_eq!(
        cid_dict.name(&Name::from("Subtype")).map(Name::as_bytes),
        Some(&b"CIDFontType2"[..])
    );

    // One run starting at CID 0, four glyphs wide. This is the array the
    // crashing build never got to write.
    let w = saved_doc
        .parser()
        .fetch(cid_dict.reference(&Name::from("W")).expect("W"))
        .expect("w")
        .as_array()
        .expect("array")
        .clone();
    assert_eq!(w.len(), 2, "one `c [w …]` run, got {w:?}");
    assert_eq!(w.int_at(0), Some(0), "the run starts at CID 0");
    let run = w.array_at(1, saved_doc.parser()).expect("run array");
    assert_eq!(
        run.iter()
            .filter_map(pdfrum_object::Object::as_int)
            .collect::<Vec<_>>(),
        vec![1000, 0, 1000, 1000]
    );

    // The descriptor still points at the whole program, unaltered.
    let desc = fetch_dict(
        &saved_doc,
        cid_dict
            .reference(&Name::from("FontDescriptor"))
            .expect("FontDescriptor"),
    );
    let file2 = saved_doc
        .parser()
        .fetch(desc.reference(&Name::from("FontFile2")).expect("FontFile2"))
        .expect("file2")
        .as_stream()
        .expect("stream")
        .clone();
    assert_eq!(
        file2.dict.direct_int(&Name::from("Length1")),
        Some(i64::try_from(BUG_2094.len()).expect("fits"))
    );

    match oracle_md5(&out) {
        Ok(stdout) => {
            assert!(
                stdout.contains("MD5:"),
                "the oracle reopens the file this program builds, got {stdout:?}"
            );
        }
        Err(msg) => {
            eprintln!("skipping oracle reopen: {msg}");
        }
    }
}

#[test]
fn embed_bug_377948405_widths_array_compaction() {
    // Ports FPDFEditEmbedderTest.Bug377948405.
    let doc = Document::from_bytes(Arc::from(HELLO_PDF)).expect("opens");
    let mut edit = doc.edit();
    let font = edit
        .embed_font(BUG_377948405, FontEncoding::Composite)
        .expect("embeds bug_377948405.ttf");
    let mut page = doc.page(0).expect("page").edit();
    page.push(
        TextBuilder {
            position: Point::new(20.0, 40.0),
            ..TextBuilder::new(font.encode("Test"), font.object(), 16.0)
        }
        .build(),
    );

    let dir = scratch_dir();
    let out = dir.join("bug_377948405.pdf");
    edit.save_pages(&out, &[page], &SaveOptions::default())
        .expect("saves");
    let saved = std::fs::read(&out).expect("reads");

    let saved_doc = Document::from_bytes(Arc::from(saved.as_slice())).expect("reopens");
    let font_dict = fetch_dict(&saved_doc, font.object());
    let descendants = font_dict
        .array(&Name::from("DescendantFonts"), saved_doc.parser())
        .expect("DescendantFonts");
    let cid_dict = fetch_dict(&saved_doc, descendants.reference_at(0).expect("cid ref"));
    let w_ref = cid_dict.reference(&Name::from("W")).expect("W");
    let w = saved_doc
        .parser()
        .fetch(w_ref)
        .expect("w")
        .as_array()
        .expect("array")
        .clone();

    // The C++ case checks only entries 0 and 2 (`EXPECT_EQ(…GetIntegerAt(0),
    // 1)` and `…GetIntegerAt(2), 5)`) but its comment names the whole array the
    // fix produces. `create_widths_array` produces exactly that, so the port
    // pins all seven entries rather than the two the C++ happened to sample:
    //
    //   [1 [639]  5 7 639  8 [881 556]]
    //    ^        ^        ^
    //    |        |        `- another `c [w …]` run, CIDs 8 and 9
    //    |        `- a `first last w` run: CIDs 5..=7 all 639, compacted
    //    `- a `c [w …]` run at CID 1
    //
    // That is the whole point of the bug: before the fix, the three equal
    // widths at CIDs 5..7 were emitted one per entry instead of as one run.
    assert_eq!(w.len(), 7, "three runs, seven entries, got {w:?}");
    assert_eq!(w.int_at(0), Some(1));
    assert_eq!(w.int_at(2), Some(5));
    assert_eq!(w.int_at(3), Some(7));
    assert_eq!(w.int_at(4), Some(639));
    assert_eq!(w.int_at(5), Some(8));
    let first_run = w.array_at(1, saved_doc.parser()).expect("run 1");
    assert_eq!(
        first_run
            .iter()
            .filter_map(pdfrum_object::Object::as_int)
            .collect::<Vec<_>>(),
        vec![639]
    );
    let last_run = w.array_at(6, saved_doc.parser()).expect("run 3");
    assert_eq!(
        last_run
            .iter()
            .filter_map(pdfrum_object::Object::as_int)
            .collect::<Vec<_>>(),
        vec![881, 556]
    );

    // The run-length form is strictly shorter than the naive one: five CIDs
    // (5..=9) would need ten entries as `c [w]` pairs, and take four here.
    assert_eq!(
        cid_dict.name(&Name::from("Subtype")).map(Name::as_bytes),
        Some(&b"CIDFontType2"[..])
    );

    match oracle_md5(&out) {
        Ok(stdout) => {
            assert!(stdout.contains("MD5:"));
        }
        Err(msg) => {
            eprintln!("skipping oracle reopen: {msg}");
        }
    }
}

#[test]
fn transform_text_placement_and_matrix_render() {
    // Ports FPDFEditEmbedderTest text transformation and matrix placement.
    let doc = Document::from_bytes(Arc::from(HELLO_PDF)).expect("opens");
    let original_dark = dark_pixels(&pixels(HELLO_PDF).2);

    let mut edit = doc.edit();
    let font = edit
        .embed_font(ROBOTO, FontEncoding::Composite)
        .expect("embeds");
    let mut page = doc.page(0).expect("page").edit();
    page.push(
        TextBuilder {
            position: Point::new(10.0, 10.0),
            ..TextBuilder::new(font.encode("Moved"), font.object(), 18.0)
        }
        .build(),
    );

    page.transform(0, Affine::translate((80.0, 60.0)))
        .expect("transforms");

    let dir = scratch_dir();
    let out = dir.join("transformed_text.pdf");
    edit.save_pages(&out, &[page], &SaveOptions::default())
        .expect("saves");
    let saved = std::fs::read(&out).expect("reads");

    let text = extracted(&saved);
    assert!(text.contains("Moved"));

    let (_, _, pix) = pixels(&saved);
    assert!(dark_pixels(&pix) > original_dark);

    match oracle_md5(&out) {
        Ok(stdout) => {
            assert!(stdout.contains("MD5:"));
        }
        Err(msg) => {
            eprintln!("skipping oracle reopen: {msg}");
        }
    }
}

#[test]
fn text_object_font_getters_retrieve_embedded_reference() {
    // Ports `FPDFTextObj_GetFont`: the font a text object was built with is
    // recoverable from the object, and it is the *same* font object the
    // resource dictionary ends up naming — a getter that returned a plausible
    // but unrelated reference would satisfy the in-memory check alone, so the
    // round-trip through the save is the load-bearing half.
    let doc = Document::from_bytes(Arc::from(HELLO_PDF)).expect("opens");
    let mut edit = doc.edit();
    let helvetica = edit
        .standard_font(StandardFont::Helvetica)
        .expect("Helvetica");
    let roboto = edit
        .embed_font(ROBOTO, FontEncoding::Composite)
        .expect("embeds Roboto");
    assert_ne!(helvetica.object(), roboto.object());

    let mut page = doc.page(0).expect("page").edit();
    let before = page.len();
    page.push(
        TextBuilder {
            position: Point::new(15.0, 25.0),
            ..TextBuilder::new(helvetica.encode("Getter test"), helvetica.object(), 14.0)
        }
        .build(),
    );
    page.push(
        TextBuilder {
            position: Point::new(15.0, 55.0),
            ..TextBuilder::new(roboto.encode("Second font"), roboto.object(), 14.0)
        }
        .build(),
    );

    // Two objects, two different fonts, each reported against its own index —
    // not one answer given twice.
    assert_eq!(page.font_of(before), Some(helvetica.object()));
    assert_eq!(page.font_of(before + 1), Some(roboto.object()));
    // The page's pre-existing objects are text too, but they were not added
    // by this session, so their fonts are not this session's references.
    for i in 0..before {
        assert_ne!(page.font_of(i), Some(helvetica.object()));
        assert_ne!(page.font_of(i), Some(roboto.object()));
    }
    assert_eq!(page.font_of(999), None, "an out-of-range index has no font");

    // Both references survive the save and resolve to the dictionaries the
    // getter named.
    let dir = scratch_dir();
    let out = dir.join("font_getters.pdf");
    edit.save_pages(&out, &[page], &SaveOptions::default())
        .expect("saves");
    let saved = std::fs::read(&out).expect("reads");
    let saved_doc = Document::from_bytes(Arc::from(saved.as_slice())).expect("reopens");
    assert_eq!(
        fetch_dict(&saved_doc, helvetica.object())
            .name(&Name::from("BaseFont"))
            .map(Name::as_bytes),
        Some(&b"Helvetica"[..])
    );
    assert_eq!(
        fetch_dict(&saved_doc, roboto.object())
            .name(&Name::from("BaseFont"))
            .map(Name::as_bytes),
        Some(&b"Roboto-Regular"[..])
    );

    let text = extracted(&saved);
    assert!(text.contains("Getter test"));
    assert!(text.contains("Second font"));
}

#[test]
fn save_and_render_round_trip_with_embedded_font() {
    // Ports FPDFEditEmbedderTest.SaveAndRender.
    let doc = Document::from_bytes(Arc::from(HELLO_PDF)).expect("opens");
    let (orig_w, orig_h, orig_pix) = pixels(HELLO_PDF);
    let orig_dark = dark_pixels(&orig_pix);

    let mut edit = doc.edit();
    let font = edit
        .embed_font(ROBOTO, FontEncoding::Composite)
        .expect("embeds");
    let mut page = doc.page(0).expect("page").edit();
    page.push(
        TextBuilder {
            position: Point::new(50.0, 50.0),
            ..TextBuilder::new(font.encode("RoundTrip"), font.object(), 20.0)
        }
        .build(),
    );

    let dir = scratch_dir();
    let out = dir.join("save_and_render.pdf");
    edit.save_pages(&out, &[page], &SaveOptions::default())
        .expect("saves");
    let saved = std::fs::read(&out).expect("reads");

    let (saved_w, saved_h, saved_pix) = pixels(&saved);
    assert_eq!((saved_w, saved_h), (orig_w, orig_h));
    assert!(dark_pixels(&saved_pix) > orig_dark);

    let text = extracted(&saved);
    assert!(text.contains("RoundTrip"));

    match oracle_md5(&out) {
        Ok(stdout) => {
            assert!(stdout.contains("MD5:"));
        }
        Err(msg) => {
            eprintln!("skipping oracle reopen: {msg}");
        }
    }
}

/// The `/FontFile` stream of `font`'s descriptor, with its three lengths.
///
/// `CheckFontDescriptor(font_dict, FPDF_FONT_TYPE1, …)` in the C++: a Type 1
/// program goes to `/FontFile` (ISO 32000-1 §9.9 Table 126) and never to
/// `/FontFile2` or `/FontFile3`, and it carries all three of the
/// clear/encrypted/trailer lengths Table 127 defines.
fn type1_font_file(doc: &Document, font: ObjRef) -> (pdfrum_object::Stream, i64, i64, i64) {
    let desc = fetch_dict(
        doc,
        fetch_dict(doc, font)
            .reference(&Name::from("FontDescriptor"))
            .expect("FontDescriptor"),
    );
    assert_eq!(
        desc.name(&Name::from("Type")).map(Name::as_bytes),
        Some(&b"FontDescriptor"[..])
    );
    assert!(desc.raw(&Name::from("FontFile2")).is_none());
    assert!(desc.raw(&Name::from("FontFile3")).is_none());
    let file = doc
        .parser()
        .fetch(desc.reference(&Name::from("FontFile")).expect("FontFile"))
        .expect("fontfile")
        .as_stream()
        .expect("stream")
        .clone();
    let get = |k: &str| {
        file.dict
            .direct_int(&Name::from(k))
            .unwrap_or_else(|| panic!("{k} is missing from /FontFile"))
    };
    let (l1, l2, l3) = (get("Length1"), get("Length2"), get("Length3"));
    (file, l1, l2, l3)
}

/// Ports `FPDFEditEmbedderTest.LoadSimpleType1Font`.
///
/// The C++ case loads `CPDF_Font::GetStockFont(doc, "Times-Bold")`'s span with
/// `FPDF_FONT_TYPE1` and asserts a `/Type1` dictionary with `/FirstChar 32`,
/// `/LastChar 255`, a 224-entry `/Widths` and a descriptor whose font file is
/// the program handed in. Under the hermetic test-fonts config that stock span
/// is in fact a TrueType substitute (`Tinos-Bold`), so the assertions there are
/// about the *simple-font shape*, not about a Type 1 program. Here the same
/// shape is asserted over a genuinely Type 1 program, which additionally
/// reaches `/FontFile` and its `/Length1` `/Length2` `/Length3` triple —
/// `embed.rs`'s Type 1 branch, which the C++ case never actually exercises.
#[test]
fn load_simple_type1_font() {
    let doc = Document::from_bytes(Arc::from(HELLO_PDF)).expect("opens");
    let original_dark = dark_pixels(&pixels(HELLO_PDF).2);

    let mut edit = doc.edit();
    let font = edit
        .embed_font(FOXIT_SERIF_MM, FontEncoding::Simple)
        .expect("embeds a Type 1 program");
    let mut page = doc.page(0).expect("page").edit();
    page.push(
        TextBuilder {
            position: Point::new(20.0, 40.0),
            ..TextBuilder::new(font.encode("Type 1 simple"), font.object(), 14.0)
        }
        .build(),
    );

    let dir = scratch_dir();
    let out = dir.join("load_simple_type1.pdf");
    edit.save_pages(&out, &[page], &SaveOptions::default())
        .expect("saves");
    let saved = std::fs::read(&out).expect("reads");

    let saved_doc = Document::from_bytes(Arc::from(saved.as_slice())).expect("reopens");
    let font_dict = fetch_dict(&saved_doc, font.object());
    assert_eq!(
        font_dict.name(&Name::from("Type")).map(Name::as_bytes),
        Some(&b"Font"[..])
    );
    assert_eq!(
        font_dict.name(&Name::from("Subtype")).map(Name::as_bytes),
        Some(&b"Type1"[..]),
        "a Type 1 program embeds as /Subtype /Type1, not /TrueType"
    );
    assert_eq!(
        font_dict.name(&Name::from("BaseFont")).map(Name::as_bytes),
        Some(&b"ChromeSerifMM"[..]),
        "/BaseFont is the program's own name, read out of its /FontName"
    );
    // The C++ case's `EXPECT_EQ(32, …FirstChar)` / `EXPECT_EQ(255, …LastChar)`.
    assert_eq!(font_dict.direct_int(&Name::from("FirstChar")), Some(32));
    assert_eq!(font_dict.direct_int(&Name::from("LastChar")), Some(255));

    let widths_ref = font_dict.reference(&Name::from("Widths")).expect("Widths");
    let widths = saved_doc
        .parser()
        .fetch(widths_ref)
        .expect("widths")
        .as_array()
        .expect("array")
        .clone();
    // `ASSERT_EQ(224u, widths_array->size())` — 255 - 32 + 1.
    assert_eq!(widths.len(), 224);
    let positive = widths
        .iter()
        .filter(|o| o.as_int().is_some_and(|w| w > 0))
        .count();
    assert!(
        positive > 100,
        "a Latin Type 1 face advances over 100 of the 224 codes, got {positive}"
    );

    let (_, l1, l2, l3) = type1_font_file(&saved_doc, font.object());
    // The three are the PFB's three segment payload lengths: clear text,
    // eexec-encrypted, and the 512-zeros-plus-`cleartomark` trailer — and the
    // stream holds exactly those payloads, the PFB framing having been
    // unwrapped. This is the divergence `embed.rs` documents against the
    // oracle, which writes `/FontFile` with none of the three
    // (`fpdf_edittext.cpp:166`, `TODO(npm): Lengths for Type1 fonts.`) and
    // stores the container verbatim.
    assert_eq!((l1, l2, l3), (10710, 102_155, 532));
    assert_eq!(
        l1 + l2 + l3 + 6 * 3 + 2,
        i64::try_from(FOXIT_SERIF_MM.len()).expect("fits"),
        "…and they account for the PFB minus its three 6-byte segment headers \
         and its two-byte `80 03` end marker"
    );

    let (_, _, pix) = pixels(&saved);
    assert!(
        dark_pixels(&pix) > original_dark,
        "the Type 1 program actually draws"
    );

    match oracle_md5(&out) {
        Ok(stdout) => {
            assert!(
                stdout.contains("MD5:"),
                "the oracle reopens a file whose font is a Type 1 program, got {stdout:?}"
            );
        }
        Err(msg) => {
            eprintln!("skipping oracle reopen: {msg}");
        }
    }
}

/// The ISO 32000-1 §9.9 Table 127 partition, on the container that used to
/// break it.
///
/// A PFB is not a Type 1 program: it is a chain of `[0x80, type, len:u32le]`
/// records wrapping one. Storing it verbatim in `/FontFile` — which the oracle
/// does (`fpdfsdk/fpdf_edittext.cpp:166-174`, `TODO(npm): Lengths for Type1
/// fonts.`) — leaves a conforming reader slicing `[0..Length1]` off six bytes
/// of segment header, and `[Length1..Length1+Length2]` straddling the next
/// one. `embed_program` therefore unwraps the container and stores the raw
/// program its records carry, so the three lengths measure what was written:
/// 10710 + 102155 + 532 = 113397 bytes, the 113417-byte file less its three
/// 6-byte headers and its two-byte `80 03` end marker.
#[test]
fn type1_font_file_lengths_partition_the_stream() {
    let doc = Document::from_bytes(Arc::from(HELLO_PDF)).expect("opens");
    let original_dark = dark_pixels(&pixels(HELLO_PDF).2);
    let mut edit = doc.edit();
    let font = edit
        .embed_font(FOXIT_SERIF_MM, FontEncoding::Simple)
        .expect("embeds a Type 1 program");
    let mut page = doc.page(0).expect("page").edit();
    page.push(
        TextBuilder {
            position: Point::new(20.0, 40.0),
            ..TextBuilder::new(font.encode("Lengths"), font.object(), 14.0)
        }
        .build(),
    );
    let dir = scratch_dir();
    let out = dir.join("type1_lengths.pdf");
    edit.save_pages(&out, &[page], &SaveOptions::default())
        .expect("saves");
    let saved = std::fs::read(&out).expect("reads");

    let saved_doc = Document::from_bytes(Arc::from(saved.as_slice())).expect("reopens");
    let (file, l1, l2, l3) = type1_font_file(&saved_doc, font.object());

    let program = pdfrum_filters::decode_chain(
        &file,
        0,
        saved_doc.parser(),
        &pdfrum_common::Limits::default(),
        &mut pdfrum_common::Diagnostics::default(),
    )
    .data;

    assert_eq!(
        i64::try_from(program.len()).expect("fits"),
        l1 + l2 + l3,
        "the three lengths must partition the decoded /FontFile"
    );
    assert_eq!(
        i64::try_from(FOXIT_SERIF_MM.len()).expect("fits"),
        l1 + l2 + l3 + 6 * 3 + 2,
        "…and what was dropped is exactly the PFB framing"
    );
    assert!(
        program.starts_with(b"%!"),
        "the stored program must open with the clear-text segment's PostScript \
         banner, not with a PFB segment header"
    );

    // Portion 1: clear text, ending at the `eexec` boundary.
    let clear = program
        .get(..usize::try_from(l1).expect("fits"))
        .expect("clear-text segment");
    let boundary = clear.len().saturating_sub(8);
    assert!(
        clear
            .get(boundary..)
            .is_some_and(|t| t.windows(5).any(|w| w == b"eexec")),
        "/Length1 must end at the eexec boundary, got {:?}",
        clear.get(boundary..)
    );

    // Portion 2: the encrypted private dictionary, starting right after it.
    let cipher_at = usize::try_from(l1).expect("fits");
    let cipher_end = cipher_at + usize::try_from(l2).expect("fits");
    let cipher = program.get(cipher_at..cipher_end).expect("eexec segment");
    assert_eq!(cipher.len(), 102_155);
    assert!(
        !cipher.is_ascii(),
        "the PFB's private portion is binary, not the hexadecimal a PFA writes"
    );

    // Portion 3: the fixed-content trailer — 512 zeros, then `cleartomark`.
    let trailer = program.get(cipher_end..).expect("trailer segment");
    assert_eq!(trailer.len(), usize::try_from(l3).expect("fits"));
    assert!(
        trailer.starts_with(&[b'0'; 64]),
        "/Length3 must start at the 512-zeros block"
    );
    assert!(
        trailer
            .get(..512)
            .is_some_and(|z| z.iter().all(|b| *b == b'0' || b.is_ascii_whitespace())),
        "the fixed-content portion opens with the 512-zero block"
    );
    assert!(
        trailer.windows(11).any(|w| w == b"cleartomark"),
        "the fixed-content portion ends with `cleartomark`"
    );

    // Round trip: what we wrote is a Type 1 program our own reader accepts,
    // and the glyphs draw.
    let (_, _, pix) = pixels(&saved);
    assert!(
        dark_pixels(&pix) > original_dark,
        "the unwrapped Type 1 program still draws"
    );

    match oracle_md5(&out) {
        Ok(stdout) => {
            assert!(
                stdout.contains("MD5:"),
                "the oracle reopens a file whose /FontFile is a raw Type 1 \
                 program, got {stdout:?}"
            );
        }
        Err(msg) => {
            eprintln!("skipping oracle reopen: {msg}");
        }
    }
}

/// Ports `FPDFEditEmbedderTest.LoadCIDType0Font`.
///
/// Same program, `FontEncoding::Composite`. The C++ case pins the `/Type0`
/// wrapper naming `Identity-H`, one descendant, `/CIDFontType0` (not `Type2`,
/// because the program is not TrueType), the `Adobe`/`Identity`/`0`
/// `/CIDSystemInfo`, and a non-trivial `/W`.
#[test]
fn load_cid_type0_font() {
    let doc = Document::from_bytes(Arc::from(HELLO_PDF)).expect("opens");
    let original_dark = dark_pixels(&pixels(HELLO_PDF).2);

    let mut edit = doc.edit();
    let font = edit
        .embed_font(FOXIT_SERIF_MM, FontEncoding::Composite)
        .expect("embeds a Type 1 program as a CID font");
    let mut page = doc.page(0).expect("page").edit();
    page.push(
        TextBuilder {
            position: Point::new(20.0, 60.0),
            ..TextBuilder::new(font.encode("Type 1 CID"), font.object(), 14.0)
        }
        .build(),
    );

    let dir = scratch_dir();
    let out = dir.join("load_cid_type0.pdf");
    edit.save_pages(&out, &[page], &SaveOptions::default())
        .expect("saves");
    let saved = std::fs::read(&out).expect("reads");

    let saved_doc = Document::from_bytes(Arc::from(saved.as_slice())).expect("reopens");
    let font_dict = fetch_dict(&saved_doc, font.object());
    assert_eq!(
        font_dict.name(&Name::from("Subtype")).map(Name::as_bytes),
        Some(&b"Type0"[..])
    );
    assert_eq!(
        font_dict.name(&Name::from("Encoding")).map(Name::as_bytes),
        Some(&b"Identity-H"[..])
    );
    // The C++'s `"Tinos-Regular-Identity-H"`: the root's `/BaseFont` is the
    // descendant's name with the encoding appended.
    assert_eq!(
        font_dict.name(&Name::from("BaseFont")).map(Name::as_bytes),
        Some(&b"ChromeSerifMM-Identity-H"[..])
    );

    let descendants = font_dict
        .array(&Name::from("DescendantFonts"), saved_doc.parser())
        .expect("DescendantFonts");
    assert_eq!(descendants.len(), 1);
    let cid_dict = fetch_dict(&saved_doc, descendants.reference_at(0).expect("cid ref"));
    assert_eq!(
        cid_dict.name(&Name::from("Subtype")).map(Name::as_bytes),
        Some(&b"CIDFontType0"[..]),
        "a Type 1 descendant is CIDFontType0; only a TrueType one is CIDFontType2"
    );
    assert_eq!(
        cid_dict.name(&Name::from("BaseFont")).map(Name::as_bytes),
        Some(&b"ChromeSerifMM"[..])
    );

    let cid_info = cid_dict
        .dict(&Name::from("CIDSystemInfo"), saved_doc.parser())
        .expect("CIDSystemInfo");
    assert_eq!(
        cid_info.byte_string(&Name::from("Registry"), saved_doc.parser()),
        Some(b"Adobe".to_vec())
    );
    assert_eq!(
        cid_info.byte_string(&Name::from("Ordering"), saved_doc.parser()),
        Some(b"Identity".to_vec())
    );
    assert_eq!(cid_info.direct_int(&Name::from("Supplement")), Some(0));

    // `EXPECT_GT(widths_array->size(), 1u)` plus `CheckCompositeFontWidths`.
    let w_ref = cid_dict.reference(&Name::from("W")).expect("W");
    let w = saved_doc
        .parser()
        .fetch(w_ref)
        .expect("w")
        .as_array()
        .expect("array")
        .clone();
    assert!(w.len() > 1, "/W should carry real runs, got {}", w.len());

    // The descendant, not the root, owns the descriptor, and it is /FontFile.
    let desc_ref = cid_dict
        .reference(&Name::from("FontDescriptor"))
        .expect("FontDescriptor");
    let desc = fetch_dict(&saved_doc, desc_ref);
    assert!(desc.reference(&Name::from("FontFile")).is_some());
    assert!(desc.raw(&Name::from("FontFile2")).is_none());
    assert!(font_dict.raw(&Name::from("FontDescriptor")).is_none());

    let (_, _, pix) = pixels(&saved);
    assert!(
        dark_pixels(&pix) > original_dark,
        "the composite Type 1 font actually draws"
    );

    match oracle_md5(&out) {
        Ok(stdout) => {
            assert!(stdout.contains("MD5:"));
        }
        Err(msg) => {
            eprintln!("skipping oracle reopen: {msg}");
        }
    }
}

/// The half of `FPDFEditEmbedderTest.LoadCidType2FontWithBadParameters` that
/// is about the *font program*, which is the only parameter `embed_font`
/// takes. The C++ case additionally rejects a null document, a null or empty
/// `to_unicode_cmap` and a null or empty `cid_to_gid_map`; those three have no
/// counterpart here — see `load_cid_type2_font_custom` for why.
#[test]
fn embed_font_rejects_a_program_it_cannot_read() {
    let doc = Document::from_bytes(Arc::from(HELLO_PDF)).expect("opens");
    let mut edit = doc.edit();

    // `FPDFText_LoadCidType2Font(document(), nullptr, …)` and its `size 0`
    // sibling: no bytes is not a font.
    for encoding in [FontEncoding::Simple, FontEncoding::Composite] {
        let err = edit
            .embed_font(&[], encoding)
            .expect_err("an empty program is not a font");
        assert!(
            matches!(err, pdfrum::Error::Save(_)),
            "an unreadable program surfaces as Error::Save, got {err:?}"
        );
        // The C++'s `dummy_vec(3)` — three zero bytes, which is neither a
        // sfnt tag nor a PFB marker nor a `%!PS` banner.
        let err = edit
            .embed_font(&[0, 0, 0], encoding)
            .expect_err("three zero bytes are not a font");
        assert!(matches!(err, pdfrum::Error::Save(_)), "got {err:?}");
        // Text that is not a font program either.
        let err = edit
            .embed_font(b"dummy", encoding)
            .expect_err("ASCII text is not a font");
        assert!(matches!(err, pdfrum::Error::Save(_)), "got {err:?}");
    }

    // A rejected program leaves the session usable: the next call still works,
    // which is the point of returning an error rather than poisoning the edit.
    let good = edit
        .embed_font(ROBOTO, FontEncoding::Simple)
        .expect("the editor survives a rejected program");
    assert_eq!(good.encode("Hi"), b"Hi".to_vec());
}

/// The `/ToUnicode` CMap `FPDFEditEmbedderTest.LoadCidType2FontCustom` passes,
/// verbatim (`fpdfsdk/fpdf_edit_embeddertest.cpp:4004-4029`).
///
/// Five `bfrange` blocks, deliberately overlapping at their endpoints — CID 3
/// appears in two of them, CID 4 in two, CID 5 in two — which is what makes it
/// a test of the collision policy and not only of the parse.
const CUSTOM_TO_UNICODE: &str = "\
/CIDInit /ProcSet findresource begin
12 dict begin
begincmap
/CIDSystemInfo <<
  /Registry (Adobe)
  /Ordering (Identity)
  /Supplement 0
>> def
/CMapName /Adobe-Identity-H def
/CMapType 2 def
1 begincodespacerange
<0000> <FFFF>
endcodespacerange
5 beginbfrange
<0001> <0003> [<0020> <3002> <2F00>]
<0003> <0004> [<4E00> <2F06>]
<0004> <0005> [<4E8C> <53E5>]
<0005> <0008> [<F906> <662F> <7B2C> <884C>]
<0008> <0009> [<FA08> <8FD9>]
endbfrange
endcmap
CMapName currentdict /CMap defineresource pop
end
end
";

/// `kCidToGidMap` from the same case: ten big-endian `u16` entries, CID `i`
/// to GID `i`.
const CUSTOM_CID_TO_GID: &[u8] = &[0, 0, 0, 1, 0, 2, 0, 3, 0, 4, 0, 5, 0, 6, 0, 7, 0, 8, 0, 9];

/// The stream behind `key` on `font`'s descendant CID font dictionary.
fn descendant_stream(doc: &Document, font: ObjRef, key: &str) -> Vec<u8> {
    let font_dict = fetch_dict(doc, font);
    let descendants = font_dict
        .array(&Name::from("DescendantFonts"), doc.parser())
        .expect("DescendantFonts");
    let cid_dict = fetch_dict(doc, descendants.reference_at(0).expect("cid ref"));
    let reference = cid_dict.reference(&Name::from(key)).expect("stream ref");
    let stream = doc
        .parser()
        .fetch(reference)
        .expect("fetches")
        .as_stream()
        .expect("stream")
        .clone();
    pdfrum_filters::decode_chain(
        &stream,
        0,
        doc.parser(),
        &pdfrum_common::Limits::default(),
        &mut pdfrum_common::Diagnostics::default(),
    )
    .data
}

/// The stream behind `key` on the `/Type0` root itself.
fn root_stream(doc: &Document, font: ObjRef, key: &str) -> Vec<u8> {
    let font_dict = fetch_dict(doc, font);
    let reference = font_dict.reference(&Name::from(key)).expect("stream ref");
    let stream = doc
        .parser()
        .fetch(reference)
        .expect("fetches")
        .as_stream()
        .expect("stream")
        .clone();
    pdfrum_filters::decode_chain(
        &stream,
        0,
        doc.parser(),
        &pdfrum_common::Limits::default(),
        &mut pdfrum_common::Diagnostics::default(),
    )
    .data
}

/// A closure over `program`'s advances, so a test can state the width it
/// expects at a GID without reimplementing the metric lookup.
fn program_advances(program: &[u8]) -> impl Fn(u16) -> i32 + use<> {
    let glyphs = pdfrum_font::GlyphSource::from_bytes(program).expect("a font program");
    move |gid| glyphs.default_advance(pdfrum_font::Gid(gid))
}

/// `CheckCompositeFontWidths` (`fpdfsdk/fpdf_edit_embeddertest.cpp:219-259`)
/// over the `/W` of `font`'s descendant: walk the two ISO 32000-1 §9.7.4.3
/// forms, check every width against the advance of the GID
/// [`CUSTOM_CID_TO_GID`] sends that CID to, and return how many CIDs the array
/// accounts for.
fn cid_widths_covered(doc: &Document, font: ObjRef) -> usize {
    let font_dict = fetch_dict(doc, font);
    let descendants = font_dict
        .array(&Name::from("DescendantFonts"), doc.parser())
        .expect("DescendantFonts");
    let cid_dict = fetch_dict(doc, descendants.reference_at(0).expect("cid ref"));
    let w_ref = cid_dict.reference(&Name::from("W")).expect("W");
    let w = doc
        .parser()
        .fetch(w_ref)
        .expect("w")
        .as_array()
        .expect("array")
        .clone();
    assert!(w.len() > 1, "/W should carry real runs, got {}", w.len());
    let advance = program_advances(NOTO_SANS_SC);
    widths_covered(&w, &|cid| {
        let at = usize::try_from(cid).expect("fits") * 2;
        let gid = u16::from_be_bytes([
            CUSTOM_CID_TO_GID.get(at).copied().unwrap_or(0),
            CUSTOM_CID_TO_GID.get(at + 1).copied().unwrap_or(0),
        ]);
        i64::from(advance(gid))
    })
}

/// Walk the two `/W` forms, checking each width against `expected` and
/// returning the CID count.
fn widths_covered(w: &pdfrum_object::Array, expected: &dyn Fn(u32) -> i64) -> usize {
    let mut covered = 0usize;
    let mut idx = 0usize;
    while idx < w.len() {
        let cid = w.int_at(idx).expect("a /W entry opens with a CID");
        idx += 1;
        let next = w.raw_at(idx).expect("a /W entry is never a lone CID");
        if let Some(inner) = next.as_array() {
            for (offset, item) in inner.iter().enumerate() {
                let cid = cid + i64::try_from(offset).expect("fits");
                let width = item.as_int().expect("a width is a number");
                assert_eq!(
                    width,
                    expected(u32::try_from(cid).expect("fits")),
                    "width at CID {cid}"
                );
            }
            covered += inner.len();
            idx += 1;
            continue;
        }
        let last = next.as_int().expect("c_first c_last w");
        idx += 1;
        let width = w.int_at(idx).expect("c_first c_last w");
        idx += 1;
        for cid in cid..=last {
            assert_eq!(
                width,
                expected(u32::try_from(cid).expect("fits")),
                "width at CID {cid}"
            );
        }
        covered += usize::try_from(last - cid + 1).expect("fits");
    }
    covered
}

/// Ports `FPDFEditEmbedderTest.LoadCidType2FontCustom` and
/// `FPDFEditEmbedderTest.LoadCidType2FontCustomGeneratedWidths`.
///
/// The two C++ cases differ only in the length of the maps they pass — 20
/// bytes and 10, so `CheckCompositeFontWidths` expects 10 CIDs and 5 — which
/// is the whole assertion: `/W` is computed **per CID from the caller's
/// `/CIDToGIDMap`**, not per GID from the program's cmap, so its coverage is
/// the map's entry count and nothing else. They are merged here because the
/// second is the first with one input shortened.
///
/// The two blobs must also arrive in the file byte for byte: the caller wrote
/// them, and a writer that regenerated either would have thrown away the
/// caller's statement of what the file's codes mean.
#[test]
fn load_cid_type2_font_custom() {
    let doc = Document::from_bytes(Arc::from(HELLO_PDF)).expect("opens");
    let original_dark = dark_pixels(&pixels(HELLO_PDF).2);

    let mut edit = doc.edit();
    let font = edit
        .embed_cid_font(NOTO_SANS_SC, CUSTOM_TO_UNICODE, CUSTOM_CID_TO_GID)
        .expect("embeds with a caller-supplied CMap and CIDToGIDMap");

    // `FPDFText_SetText` on such a font goes through
    // `CPDF_Font::CharCodeFromUnicode`, which is a reverse lookup through the
    // *caller's* `/ToUnicode` (`core/fpdfapi/font/cpdf_font.cpp:110-115`).
    // U+3002 is CID 2 and U+4E00 is CID 3 in the CMap above.
    let codes = font.encode("\u{3002}\u{4e00}");
    assert_eq!(codes, vec![0, 2, 0, 3], "encode inverts the caller's CMap");
    // A character the CMap does not reach is `.notdef`, as everywhere else.
    assert_eq!(font.encode("Z"), vec![0, 0]);

    let mut page = doc.page(0).expect("page").edit();
    page.push(
        TextBuilder {
            position: Point::new(20.0, 120.0),
            ..TextBuilder::new(codes, font.object(), 24.0)
        }
        .build(),
    );

    let dir = scratch_dir();
    let out = dir.join("cid_type2_custom.pdf");
    edit.save_pages(&out, &[page], &SaveOptions::default())
        .expect("saves");
    let saved = std::fs::read(&out).expect("reads");
    let saved_doc = Document::from_bytes(Arc::from(saved.as_slice())).expect("reopens");

    // The chain `LoadCustomCompositeFont` builds: /Type0 Identity-H over one
    // /CIDFontType2 descendant. `/CIDFontType2` and not `/CIDFontType0`
    // even though the program is CFF, because a /CIDFontType0 reaches glyphs
    // with the CID as the glyph index and never consults /CIDToGIDMap
    // (`core/fpdfapi/font/cpdf_cidfont.cpp:508-518`), which would make the
    // caller's map dead weight.
    let font_dict = fetch_dict(&saved_doc, font.object());
    assert_eq!(
        font_dict.name(&Name::from("Subtype")).map(Name::as_bytes),
        Some(&b"Type0"[..])
    );
    assert_eq!(
        font_dict.name(&Name::from("Encoding")).map(Name::as_bytes),
        Some(&b"Identity-H"[..])
    );
    let descendants = font_dict
        .array(&Name::from("DescendantFonts"), saved_doc.parser())
        .expect("DescendantFonts");
    assert_eq!(descendants.len(), 1);
    let cid_dict = fetch_dict(&saved_doc, descendants.reference_at(0).expect("cid ref"));
    assert_eq!(
        cid_dict.name(&Name::from("Subtype")).map(Name::as_bytes),
        Some(&b"CIDFontType2"[..])
    );

    // Both blobs, byte for byte.
    assert_eq!(
        descendant_stream(&saved_doc, font.object(), "CIDToGIDMap"),
        CUSTOM_CID_TO_GID,
        "/CIDToGIDMap must be the caller's bytes, verbatim"
    );
    assert_eq!(
        root_stream(&saved_doc, font.object(), "ToUnicode"),
        CUSTOM_TO_UNICODE.as_bytes(),
        "/ToUnicode must be the caller's CMap text, verbatim"
    );

    // `CheckCompositeFontWidths(widths_array, typed_font, Eq(10))`: ten
    // entries in, ten CIDs covered, each width the advance of the GID the
    // caller's map sends that CID to.
    assert_eq!(
        cid_widths_covered(&saved_doc, font.object()),
        10,
        "/W covers exactly the map's ten CIDs"
    );

    // Text extracts back through the caller's CMap, which is the only reason
    // the two blobs are worth carrying.
    // The CMap's five ranges overlap at their endpoints, so CID 3 is named
    // twice — U+2F00 by the first block and U+4E00 by the second. The
    // lowest-value-wins collision policy (`InsertIntoMaps`,
    // the former working note) keeps U+2F00 forward, while the
    // *reverse* map keeps CID 3 for U+4E00, which is why `encode` above wrote
    // CID 3 for it and extraction reads U+2F00 back. That asymmetry is the
    // oracle's, and it is the caller's CMap that produces it.
    let text = extracted(&saved);
    assert!(
        text.contains('\u{3002}') && text.contains('\u{2f00}'),
        "text extracts through the caller's /ToUnicode, got {text:?}"
    );

    let (_, _, pix) = pixels(&saved);
    assert!(
        dark_pixels(&pix) > original_dark,
        "the custom composite font actually draws"
    );

    match oracle_md5(&out) {
        Ok(stdout) => {
            assert!(stdout.contains("MD5:"));
        }
        Err(msg) => {
            eprintln!("skipping oracle reopen: {msg}");
        }
    }
}

/// Ports `FPDFEditEmbedderTest.LoadCidType2FontCustomGeneratedWidths`.
///
/// The same font and the same CMap as `load_cid_type2_font_custom`, with the
/// `/CIDToGIDMap` cut in half. `/W` must shrink with it — five entries in,
/// five CIDs covered — which is the assertion that `/W` is walked out of the
/// caller's map and not out of the program.
#[test]
fn load_cid_type2_font_custom_generated_widths() {
    let doc = Document::from_bytes(Arc::from(HELLO_PDF)).expect("opens");
    let mut edit = doc.edit();
    let font = edit
        .embed_cid_font(
            NOTO_SANS_SC,
            CUSTOM_TO_UNICODE,
            CUSTOM_CID_TO_GID.get(..10).expect("ten bytes"),
        )
        .expect("embeds");

    let out = scratch_dir().join("cid_type2_custom_short.pdf");
    edit.save(&out, &SaveOptions::default()).expect("saves");
    let saved = std::fs::read(&out).expect("reads");
    let saved_doc = Document::from_bytes(Arc::from(saved.as_slice())).expect("reopens");

    assert_eq!(
        cid_widths_covered(&saved_doc, font.object()),
        5,
        "a five-entry map yields five CIDs of /W"
    );
}

/// Ports the four `FPDFEditEmbedderTest.LoadCidType2FontWithBadParameters`
/// cases `embed_cid_font` can express: an empty `to_unicode_cmap`, and a
/// `cid_to_gid_map` that is empty or not a whole number of entries.
///
/// The C++'s null-pointer arms have no counterpart — a `&str` and a `&[u8]`
/// cannot be null. Its `size 0` arms are the empty ones here.
///
/// [oracle-bug] The **odd-length** map the C++ does not check at all.
/// `LoadCustomCompositeFont` walks `i += 2` to `cid_to_gid_map_span.size()`
/// and takes `cid_to_gid_map_span.subspan(i).first<2u>()`
/// (`fpdfsdk/fpdf_edittext.cpp:308-313`), so a trailing one-byte remainder
/// asks a 1-element span for its first 2 — a bounds `CHECK` in
/// `pdfium::span`, i.e. an abort rather than a rejection. ISO 32000-1 §9.7.4.2
/// defines `/CIDToGIDMap` as a stream of two-byte glyph indices, so a
/// half-entry is not a map; an error says so without the crash. pdf.js is the
/// reader that depends on it: `readCidToGidMap` pairs the bytes as
/// `(glyphsData[j++] << 8) | glyphsData[j]` over the map's whole length
/// (`src/core/evaluator.js:4103-4116`), so a trailing half-entry reads
/// `undefined` as its low byte and `x | undefined` is `x << 8` — a glyph index
/// 256 times too large, silently, for the last CID.
#[test]
fn embed_cid_font_rejects_bad_maps() {
    let doc = Document::from_bytes(Arc::from(HELLO_PDF)).expect("opens");
    let mut edit = doc.edit();

    let err = edit
        .embed_cid_font(NOTO_SANS_SC, "", CUSTOM_CID_TO_GID)
        .expect_err("an empty CMap is not a /ToUnicode");
    assert!(matches!(err, pdfrum::Error::Save(_)), "got {err:?}");

    let err = edit
        .embed_cid_font(NOTO_SANS_SC, CUSTOM_TO_UNICODE, &[])
        .expect_err("an empty map is not a /CIDToGIDMap");
    assert!(matches!(err, pdfrum::Error::Save(_)), "got {err:?}");

    let err = edit
        .embed_cid_font(NOTO_SANS_SC, CUSTOM_TO_UNICODE, &[0, 0, 0])
        .expect_err("three bytes are one and a half entries");
    assert!(matches!(err, pdfrum::Error::Save(_)), "got {err:?}");

    // The font program is validated the same way `embed_font` validates it.
    for program in [&b""[..], &[0, 0, 0][..], b"dummy"] {
        let err = edit
            .embed_cid_font(program, CUSTOM_TO_UNICODE, CUSTOM_CID_TO_GID)
            .expect_err("not a font program");
        assert!(matches!(err, pdfrum::Error::Save(_)), "got {err:?}");
    }

    // A rejected call leaves the session usable.
    let good = edit
        .embed_cid_font(NOTO_SANS_SC, CUSTOM_TO_UNICODE, CUSTOM_CID_TO_GID)
        .expect("the editor survives four rejections");
    assert_eq!(good.encode("\u{3002}"), vec![0, 2]);
}