pdfboss-cli 2.3.0

PDF command line: PDF to text, Markdown and PNG, image extraction, PDF creation, and the json/hex/q/tui explorer
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
//! The `pdfboss` command-line tool: document info, text extraction, page
//! rendering and object inspection.

mod assemble;
mod create;
mod hexdump;
mod input;
mod json;
mod manifest;
mod meta;
mod pages;
mod progress;
mod q;
mod skill;

use pdfboss_core::pretty;

use std::fmt::Write as _;
use std::path::{Path, PathBuf};

use clap::{Parser, Subcommand};
use pdfboss_core::{Document, Error, Metadata, ObjRef, Object};
use pdfboss_output::Output as _;

use crate::input::is_url;

/// A fatal CLI failure: message for stderr plus the process exit code.
/// PDF/IO problems exit 1; invalid jq programs exit 2 (mirroring clap's own
/// usage-error code and keeping the two failure kinds distinguishable).
pub struct Failure {
    pub message: String,
    pub code: i32,
}

impl Failure {
    /// A PDF/IO failure (exit code 1).
    pub fn new(message: impl Into<String>) -> Failure {
        Failure {
            message: message.into(),
            code: 1,
        }
    }

    /// An invalid-program failure (exit code 2).
    pub fn program(message: impl Into<String>) -> Failure {
        Failure {
            message: message.into(),
            code: 2,
        }
    }
}

impl From<String> for Failure {
    fn from(message: String) -> Failure {
        Failure::new(message)
    }
}

#[derive(Parser)]
#[command(
    name = "pdfboss",
    version,
    about = "PDF parsing, text extraction and rendering"
)]
struct Cli {
    #[command(subcommand)]
    command: Command,
}

