pdfboss-cli 0.6.0

Command-line interface for pdfboss: info, text, render, obj, and the json/hex/q/tui explorer subcommands
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
//! The `pdfboss` command-line tool: document info, text extraction, page
//! rendering and object inspection.

mod hexdump;
mod input;
mod json;
mod q;

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 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 {
    /// Show version, page count, page sizes and metadata.
    Info {
        /// Path to the PDF file.
        file: PathBuf,
    },
    /// Extract text (all pages separated by form feed unless --page is given).
    Text {
        /// Path to the PDF file.
        file: PathBuf,
        /// 1-based page number.
        #[arg(long)]
        page: Option<usize>,
    },
    /// Render a page to PNG.
    Render {
        /// Path to the PDF file.
        file: PathBuf,
        /// 1-based page number.
        #[arg(long)]
        page: usize,
        /// Output file (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.
        #[arg(long, value_enum, default_value_t = FontsArg::AllEmbedded)]
        fonts: FontsArg,
        /// Directory of substitute faces for `--fonts full` (one file per
        /// `pdfboss_render::substitute::face_filename`, e.g. an installed
        /// `pdfboss-fonts` package). Overrides the compiled-in OFL set.
        #[arg(long)]
        font_dir: Option<PathBuf>,
    },
    /// Pretty-print a single object.
    Obj {
        /// Path to the PDF file.
        file: PathBuf,
        /// Object number.
        num: u32,
        /// Generation number (default 0).
        gen: Option<u16>,
    },
    /// Explore a PDF interactively in the terminal.
    ///
    /// Encrypted PDFs are not yet supported over this path (they are
    /// rejected at open, even under the empty user password that
    /// `info`/`text`/`render`/`obj` accept).
    Tui {
        /// Path or http(s) URL of the PDF.
        target: 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,
        /// 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,
    },
    /// Hexdump the file or a selected element (hexyl-style).
    Hex {
        /// Path or http(s) URL of the PDF.
        input: 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,
        /// 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,
    },
}

/// `--fonts` choices for `render`, mapping to `pdfboss_render::GlyphPainting`.
#[derive(Clone, Copy, Debug, Default, clap::ValueEnum)]
enum FontsArg {
    /// Only embedded TrueType outlines (fastest).
    EmbeddedOnly,
    /// Every embedded program (default).
    #[default]
    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,
        }
    }
}

fn main() {
    let cli = Cli::parse();
    let result: Result<(), Failure> = match cli.command {
        Command::Info { file } => cmd_info(&file).map_err(Failure::from),
        Command::Text { file, page } => cmd_text(&file, page).map_err(Failure::from),
        Command::Render {
            file,
            page,
            out,
            scale,
            fonts,
            font_dir,
        } => cmd_render(&file, page, out, scale, fonts, font_dir).map_err(Failure::from),
        Command::Obj { file, num, gen } => {
            cmd_obj(&file, num, gen.unwrap_or(0)).map_err(Failure::from)
        }
        Command::Tui { target } => cmd_tui(&target).map_err(Failure::from),
        Command::Json {
            input,
            raw,
            decode,
            pages,
            no_logical,
            content_ops,
        } => {
            let flags = q::value::TreeFlags {
                raw,
                decode,
                pages,
                no_logical,
                content_ops,
            };
            json::cmd_json(&input, &flags).map_err(Failure::from)
        }
        Command::Hex {
            input,
            selector,
            annotate,
            width,
        } => hexdump::cmd_hex(&input, selector.as_deref(), annotate, width).map_err(Failure::from),
        Command::Q {
            input,
            program,
            raw,
            decode,
            hex,
            raw_strings,
            pages,
            no_logical,
            content_ops,
        } => {
            let flags = q::value::TreeFlags {
                raw,
                decode,
                pages,
                no_logical,
                content_ops,
            };
            q::run::cmd_q(&input, &program, &flags, hex, raw_strings)
        }
    };
    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) -> Result<(), String> {
    match Document::open(file) {
        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())
            );
            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).
fn info_text(
    version: Option<(u8, u8)>,
    encrypted: bool,
    sizes: Option<&[Option<(f32, f32)>]>,
    meta: &Metadata,
) -> String {
    let mut out = String::new();
    match version {
        Some((major, minor)) => {
            let _ = writeln!(out, "version:   {major}.{minor}");
        }
        None => {
            let _ = writeln!(out, "version:   unknown");
        }
    }
    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");
        }
    }
    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", &meta.creation_date),
        ("modified", &meta.mod_date),
    ];
    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.
fn cmd_text(file: &Path, page: Option<usize>) -> Result<(), String> {
    let doc = Document::open(file).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())?;
            pdfboss_text::extract_text(&doc, &page).map_err(|e| e.to_string())?
        }
        None => {
            // Drive iteration by successful page lookups: `page_count()` is
            // the declared `/Count`, which on a damaged file may not match the
            // pages the tree yields. `page(index)` fails only past the last
            // real page.
            let mut parts = Vec::new();
            let mut index = 0;
            while let Ok(page) = doc.page(index) {
                parts.push(pdfboss_text::extract_text(&doc, &page).map_err(|e| e.to_string())?);
                index += 1;
            }
            parts.join("\u{c}")
        }
    };
    println!("{text}");
    Ok(())
}

/// 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 a PNG file.
fn cmd_render(
    file: &Path,
    page: usize,
    out: Option<PathBuf>,
    scale: f32,
    fonts: FontsArg,
    font_dir: Option<PathBuf>,
) -> Result<(), String> {
    if !scale.is_finite() || scale <= 0.0 {
        return Err(format!("invalid scale {scale}: must be a positive number"));
    }
    let substitutes = substitute_source(fonts, font_dir)?;
    let doc = Document::open(file).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,
    };
    let (pixmap, report) =
        pdfboss_render::render_page_reporting(&doc, &p, scale, &opts).map_err(|e| e.to_string())?;
    let out = out.unwrap_or_else(|| default_out(page));
    pixmap.save_png(&out).map_err(|e| e.to_string())?;
    // Rendering is lenient, so a page whose content pdfboss could not read
    // still writes a PNG 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 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) -> Result<(), String> {
    let doc = Document::open(file).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) -> 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).await?;
        pdfboss_tui::run(doc, display_title(target))
            .await
            .map_err(|e| e.to_string())
    })
}

/// Builds the async document: the HTTP backend 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) -> Result<pdfboss_aio::AsyncDocument, String> {
    if is_url(target) {
        return pdfboss_aio::AsyncDocument::open_url(target)
            .await
            .map_err(|e| format!("{target}: {e}"));
    }
    pdfboss_aio::AsyncDocument::open(target)
        .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"))
}

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

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

    #[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, 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, FontsArg::Full));
        assert_eq!(font_dir, Some(PathBuf::from("X")));

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

    #[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"));
    }

    #[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",
        ]);
        let Command::Json {
            input,
            raw,
            decode,
            pages,
            no_logical,
            content_ops,
        } = cli.command
        else {
            panic!("expected json command");
        };
        assert_eq!(input, "in.pdf");
        assert!(raw && !decode && no_logical && content_ops);
        assert_eq!(pages, Some(vec![1, 3]));
    }

    #[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,
        } = 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/");
    }
}