#[derive(Subcommand)]
enum Command {
    /// Create a new PDF: blank pages, word-wrapped text, image pages, or a
    /// themed Markdown document.
    Create {
        #[command(subcommand)]
        command: create::CreateCommand,
    },
    /// Set document metadata by appending an update (original bytes preserved).
    Meta {
        /// Input PDF.
        file: PathBuf,
        /// Output PDF path.
        #[arg(short, long)]
        out: PathBuf,
        /// Metadata assignment, repeatable: title, author, subject, keywords, creator, producer.
        #[arg(long = "set", value_name = "KEY=VALUE", required = true)]
        set: Vec<String>,
        /// Full rewrite instead of an incremental append.
        #[arg(long)]
        rewrite: bool,
        /// Password for encrypted PDFs.
        #[arg(long, default_value = "")]
        password: String,
    },
    /// Combine selected pages from several inputs into one fresh document.
    Merge {
        /// Inputs, each optionally FILE:RANGE (1-based, e.g. report.pdf:2-9).
        #[arg(required = true)]
        inputs: Vec<String>,
        /// Output PDF file.
        #[arg(short, long)]
        out: PathBuf,
        /// One password tried for every encrypted input.
        #[arg(long, default_value = "")]
        password: String,
    },
    /// Cut a document into consecutive chunks of pages.
    Split {
        /// Path to the PDF file.
        file: PathBuf,
        /// Output pattern containing %d (1-based part number).
        #[arg(short, long)]
        out: String,
        /// Pages per part.
        #[arg(long, value_parser = parse_every)]
        every: usize,
        /// Password for an encrypted file (user or owner password).
        #[arg(long, default_value = "")]
        password: String,
    },
    /// Rotate selected pages by a quarter-turn multiple, clockwise.
    Rotate {
        /// Path to the PDF file.
        file: PathBuf,
        /// Output PDF file.
        #[arg(short, long)]
        out: PathBuf,
        /// 1-based pages, e.g. 2,4-9; every page when omitted.
        #[arg(long)]
        pages: Option<String>,
        /// Quarter turns clockwise: 90, 180 or 270.
        #[arg(long, value_parser = ["90", "180", "270"])]
        by: String,
        /// Full rewrite instead of an incremental append.
        #[arg(long)]
        rewrite: bool,
        /// Password for an encrypted file (user or owner password).
        #[arg(long, default_value = "")]
        password: String,
    },
    /// Draw the first page of another PDF onto every page.
    Overlay {
        /// Path to the PDF file.
        file: PathBuf,
        /// PDF whose first page is drawn onto every page.
        overlay: PathBuf,
        /// Output PDF file.
        #[arg(short, long)]
        out: PathBuf,
        /// Draw beneath the page content instead of on top of it.
        #[arg(long)]
        under: bool,
        /// Full rewrite instead of an incremental append.
        #[arg(long)]
        rewrite: bool,
        /// Password for an encrypted file (user or owner password).
        #[arg(long, default_value = "")]
        password: String,
    },
    /// Rewrite a document fresh: recompressed, unreachable objects and
    /// earlier update sections left behind.
    Rewrite {
        /// Path to the PDF file.
        file: PathBuf,
        /// Output PDF file.
        #[arg(short, long)]
        out: PathBuf,
        /// Password for an encrypted file (user or owner password).
        #[arg(long, default_value = "")]
        password: String,
    },
    /// Encrypt a document with AES-256 (a fresh file is always written).
    Encrypt {
        /// Path to the PDF file.
        file: PathBuf,
        /// Output PDF file.
        #[arg(short, long)]
        out: PathBuf,
        /// Password readers must supply to open the file.
        #[arg(long, default_value = "")]
        user_password: String,
        /// Owner password; defaults to the user password when omitted.
        #[arg(long, default_value = "")]
        owner_password: String,
        /// Permissions granted to readers, comma-separated; all when omitted.
        /// Values: print, modify, copy, annotate, fill-forms, accessibility, assemble, print-hires.
        #[arg(long, value_delimiter = ',')]
        allow: Option<Vec<String>>,
        /// Password for reading an input that is itself encrypted.
        #[arg(long, default_value = "")]
        password: String,
    },
    /// Remove encryption (opens with the password, writes a fresh plain file).
    Decrypt {
        /// Path to the PDF file.
        file: PathBuf,
        /// Output PDF file.
        #[arg(short, long)]
        out: PathBuf,
        /// Password for the encrypted file (user or owner password).
        #[arg(long, default_value = "")]
        password: String,
    },
    /// Show version, page count, page sizes and metadata.
    Info {
        /// Path to the PDF file.
        file: PathBuf,
        /// Password for an encrypted file (user or owner password).
        #[arg(long, default_value = "")]
        password: String,
    },
    /// Extract text (all pages separated by form feed unless --page is given).
    Text {
        /// Path to the PDF file.
        file: PathBuf,
        /// Password for an encrypted file (user or owner password).
        #[arg(long, default_value = "")]
        password: String,
        /// 1-based page number.
        #[arg(long)]
        page: Option<usize>,
        /// The order lines are read in.
        #[arg(long, value_enum, default_value_t = ReadingOrderArg::Content)]
        reading_order: ReadingOrderArg,
    },
    /// Extract markdown (headings, lists, tables inferred from layout).
    Md {
        /// Path to the PDF file.
        file: PathBuf,
        /// Password for an encrypted file (user or owner password).
        #[arg(long, default_value = "")]
        password: String,
        /// 1-based page number (heading sizes are then judged per page,
        /// not across the document).
        #[arg(long)]
        page: Option<usize>,
        /// The order lines are read in.
        #[arg(long, value_enum, default_value_t = ReadingOrderArg::Content)]
        reading_order: ReadingOrderArg,
    },
    /// Render a page to PNG, PPM, BMP or JPEG.
    Render {
        /// Path to the PDF file.
        file: PathBuf,
        /// Password for an encrypted file (user or owner password).
        #[arg(long, default_value = "")]
        password: String,
        /// 1-based page number.
        #[arg(long)]
        page: usize,
        /// Output file; its extension picks the format, .png, .ppm, .bmp or
        /// .jpg (default: page-N.png).
        #[arg(short, long)]
        out: Option<PathBuf>,
        /// Scale factor.
        #[arg(long, default_value_t = 1.0)]
        scale: f32,
        /// Which fonts to paint: embedded-only, all-embedded, or full.
        /// Defaults to full when substitute faces are available (the
        /// compiled-in OFL set or --font-dir), otherwise all-embedded.
        #[arg(long, value_enum)]
        fonts: Option<FontsArg>,
        /// Directory of substitute faces for `--fonts full`: one file per
        /// face, named like `Arimo[wght].ttf` (the book's rendering chapter
        /// lists all of them), e.g. an installed `pdfboss-fonts` package.
        /// Overrides the compiled-in OFL set.
        #[arg(long)]
        font_dir: Option<PathBuf>,
        /// PNG compression: encode time against file size, same pixels
        /// (.ppm and .bmp are never compressed).
        #[arg(long, value_enum, default_value_t = PngCompressionArg::Default)]
        png_compression: PngCompressionArg,
        /// JPEG quality, 1 to 100 (.jpg and .jpeg only).
        #[arg(long, default_value_t = 90, value_parser = clap::value_parser!(u8).range(1..=100))]
        jpeg_quality: u8,
    },
    /// Extract every image a page draws, each as a native-size PNG.
    Images {
        /// Path to the PDF file.
        file: PathBuf,
        /// Password for an encrypted file (user or owner password).
        #[arg(long, default_value = "")]
        password: String,
        /// 1-based page number (default: all pages).
        #[arg(long)]
        page: Option<usize>,
        /// Output directory (default: current directory).
        #[arg(short, long)]
        out: Option<PathBuf>,
        /// PNG compression: encode time against file size, same pixels.
        #[arg(long, value_enum, default_value_t = PngCompressionArg::Default)]
        png_compression: PngCompressionArg,
    },
    /// Pretty-print a single object.
    Obj {
        /// Path to the PDF file.
        file: PathBuf,
        /// Password for an encrypted file (user or owner password).
        #[arg(long, default_value = "")]
        password: String,
        /// Object number.
        num: u32,
        /// Generation number (default 0).
        gen: Option<u16>,
    },
    /// Explore a PDF interactively in the terminal.
    Tui {
        /// Path or http(s) URL of the PDF.
        target: String,
        /// Password for an encrypted file (user or owner password).
        #[arg(long, default_value = "")]
        password: String,
    },
    /// Dump the document as a JSON value tree (for piping to external tools).
    Json {
        /// Path or http(s) URL of the PDF.
        input: String,
        /// Password for an encrypted file (user or owner password).
        #[arg(long, default_value = "")]
        password: String,
        /// Embed raw (still encoded) stream data as base64.
        #[arg(long, conflicts_with = "decode")]
        raw: bool,
        /// Embed decoded stream data as base64.
        #[arg(long)]
        decode: bool,
        /// Restrict logical elements to these 1-based pages (comma separated).
        #[arg(long, value_delimiter = ',')]
        pages: Option<Vec<usize>>,
        /// Skip the logical layer (pages/fonts/images/annotations).
        #[arg(long)]
        no_logical: bool,
        /// Include per-page content-stream operators (high volume).
        #[arg(long)]
        content_ops: bool,
        /// Include per-page layout blocks (headings, paragraphs, lists, tables).
        #[arg(long)]
        layout: bool,
    },
    /// Hexdump the file or a selected element (hexyl-style).
    Hex {
        /// Path or http(s) URL of the PDF.
        input: String,
        /// Password for an encrypted file (user or owner password).
        #[arg(long, default_value = "")]
        password: String,
        // Not a real intra-doc link: `[,G]` is the CLI's own bracket
        // notation for an optional generation number, not markdown link
        // syntax, but rustdoc parses it as one.
        #[allow(rustdoc::broken_intra_doc_links)]
        /// obj:N[,G] | header | xref:N | trailer | range:START-END
        /// (offsets decimal or 0x-hex; xref sections indexed in chain
        /// order, newest first). Default: the whole file.
        selector: Option<String>,
        /// Print labeled element boundaries as the dump crosses them.
        #[arg(long)]
        annotate: bool,
        /// Bytes per row.
        #[arg(long, default_value_t = 16)]
        width: usize,
    },
    /// Run a jq program over the document's JSON value tree.
    Q {
        /// Path or http(s) URL of the PDF.
        input: String,
        /// Password for an encrypted file (user or owner password).
        #[arg(long, default_value = "")]
        password: String,
        /// jq program, e.g. '.objects["12 0"]'.
        program: String,
        /// Embed raw (still encoded) stream data as base64.
        #[arg(long, conflicts_with = "decode")]
        raw: bool,
        /// Embed decoded stream data as base64.
        #[arg(long)]
        decode: bool,
        /// Hexdump results carrying a `_span` instead of printing JSON.
        #[arg(long)]
        hex: bool,
        /// Print string results raw, without quotes (like jq -r).
        #[arg(short = 'r')]
        raw_strings: bool,
        /// Restrict logical elements to these 1-based pages (comma separated).
        #[arg(long, value_delimiter = ',')]
        pages: Option<Vec<usize>>,
        /// Skip the logical layer (pages/fonts/images/annotations).
        #[arg(long)]
        no_logical: bool,
        /// Include per-page content-stream operators (high volume).
        #[arg(long)]
        content_ops: bool,
    },
    /// Install or print the bundled Claude Code skill for coding agents.
    Skill {
        #[command(subcommand)]
        command: skill::SkillCommand,
    },
}

/// Parses `--every` as a positive page count. `usize` carries no
/// `clap::value_parser!` range support (unlike the fixed-width integers),
/// so the 1.. bound is checked by hand: 0 is rejected here rather than
/// reaching `split_document` as an unrepresentable chunk size.
fn parse_every(s: &str) -> Result<usize, String> {
    let n: usize = s
        .parse()
        .map_err(|_| format!("invalid value '{s}' for --every: not a number"))?;
    if n == 0 {
        return Err("invalid value '0' for --every: 0 is not in 1..".to_string());
    }
    Ok(n)
}

/// `--fonts` choices for `render`, mapping to `pdfboss_render::GlyphPainting`.
#[derive(Clone, Copy, Debug, PartialEq, clap::ValueEnum)]
enum FontsArg {
    /// Only embedded TrueType outlines (fastest).
    EmbeddedOnly,
    /// Every embedded program.
    AllEmbedded,
    /// Also substitute bundled faces for non-embedded fonts.
    Full,
}

impl FontsArg {
    fn to_painting(self) -> pdfboss_render::GlyphPainting {
        use pdfboss_render::GlyphPainting;
        match self {
            FontsArg::EmbeddedOnly => GlyphPainting::EmbeddedTrueTypeOnly,
            FontsArg::AllEmbedded => GlyphPainting::AllEmbedded,
            FontsArg::Full => GlyphPainting::Full,
        }
    }
}

/// Resolves an omitted `--fonts` to a tier: `full` when substitute faces
/// are at hand — an explicit `--font-dir`, or the compiled-in OFL set —
/// and `all-embedded` when neither is, so a default render paints
/// non-embedded fonts wherever it can and never errors over the choice.
fn default_fonts(font_dir: &Option<PathBuf>) -> FontsArg {
    if font_dir.is_some() || pdfboss_render::builtin_fonts_available() {
        FontsArg::Full
    } else {
        FontsArg::AllEmbedded
    }
}

/// `--png-compression` choices for `render`, mapping to
/// `pdfboss_render::PngCompression`.
#[derive(Clone, Copy, Debug, Default, clap::ValueEnum)]
enum PngCompressionArg {
    /// Uncompressed: fastest, largest files.
    None,
    /// Very fast with a decent ratio.
    Fast,
    /// Balances encode speed and file size (default).
    #[default]
    Default,
    /// Smallest files, much slower.
    Best,
}

impl PngCompressionArg {
    fn to_compression(self) -> pdfboss_render::PngCompression {
        use pdfboss_render::PngCompression;
        match self {
            PngCompressionArg::None => PngCompression::None,
            PngCompressionArg::Fast => PngCompression::Fast,
            PngCompressionArg::Default => PngCompression::Balanced,
            PngCompressionArg::Best => PngCompression::Best,
        }
    }
}

/// `--reading-order` values for `text` and `md`, mapped onto
/// `pdfboss_output::ReadingOrder`.
#[derive(Clone, Copy, Debug, Default, clap::ValueEnum)]
enum ReadingOrderArg {
    /// The content stream's order, corrected by geometry (default).
    #[default]
    Content,
    /// The structure tree's order on tagged pages, content order elsewhere.
    StructureTree,
    /// Position alone: lines top to bottom, left to right.
    Geometric,
}

impl ReadingOrderArg {
    fn to_order(self) -> pdfboss_output::ReadingOrder {
        use pdfboss_output::ReadingOrder;
        match self {
            ReadingOrderArg::Content => ReadingOrder::Content,
            ReadingOrderArg::StructureTree => ReadingOrder::StructureTree,
            ReadingOrderArg::Geometric => ReadingOrder::Geometric,
        }
    }
}

fn main() {
    let cli = Cli::parse();
    let result: Result<(), Failure> = match cli.command {
        Command::Create { command } => create::cmd_create(command).map_err(Failure::from),
        Command::Skill { command } => skill::cmd_skill(command).map_err(Failure::from),
        Command::Meta {
            file,
            out,
            set,
            rewrite,
            password,
        } => meta::cmd_meta(&file, &out, &set, rewrite, &password).map_err(Failure::from),
        Command::Merge {
            inputs,
            out,
            password,
        } => assemble::cmd_merge(&inputs, &out, &password).map_err(Failure::from),
        Command::Split {
            file,
            out,
            every,
            password,
        } => assemble::cmd_split(&file, &out, every, &password).map_err(Failure::from),
        Command::Rotate {
            file,
            out,
            pages,
            by,
            rewrite,
            password,
        } => assemble::cmd_rotate(&file, &out, pages.as_deref(), &by, rewrite, &password)
            .map_err(Failure::from),
        Command::Overlay {
            file,
            overlay,
            out,
            under,
            rewrite,
            password,
        } => assemble::cmd_overlay(&file, &overlay, &out, under, rewrite, &password)
            .map_err(Failure::from),
        Command::Rewrite {
            file,
            out,
            password,
        } => assemble::cmd_rewrite(&file, &out, &password).map_err(Failure::from),
        Command::Encrypt {
            file,
            out,
            user_password,
            owner_password,
            allow,
            password,
        } => assemble::cmd_encrypt(
            &file,
            &out,
            &user_password,
            &owner_password,
            allow,
            &password,
        ),
        Command::Decrypt {
            file,
            out,
            password,
        } => assemble::cmd_decrypt(&file, &out, &password).map_err(Failure::from),
        Command::Info { file, password } => cmd_info(&file, &password).map_err(Failure::from),
        Command::Text {
            file,
            page,
            password,
            reading_order,
        } => cmd_text(&file, page, &password, reading_order.to_order()).map_err(Failure::from),
        Command::Md {
            file,
            page,
            password,
            reading_order,
        } => cmd_md(&file, page, &password, reading_order.to_order()).map_err(Failure::from),
        Command::Render {
            file,
            page,
            out,
            scale,
            fonts,
            font_dir,
            password,
            png_compression,
            jpeg_quality,
        } => cmd_render(
            &file,
            page,
            out,
            scale,
            fonts,
            font_dir,
            &password,
            png_compression,
            jpeg_quality,
        )
        .map_err(Failure::from),
        Command::Images {
            file,
            page,
            out,
            password,
            png_compression,
        } => cmd_images(&file, page, out, &password, png_compression).map_err(Failure::from),
        Command::Obj {
            file,
            num,
            gen,
            password,
        } => cmd_obj(&file, num, gen.unwrap_or(0), &password).map_err(Failure::from),
        Command::Tui { target, password } => cmd_tui(&target, &password).map_err(Failure::from),
        Command::Json {
            input,
            raw,
            decode,
            pages,
            no_logical,
            content_ops,
            layout,
            password,
        } => {
            let flags = q::value::TreeFlags {
                raw,
                decode,
                pages,
                no_logical,
                content_ops,
            };
            json::cmd_json(&input, &flags, layout, &password).map_err(Failure::from)
        }
        Command::Hex {
            input,
            selector,
            annotate,
            width,
            password,
        } => hexdump::cmd_hex(&input, selector.as_deref(), annotate, width, &password)
            .map_err(Failure::from),
        Command::Q {
            input,
            program,
            raw,
            decode,
            hex,
            raw_strings,
            pages,
            no_logical,
            content_ops,
            password,
        } => {
            let flags = q::value::TreeFlags {
                raw,
                decode,
                pages,
                no_logical,
                content_ops,
            };
            q::run::cmd_q(&input, &program, &flags, hex, raw_strings, &password)
        }
    };
    if let Err(failure) = result {
        eprintln!("pdfboss: {}", failure.message);
        std::process::exit(failure.code);
    }
}

/// `pdfboss info`: prints version, encrypted flag, page count, per-page
/// sizes and the metadata table. Encrypted documents still report
/// successfully (with `encrypted: true`) since that is the very thing the
/// user is asking about.
fn cmd_info(file: &Path, password: &str) -> Result<(), String> {
    match Document::open_with_password(file, password) {
        Ok(doc) => {
            let sizes: Vec<Option<(f32, f32)>> = (0..doc.page_count())
                .map(|i| doc.page(i).ok().map(|p| p.size()))
                .collect();
            print!(
                "{}",
                info_text(
                    Some(doc.version()),
                    false,
                    Some(&sizes),
                    &doc.metadata(),
                    &doc.extensions(),
                    &doc.form_fields(),
                )
            );
            Ok(())
        }
        Err(Error::Encrypted) => {
            let data = std::fs::read(file).map_err(|e| e.to_string())?;
            print!(
                "{}",
                info_text(
                    scan_version(&data),
                    true,
                    None,
                    &Metadata::default(),
                    &[],
                    &[]
                )
            );
            Ok(())
        }
        Err(e) => Err(e.to_string()),
    }
}

/// Renders the `info` report. `sizes` is one entry per page (`None` when a
/// page failed to load); `None` for the whole slice means the page count is
/// unknown (encrypted document). `fields` are the interactive form's
/// fields, counted by type.
fn info_text(
    version: Option<(u8, u8)>,
    encrypted: bool,
    sizes: Option<&[Option<(f32, f32)>]>,
    meta: &Metadata,
    extensions: &[pdfboss_core::DeveloperExtension],
    fields: &[pdfboss_core::FormField],
) -> String {
    let mut out = String::new();
    match version {
        Some((major, minor)) => {
            let _ = writeln!(out, "version:   {major}.{minor}");
        }
        None => {
            let _ = writeln!(out, "version:   unknown");
        }
    }
    if !extensions.is_empty() {
        let _ = writeln!(out, "extensions:");
        for extension in extensions {
            let _ = writeln!(
                out,
                "  {:<9} {} level {}",
                extension.prefix, extension.base_version, extension.extension_level
            );
        }
    }
    let _ = writeln!(out, "encrypted: {encrypted}");
    match sizes {
        Some(sizes) => {
            let _ = writeln!(out, "pages:     {}", sizes.len());
            for (i, size) in sizes.iter().enumerate() {
                match size {
                    Some((w, h)) => {
                        let _ = writeln!(out, "  page {}: {w} x {h} pt", i + 1);
                    }
                    None => {
                        let _ = writeln!(out, "  page {}: (unavailable)", i + 1);
                    }
                }
            }
        }
        None => {
            let _ = writeln!(out, "pages:     unknown");
        }
    }
    // Only terminal fields hold values; a field with child fields is a
    // container for inheritable entries (ISO 32000-1 §12.7.3).
    let terminal: Vec<&pdfboss_core::FormField> = fields
        .iter()
        .filter(|field| field.kids.is_empty())
        .collect();
    if !terminal.is_empty() {
        use pdfboss_core::FieldType;
        let groups = [
            (Some(FieldType::Button), "Btn"),
            (Some(FieldType::Text), "Tx"),
            (Some(FieldType::Choice), "Ch"),
            (Some(FieldType::Signature), "Sig"),
            (None, "untyped"),
        ];
        let breakdown: Vec<String> = groups
            .iter()
            .map(|(field_type, label)| {
                let count = terminal
                    .iter()
                    .filter(|field| field.field_type == *field_type)
                    .count();
                (count, label)
            })
            .filter(|(count, _)| *count > 0)
            .map(|(count, label)| format!("{label} {count}"))
            .collect();
        let _ = writeln!(
            out,
            "fields:    {} ({})",
            terminal.len(),
            breakdown.join(", ")
        );
    }
    // A date that parses (ISO 32000-1 §7.9.4) prints as ISO 8601; one that
    // does not prints as written.
    let created = meta
        .creation_date_parsed()
        .map(|d| d.to_iso8601())
        .or_else(|| meta.creation_date.clone());
    let modified = meta
        .mod_date_parsed()
        .map(|d| d.to_iso8601())
        .or_else(|| meta.mod_date.clone());
    let rows: [(&str, &Option<String>); 8] = [
        ("title", &meta.title),
        ("author", &meta.author),
        ("subject", &meta.subject),
        ("keywords", &meta.keywords),
        ("creator", &meta.creator),
        ("producer", &meta.producer),
        ("created", &created),
        ("modified", &modified),
    ];
    if rows.iter().any(|(_, v)| v.is_some()) {
        let _ = writeln!(out, "metadata:");
        for (label, value) in rows {
            if let Some(value) = value {
                let _ = writeln!(out, "  {label:<9} {value}");
            }
        }
    }
    out
}

/// Finds `%PDF-x.y` in the first KiB of `data` without loading the
/// document (used when the document is encrypted and cannot be opened).
fn scan_version(data: &[u8]) -> Option<(u8, u8)> {
    let window = &data[..data.len().min(1024)];
    let pos = window.windows(5).position(|w| w == b"%PDF-")?;
    let rest = &window[pos + 5..];
    let major = (*rest.first()? as char).to_digit(10)? as u8;
    if rest.get(1) != Some(&b'.') {
        return None;
    }
    let minor = (*rest.get(2)? as char).to_digit(10)? as u8;
    Some((major, minor))
}

/// `pdfboss text`: one page (1-based `--page`) or all pages joined by
/// form feed. Extraction is lenient — content that will not read yields
/// no text rather than an error — so anything skipped is surfaced as a
/// stderr warning instead of vanishing.
fn cmd_text(
    file: &Path,
    page: Option<usize>,
    password: &str,
    order: pdfboss_output::ReadingOrder,
) -> Result<(), String> {
    let doc = Document::open_with_password(file, password).map_err(|e| e.to_string())?;
    let text = match page {
        Some(n) => {
            let index = page_index(n, doc.page_count())?;
            let page = doc.page(index).map_err(|e| e.to_string())?;
            let (text, report) = pdfboss_output::extract_text_reporting(&doc, &page, order)
                .map_err(|e| e.to_string())?;
            warn_skips(n, &report);
            text
        }
        None => {
            // Fanned out across the cores, one document fork per worker;
            // `map_pages` visits exactly the materializable pages (the
            // flattened tree, not the declared `/Count`, which on a damaged
            // file may not match what the tree yields) and returns them in
            // page order. One font cache serves every worker, so a font
            // loads once per document rather than once per page.
            let fonts = pdfboss_output::FontCache::default();
            let parts = pdfboss_core::map_pages(&doc, |doc, page| {
                pdfboss_output::extract_text_reporting_cached(doc, page, &fonts, order)
            })
            .into_iter()
            .enumerate()
            .map(|(index, outcome)| {
                let (text, report) = outcome.map_err(|e| e.to_string())?;
                warn_skips(index + 1, &report);
                Ok(text)
            })
            .collect::<Result<Vec<String>, String>>()?;
            parts.join("\u{c}")
        }
    };
    println!("{text}");
    Ok(())
}

/// `pdfboss md`: one page (1-based `--page`) or the whole document as
/// Markdown -- headings, lists and pipe/HTML tables inferred from layout.
/// Heading sizes rank against the whole document unless `--page` narrows to
/// one page, whose sizes are then judged only against themselves.
fn cmd_md(
    file: &Path,
    page: Option<usize>,
    password: &str,
    order: pdfboss_output::ReadingOrder,
) -> Result<(), String> {
    let doc = Document::open_with_password(file, password).map_err(|e| e.to_string())?;
    let text = match page {
        Some(n) => {
            let index = page_index(n, doc.page_count())?;
            let page = doc.page(index).map_err(|e| e.to_string())?;
            let (spans, rulings, report) =
                pdfboss_text::extract_spans_and_rulings_reporting(&doc, &page, order)
                    .map_err(|e| e.to_string())?;
            warn_skips(n, &report);
            pdfboss_output::Markdown.render(&[pdfboss_output::page_layout_with_rulings(
                &spans,
                &rulings,
                report.order,
            )])
        }
        None => {
            let (md, reports) = pdfboss_output::extract_markdown_reporting(&doc, order)
                .map_err(|e| e.to_string())?;
            for (index, report) in reports.iter().enumerate() {
                warn_skips(index + 1, report);
            }
            md
        }
    };
    println!("{text}");
    Ok(())
}

/// One stderr line per skipped stream, 1-based page numbers matching
/// `--page`. Warnings, not errors: the text on stdout is still everything
/// that could be read.
fn warn_skips(page_no: usize, report: &pdfboss_output::ExtractReport) {
    for skip in &report.skipped {
        eprintln!(
            "warning: page {page_no}: skipped {} ({})",
            skip.kind, skip.cause
        );
    }
}

/// Resolves `--fonts`/`--font-dir` into a [`pdfboss_render::SubstituteSource`].
///
/// `embedded-only`/`all-embedded` never substitute. `full` needs a face
/// source: an explicit `--font-dir` always wins; otherwise the compiled-in
/// OFL set is used if this binary was built with the `substitute-fonts`
/// feature. With neither, this is an actionable error rather than a silent
/// no-op -- the caller asked for substitution and would otherwise get a
/// render indistinguishable from `all-embedded` with no explanation why.
fn substitute_source(
    fonts: FontsArg,
    font_dir: Option<PathBuf>,
) -> Result<pdfboss_render::SubstituteSource, String> {
    use pdfboss_render::SubstituteSource;
    match fonts {
        FontsArg::EmbeddedOnly | FontsArg::AllEmbedded => Ok(SubstituteSource::None),
        FontsArg::Full => match font_dir {
            Some(dir) => Ok(SubstituteSource::Dir(dir)),
            None if pdfboss_render::builtin_fonts_available() => Ok(SubstituteSource::Builtin),
            None => Err(
                "--fonts full requested but no substitute faces are available: pass \
                 --font-dir <PATH> (a directory holding the substitute font files), or \
                 rebuild pdfboss with the default `substitute-fonts` feature (this \
                 binary was built without it) to bundle the OFL set."
                    .to_string(),
            ),
        },
    }
}

/// `pdfboss render`: rasterizes one page to the image file `out`'s
/// extension names.
#[allow(clippy::too_many_arguments)]
fn cmd_render(
    file: &Path,
    page: usize,
    out: Option<PathBuf>,
    scale: f32,
    fonts: Option<FontsArg>,
    font_dir: Option<PathBuf>,
    password: &str,
    png_compression: PngCompressionArg,
    jpeg_quality: u8,
) -> Result<(), String> {
    if !scale.is_finite() || scale <= 0.0 {
        return Err(format!("invalid scale {scale}: must be a positive number"));
    }
    let out = out.unwrap_or_else(|| default_out(page));
    let format = output_format(&out, png_compression, jpeg_quality)?;
    let fonts = fonts.unwrap_or_else(|| default_fonts(&font_dir));
    let substitutes = substitute_source(fonts, font_dir)?;
    let doc = Document::open_with_password(file, password).map_err(|e| e.to_string())?;
    let index = page_index(page, doc.page_count())?;
    let p = doc.page(index).map_err(|e| e.to_string())?;
    let opts = pdfboss_render::RenderOptions {
        glyph_painting: fonts.to_painting(),
        substitutes,
        ..Default::default()
    };
    let (pixmap, report) =
        pdfboss_render::render_page_reporting(&doc, &p, scale, &opts).map_err(|e| e.to_string())?;
    let image = pixmap.encode(format).map_err(|e| e.to_string())?;
    std::fs::write(&out, image).map_err(|e| e.to_string())?;
    // Rendering is lenient, so a page whose content pdfboss could not read
    // still writes the image and still exits 0. Say what was lost, on stderr and
    // in the summary line, rather than reporting a clean render.
    for warning in report.warnings() {
        eprintln!("warning: page {page}: {warning}");
    }
    match report.summary() {
        Some(summary) => println!(
            "wrote {} ({} x {} px) [{}]",
            out.display(),
            pixmap.width,
            pixmap.height,
            summary
        ),
        None => println!(
            "wrote {} ({} x {} px)",
            out.display(),
            pixmap.width,
            pixmap.height
        ),
    }
    Ok(())
}

/// `pdfboss images`: writes every image the selected pages draw as
/// `page-N-image-M.png` (both numbers 1-based, M counting in drawing
/// order). Extraction is lenient like rendering, so a page whose images
/// cannot be decoded writes nothing for them and still exits 0.
fn cmd_images(
    file: &Path,
    page: Option<usize>,
    out: Option<PathBuf>,
    password: &str,
    png_compression: PngCompressionArg,
) -> Result<(), String> {
    let doc = Document::open_with_password(file, password).map_err(|e| e.to_string())?;
    let pages = match page {
        Some(p) => vec![page_index(p, doc.page_count())?],
        None => (0..doc.page_count()).collect(),
    };
    let dir = out.unwrap_or_else(|| PathBuf::from("."));
    let mut written = 0usize;
    for index in pages {
        let p = doc.page(index).map_err(|e| e.to_string())?;
        let images = pdfboss_render::extract_page_images(&doc, &p).map_err(|e| e.to_string())?;
        for (i, pix) in images.iter().enumerate() {
            let path = dir.join(format!("page-{}-image-{}.png", index + 1, i + 1));
            let png = pix
                .encode_png_with(png_compression.to_compression())
                .map_err(|e| e.to_string())?;
            std::fs::write(&path, png).map_err(|e| e.to_string())?;
            println!(
                "wrote {} ({} x {} px)",
                path.display(),
                pix.width,
                pix.height
            );
            written += 1;
        }
    }
    match written {
        1 => println!("extracted 1 image"),
        n => println!("extracted {n} images"),
    }
    Ok(())
}

/// `pdfboss obj`: pretty-prints one indirect object. Stream objects print
/// their dictionary plus a decoded-length note instead of raw bytes.
fn cmd_obj(file: &Path, num: u32, gen: u16, password: &str) -> Result<(), String> {
    let doc = Document::open_with_password(file, password).map_err(|e| e.to_string())?;
    let obj = doc.get(ObjRef { num, gen }).map_err(|e| e.to_string())?;
    match &obj {
        Object::Stream(s) => {
            println!("{}", pretty::format_dict(&s.dict));
            match doc.stream_data(s) {
                Ok(data) => println!("stream <{} bytes decoded>", data.len()),
                Err(e) => println!("stream <decode failed: {e}>"),
            }
        }
        other => println!("{}", pretty::format_object(other)),
    }
    Ok(())
}

/// `pdfboss tui`: interactive explorer over a local file or an http(s)
/// URL, on a current-thread tokio runtime (rasterization uses the
/// runtime's blocking pool; the loop itself is single-threaded).
fn cmd_tui(target: &str, password: &str) -> Result<(), String> {
    let runtime = tokio::runtime::Builder::new_current_thread()
        .enable_all()
        .build()
        .map_err(|e| e.to_string())?;
    runtime.block_on(async {
        let doc = open_async_document(target, password).await?;
        pdfboss_tui::run(doc, display_title(target), target.to_string())
            .await
            .map_err(|e| e.to_string())
    })
}

/// Builds the async document: the HTTP backend (with fallback-download
/// progress on stderr) for URLs, the file backend otherwise -- exactly the
/// split `json`/`hex`/`q` already make via `Input::open` (`pdfboss-aio`'s
/// `http` feature is unconditionally on for this crate, so there is no cfg
/// gate to make here).
///
/// Both branches wrap the aio error with `target`, the same
/// `format!("{spec}: {err}")` shape `Input::open` uses for its local
/// `std::io::Error` failures: without it, a missing file or bad URL surfaces
/// only the layer-prefixed message ("io: No such file or directory") with
/// no indication of which target failed to open.
async fn open_async_document(
    target: &str,
    password: &str,
) -> Result<pdfboss_aio::AsyncDocument, String> {
    if is_url(target) {
        return crate::progress::open_url_with_progress(target, password)
            .await
            .map_err(|e| format!("{target}: {e}"));
    }
    pdfboss_aio::AsyncDocument::open_with_password(target, password)
        .await
        .map_err(|e| format!("{target}: {e}"))
}

/// The status-bar title: the last path/URL segment, or the whole target.
fn display_title(target: &str) -> String {
    target
        .rsplit('/')
        .next()
        .filter(|segment| !segment.is_empty())
        .unwrap_or(target)
        .to_string()
}

/// Converts a 1-based page number into a 0-based index, validating range.
fn page_index(page: usize, count: usize) -> Result<usize, String> {
    if page == 0 || page > count {
        let plural = if count == 1 { "" } else { "s" };
        Err(format!(
            "page {page} out of range (document has {count} page{plural})"
        ))
    } else {
        Ok(page - 1)
    }
}

/// Default output path for `render`: `page-N.png`.
fn default_out(page: usize) -> PathBuf {
    PathBuf::from(format!("page-{page}.png"))
}

/// The image format `out`'s extension names, PNG carrying the requested
/// compression level and JPEG the requested quality.
fn output_format(
    out: &Path,
    png_compression: PngCompressionArg,
    jpeg_quality: u8,
) -> Result<pdfboss_render::ImageFormat, String> {
    use pdfboss_render::ImageFormat;
    let extension = out.extension().and_then(|e| e.to_str()).unwrap_or("");
    match ImageFormat::from_name(extension) {
        Some(ImageFormat::Png(_)) => Ok(ImageFormat::Png(png_compression.to_compression())),
        Some(ImageFormat::Jpeg { .. }) => Ok(ImageFormat::Jpeg {
            quality: jpeg_quality,
        }),
        Some(format) => Ok(format),
        None => Err(format!(
            "unsupported output format {extension:?}: use .png, .ppm, .bmp or .jpg"
        )),
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use clap::Parser;

    #[test]
    fn omitted_fonts_flag_resolves_by_face_availability() {
        let cli = Cli::parse_from(["pdfboss", "render", "in.pdf", "--page", "1"]);
        let Command::Render {
            fonts, font_dir, ..
        } = cli.command
        else {
            panic!("expected render command");
        };
        assert!(fonts.is_none(), "no flag parses as no explicit tier");
        let expected = if pdfboss_render::builtin_fonts_available() {
            FontsArg::Full
        } else {
            FontsArg::AllEmbedded
        };
        assert_eq!(default_fonts(&font_dir), expected);
        assert_eq!(
            default_fonts(&Some(PathBuf::from("/faces"))),
            FontsArg::Full,
            "a --font-dir alone asks for substitution"
        );
    }

    #[test]
    fn fonts_flag_parses_embedded_only() {
        let cli = Cli::parse_from([
            "pdfboss",
            "render",
            "in.pdf",
            "--page",
            "1",
            "--fonts",
            "embedded-only",
        ]);
        let Command::Render { fonts, .. } = cli.command else {
            panic!("expected render command");
        };
        assert!(matches!(fonts, Some(FontsArg::EmbeddedOnly)));
    }

    #[test]
    fn fonts_full_with_font_dir_parses_to_dir_source() {
        let cli = Cli::parse_from([
            "pdfboss",
            "render",
            "in.pdf",
            "--page",
            "1",
            "--fonts",
            "full",
            "--font-dir",
            "X",
        ]);
        let Command::Render {
            fonts, font_dir, ..
        } = cli.command
        else {
            panic!("expected render command");
        };
        assert!(matches!(fonts, Some(FontsArg::Full)));
        assert_eq!(font_dir, Some(PathBuf::from("X")));

        let source =
            substitute_source(FontsArg::Full, font_dir).expect("--font-dir given, always Ok");
        assert!(matches!(source, pdfboss_render::SubstituteSource::Dir(p) if p == Path::new("X")));
    }

    #[test]
    fn png_compression_flag_defaults_to_default_level() {
        let cli = Cli::parse_from(["pdfboss", "render", "in.pdf", "--page", "1"]);
        let Command::Render {
            png_compression, ..
        } = cli.command
        else {
            panic!("expected render command");
        };
        assert!(matches!(png_compression, PngCompressionArg::Default));
    }

    #[test]
    fn png_compression_flag_parses_every_level() {
        for (value, expected) in [
            ("none", pdfboss_render::PngCompression::None),
            ("fast", pdfboss_render::PngCompression::Fast),
            ("default", pdfboss_render::PngCompression::Balanced),
            ("best", pdfboss_render::PngCompression::Best),
        ] {
            let cli = Cli::parse_from([
                "pdfboss",
                "render",
                "in.pdf",
                "--page",
                "1",
                "--png-compression",
                value,
            ]);
            let Command::Render {
                png_compression, ..
            } = cli.command
            else {
                panic!("expected render command");
            };
            assert_eq!(png_compression.to_compression(), expected, "{value}");
        }
    }

    #[test]
    fn png_compression_flag_rejects_unknown_levels() {
        let outcome = Cli::try_parse_from([
            "pdfboss",
            "render",
            "in.pdf",
            "--page",
            "1",
            "--png-compression",
            "bogus",
        ]);
        assert!(outcome.is_err());
    }

    #[test]
    fn font_dir_defaults_to_none() {
        let cli = Cli::parse_from(["pdfboss", "render", "in.pdf", "--page", "1"]);
        let Command::Render { font_dir, .. } = cli.command else {
            panic!("expected render command");
        };
        assert_eq!(font_dir, None);
    }

    #[test]
    fn embedded_only_and_all_embedded_never_substitute() {
        assert!(matches!(
            substitute_source(FontsArg::EmbeddedOnly, None),
            Ok(pdfboss_render::SubstituteSource::None)
        ));
        assert!(matches!(
            substitute_source(FontsArg::AllEmbedded, None),
            Ok(pdfboss_render::SubstituteSource::None)
        ));
        // Even if a --font-dir happens to be set, embedded-only/all-embedded
        // ignore it.
        assert!(matches!(
            substitute_source(FontsArg::AllEmbedded, Some(PathBuf::from("X"))),
            Ok(pdfboss_render::SubstituteSource::None)
        ));
    }

    /// Without `--font-dir`, `full`'s fallback depends on whether this binary
    /// was built with the `substitute-fonts` feature (a default feature, so
    /// this is the path `cargo install pdfboss-cli` users get).
    #[cfg(feature = "substitute-fonts")]
    #[test]
    fn full_without_font_dir_falls_back_to_builtin_faces() {
        assert!(matches!(
            substitute_source(FontsArg::Full, None),
            Ok(pdfboss_render::SubstituteSource::Builtin)
        ));
    }

    /// A `--no-default-features` build has no bundled faces, so `full` without
    /// `--font-dir` is the actionable-error path, naming both escape hatches.
    #[cfg(not(feature = "substitute-fonts"))]
    #[test]
    fn full_without_font_dir_or_feature_is_actionable_error() {
        let err = substitute_source(FontsArg::Full, None).expect_err("no dir, no feature");
        assert!(err.contains("--font-dir"));
        assert!(err.contains("substitute-fonts"));
    }

    #[test]
    fn fonts_arg_maps_to_painting() {
        assert_eq!(
            FontsArg::EmbeddedOnly.to_painting(),
            pdfboss_render::GlyphPainting::EmbeddedTrueTypeOnly
        );
        assert_eq!(
            FontsArg::AllEmbedded.to_painting(),
            pdfboss_render::GlyphPainting::AllEmbedded
        );
        assert_eq!(
            FontsArg::Full.to_painting(),
            pdfboss_render::GlyphPainting::Full
        );
    }

    #[test]
    fn info_text_normal_document() {
        let sizes = [Some((612.0, 792.0))];
        let meta = Metadata {
            title: Some("Demo".to_string()),
            ..Metadata::default()
        };
        let report = info_text(Some((1, 7)), false, Some(&sizes), &meta, &[], &[]);
        assert!(report.contains("version:   1.7"));
        assert!(report.contains("encrypted: false"));
        assert!(report.contains("pages:     1"));
        assert!(report.contains("page 1: 612 x 792 pt"));
        assert!(report.contains("title"));
        assert!(report.contains("Demo"));
    }

    /// The catalog's developer extensions print after the version, one
    /// per line with the base version and the level; none prints nothing.
    // Covers ISO 32000-1 §7.12.2.
    #[test]
    fn info_text_lists_developer_extensions() {
        let extensions = [pdfboss_core::DeveloperExtension {
            prefix: "ADBE".to_string(),
            base_version: "1.7".to_string(),
            extension_level: 3,
        }];
        let report = info_text(
            Some((1, 7)),
            false,
            None,
            &Metadata::default(),
            &extensions,
            &[],
        );
        assert!(
            report.contains("version:   1.7\nextensions:\n  ADBE      1.7 level 3\n"),
            "{report}"
        );
        let report = info_text(Some((1, 7)), false, None, &Metadata::default(), &[], &[]);
        assert!(!report.contains("extensions"), "{report}");
    }

    /// The interactive form's terminal fields print after the pages as one
    /// count with a breakdown by field type; a non-terminal field is only a
    /// container and is not counted, and a document without fields prints
    /// no line.
    // Covers ISO 32000-1 §12.7.3.
    #[test]
    fn info_text_counts_form_fields_by_type() {
        use pdfboss_core::{FieldFlags, FieldType, FormField, ObjRef};
        fn field(field_type: Option<FieldType>, kids: Vec<ObjRef>) -> FormField {
            FormField {
                object: ObjRef { num: 1, gen: 0 },
                parent: None,
                kids,
                widgets: Vec::new(),
                field_type,
                partial_name: None,
                name: String::new(),
                alternate_name: None,
                mapping_name: None,
                flags: FieldFlags::default(),
                value: None,
                default_value: None,
                max_len: None,
                options: Vec::new(),
                top_index: 0,
                selected_indices: Vec::new(),
                additional_actions: None,
                lock: None,
                seed_value: None,
            }
        }
        let fields = [
            field(Some(FieldType::Text), vec![ObjRef { num: 2, gen: 0 }]),
            field(Some(FieldType::Text), Vec::new()),
            field(Some(FieldType::Text), Vec::new()),
            field(Some(FieldType::Button), Vec::new()),
            field(Some(FieldType::Choice), Vec::new()),
            field(Some(FieldType::Signature), Vec::new()),
            field(None, Vec::new()),
        ];
        let sizes = [Some((612.0, 792.0))];
        let report = info_text(
            Some((1, 7)),
            false,
            Some(&sizes),
            &Metadata::default(),
            &[],
            &fields,
        );
        assert!(
            report.contains(
                "  page 1: 612 x 792 pt
fields:    6 (Btn 1, Tx 2, Ch 1, Sig 1, untyped 1)
"
            ),
            "{report}"
        );
        let report = info_text(
            Some((1, 7)),
            false,
            Some(&sizes),
            &Metadata::default(),
            &[],
            &[],
        );
        assert!(!report.contains("fields"), "{report}");
    }

    #[test]
    fn info_text_encrypted_document() {
        let report = info_text(Some((1, 4)), true, None, &Metadata::default(), &[], &[]);
        assert!(report.contains("encrypted: true"));
        assert!(report.contains("pages:     unknown"));
        assert!(!report.contains("metadata:"));
    }

    #[test]
    fn info_text_unavailable_page() {
        let sizes = [None];
        let report = info_text(None, false, Some(&sizes), &Metadata::default(), &[], &[]);
        assert!(report.contains("version:   unknown"));
        assert!(report.contains("page 1: (unavailable)"));
    }

    #[test]
    fn scan_version_finds_header() {
        assert_eq!(scan_version(b"%PDF-1.7\n..."), Some((1, 7)));
        assert_eq!(scan_version(b"junk\n%PDF-2.0\n"), Some((2, 0)));
        assert_eq!(scan_version(b"no header here"), None);
        assert_eq!(scan_version(b"%PDF-x.y"), None);
        assert_eq!(scan_version(b""), None);
    }

    #[test]
    fn page_index_validates_range() {
        assert_eq!(page_index(1, 3), Ok(0));
        assert_eq!(page_index(3, 3), Ok(2));
        assert!(page_index(0, 3).is_err());
        assert!(page_index(4, 3).is_err());
        assert!(page_index(1, 0).is_err());
    }

    #[test]
    fn default_out_names_by_page() {
        assert_eq!(default_out(2), PathBuf::from("page-2.png"));
    }

    #[test]
    fn failure_from_string_exits_one() {
        let failure = Failure::from("boom".to_string());
        assert_eq!(failure.code, 1);
        assert_eq!(failure.message, "boom");
    }

    #[test]
    fn failure_program_exits_two() {
        let failure = Failure::program("bad program");
        assert_eq!(failure.code, 2);
        assert_eq!(failure.message, "bad program");
    }

    #[test]
    fn json_flags_parse() {
        let cli = Cli::parse_from([
            "pdfboss",
            "json",
            "in.pdf",
            "--raw",
            "--pages",
            "1,3",
            "--no-logical",
            "--content-ops",
            "--layout",
        ]);
        let Command::Json {
            input,
            raw,
            decode,
            pages,
            no_logical,
            content_ops,
            layout,
            password: _,
        } = cli.command
        else {
            panic!("expected json command");
        };
        assert_eq!(input, "in.pdf");
        assert!(raw && !decode && no_logical && content_ops && layout);
        assert_eq!(pages, Some(vec![1, 3]));
    }

    #[test]
    fn json_layout_flag_defaults_to_false() {
        let cli = Cli::parse_from(["pdfboss", "json", "in.pdf"]);
        let Command::Json { layout, .. } = cli.command else {
            panic!("expected json command");
        };
        assert!(!layout);
    }

    #[test]
    fn md_subcommand_parses_page_flag() {
        let cli = Cli::parse_from(["pdfboss", "md", "in.pdf", "--page", "2"]);
        let Command::Md { file, page, .. } = cli.command else {
            panic!("expected md command");
        };
        assert_eq!(file, PathBuf::from("in.pdf"));
        assert_eq!(page, Some(2));
    }

    #[test]
    fn md_subcommand_page_defaults_to_none() {
        let cli = Cli::parse_from(["pdfboss", "md", "in.pdf"]);
        let Command::Md { page, .. } = cli.command else {
            panic!("expected md command");
        };
        assert_eq!(page, None);
    }

    #[test]
    fn create_md_parses_theme_and_size() {
        let cli = Cli::try_parse_from([
            "pdfboss",
            "create",
            "md",
            "in.md",
            "-o",
            "out.pdf",
            "--theme",
            "dark.css",
            "--size",
            "letter",
            "--landscape",
        ])
        .unwrap();
        let Command::Create {
            command:
                create::CreateCommand::Md {
                    input,
                    out,
                    theme,
                    landscape,
                    ..
                },
        } = cli.command
        else {
            panic!("expected create md");
        };
        assert_eq!(input, PathBuf::from("in.md"));
        assert_eq!(out, PathBuf::from("out.pdf"));
        assert_eq!(theme, Some(PathBuf::from("dark.css")));
        assert!(landscape);
    }

    #[test]
    fn create_md_theme_defaults_to_none() {
        let cli =
            Cli::try_parse_from(["pdfboss", "create", "md", "in.md", "-o", "out.pdf"]).unwrap();
        let Command::Create {
            command: create::CreateCommand::Md { theme, .. },
        } = cli.command
        else {
            panic!("expected create md");
        };
        assert!(theme.is_none());
    }

    #[test]
    fn create_manifest_parses_input_and_out() {
        let cli = Cli::try_parse_from(["pdfboss", "create", "manifest", "q3.toml", "-o", "q3.pdf"])
            .unwrap();
        let Command::Create {
            command: create::CreateCommand::Manifest { input, out },
        } = cli.command
        else {
            panic!("expected create manifest");
        };
        assert_eq!(input, PathBuf::from("q3.toml"));
        assert_eq!(out, PathBuf::from("q3.pdf"));
    }

    #[test]
    fn create_manifest_requires_out() {
        let outcome = Cli::try_parse_from(["pdfboss", "create", "manifest", "q3.toml"]);
        assert!(outcome.is_err());
    }

    #[test]
    fn hex_flags_parse() {
        let cli = Cli::parse_from([
            "pdfboss",
            "hex",
            "in.pdf",
            "obj:12",
            "--annotate",
            "--width",
            "8",
        ]);
        let Command::Hex {
            input,
            selector,
            annotate,
            width,
            password: _,
        } = cli.command
        else {
            panic!("expected hex command");
        };
        assert_eq!(input, "in.pdf");
        assert_eq!(selector.as_deref(), Some("obj:12"));
        assert!(annotate);
        assert_eq!(width, 8);
    }

    #[test]
    fn q_flags_parse() {
        let cli = Cli::parse_from(["pdfboss", "q", "in.pdf", ".header", "--hex", "-r"]);
        let Command::Q {
            input,
            program,
            raw,
            decode,
            hex,
            raw_strings,
            ..
        } = cli.command
        else {
            panic!("expected q command");
        };
        assert_eq!(input, "in.pdf");
        assert_eq!(program, ".header");
        assert!(hex && raw_strings);
        assert!(!raw && !decode);
    }

    #[test]
    fn tui_subcommand_parses() {
        let cli = Cli::parse_from(["pdfboss", "tui", "in.pdf"]);
        let Command::Tui { target, .. } = cli.command else {
            panic!("expected tui command");
        };
        assert_eq!(target, "in.pdf");
    }

    #[test]
    fn url_detection() {
        assert!(is_url("https://example.com/a.pdf"));
        assert!(is_url("http://example.com/a.pdf"));
        assert!(!is_url("plain.pdf"));
        assert!(!is_url("dir/httpish.pdf"));
    }

    #[test]
    fn display_title_takes_last_segment() {
        assert_eq!(display_title("dir/sub/file.pdf"), "file.pdf");
        assert_eq!(display_title("file.pdf"), "file.pdf");
        assert_eq!(
            display_title("https://example.com/docs/spec.pdf"),
            "spec.pdf"
        );
        assert_eq!(display_title("trailing/"), "trailing/");
    }

    #[test]
    fn cmd_images_writes_each_drawn_image_as_png() {
        use pdfboss_testkit::PdfBuilder;
        let mut b = PdfBuilder::new();
        b.object(1, "<< /Type /Catalog /Pages 2 0 R >>");
        b.object(2, "<< /Type /Pages /Kids [3 0 R] /Count 1 >>");
        b.object(
            3,
            "<< /Type /Page /Parent 2 0 R /MediaBox [0 0 100 100] \
             /Resources << /XObject << /Im1 5 0 R >> >> /Contents 4 0 R >>",
        );
        b.stream(
            4,
            "",
            b"q 50 0 0 50 0 0 cm /Im1 Do Q q 50 0 0 50 50 50 cm /Im1 Do Q",
        );
        b.stream(
            5,
            "/Type /XObject /Subtype /Image /Width 2 /Height 2 \
             /ColorSpace /DeviceRGB /BitsPerComponent 8",
            &[255, 0, 0, 0, 255, 0, 0, 0, 255, 255, 255, 0],
        );
        let dir = std::env::temp_dir().join(format!("pdfboss-images-test-{}", std::process::id()));
        std::fs::create_dir_all(&dir).expect("temp dir");
        let pdf = dir.join("two-draws.pdf");
        std::fs::write(&pdf, b.build(1)).expect("fixture");
        cmd_images(
            &pdf,
            None,
            Some(dir.clone()),
            "",
            PngCompressionArg::Default,
        )
        .expect("extract");
        for name in ["page-1-image-1.png", "page-1-image-2.png"] {
            let png = std::fs::read(dir.join(name)).expect(name);
            assert_eq!(&png[..8], b"\x89PNG\r\n\x1a\n", "{name} is a PNG");
        }
        std::fs::remove_dir_all(&dir).expect("cleanup");
    }

    #[test]
    fn images_subcommand_parses_with_defaults() {
        let cli = Cli::parse_from(["pdfboss", "images", "in.pdf"]);
        let Command::Images {
            file, page, out, ..
        } = cli.command
        else {
            panic!("expected images command");
        };
        assert_eq!(file, PathBuf::from("in.pdf"));
        assert_eq!(page, None);
        assert_eq!(out, None);
    }
}