use std::path::Path;
use anyhow::{Context, Result};
use pdfium_render::prelude::*;
use crate::layout::furniture::Reason;
use crate::layout::{self, Block, Char, CharKind, Region, extract};
use crate::{engine, tags};
pub struct Options {
pub pages: Option<Vec<PdfPageIndex>>,
pub words: bool,
pub chars: bool,
}
pub fn run(file: &Path, opts: &Options) -> Result<()> {
let pdfium = engine::load()?;
let doc = pdfium
.load_pdf_from_file(file, None)
.with_context(|| format!("cannot open {}", file.display()))?;
let raw_doc = tags::RawDoc::open(doc.bindings(), &file.to_string_lossy());
outln!("== document: {}", file.display());
let indices: Vec<PdfPageIndex> = match &opts.pages {
Some(p) => p.clone(),
None => (0..doc.pages().len()).collect(),
};
let analyzed = if opts.chars {
Vec::new()
} else {
layout::analyze_document(&doc, raw_doc.as_ref())
};
for idx in indices {
let Ok(page) = doc.pages().get(idx) else {
outln!(
"
== page {} does not exist",
idx + 1
);
continue;
};
let (w, h) = (page.width().value, page.height().value);
outln!(
"
== page {} ({w:.0} x {h:.0} pt)",
idx + 1
);
if opts.chars {
let raw = raw_doc.as_ref().and_then(|d| d.page(idx));
print_chars(&extract::page_chars(&page, raw.as_ref()));
continue;
}
let Some(p) = usize::try_from(idx).ok().and_then(|i| analyzed.get(i)) else {
continue;
};
let mut n = 0;
let mut prev_base = None;
let mut region = None;
for b in &p.blocks {
if region != Some(b.region) {
region = Some(b.region);
if let Some(r) = p.regions.get(b.region) {
print_region(b.region, r);
}
prev_base = None;
}
print_block(n, b, opts.words, &mut prev_base, None);
n += 1;
}
if !p.furniture.is_empty() {
outln!("-- furniture (out of the reading order)");
prev_base = None;
for f in &p.furniture {
print_block(n, &f.block, opts.words, &mut prev_base, Some(f.reason));
n += 1;
}
}
}
Ok(())
}
fn print_chars(chars: &[Char]) {
for c in chars {
outln!(
"{:?}{} x={:.1}..{:.1} y={:.1}..{:.1} base={:.1} {:.1}pt {} {}{}",
c.ch,
if c.generated { " (gen)" } else { "" },
c.bbox.left,
c.bbox.right,
c.bbox.top,
c.bbox.bottom,
c.baseline,
c.size,
c.style.label(),
c.font,
char_signals(c)
);
}
}
fn char_signals(c: &Char) -> String {
let s = &c.source;
let mut parts = Vec::new();
match c.kind {
CharKind::Text => {}
CharKind::LineEndHyphen => parts.push("kind=line-end-hyphen".to_string()),
CharKind::SoftHyphen => parts.push("kind=soft-hyphen".to_string()),
}
if let Some(o) = s.object {
parts.push(format!("obj={o}"));
}
if let Some(m) = s.mcid {
parts.push(format!("mcid={m}"));
}
if let Some(t) = &s.actual_text {
parts.push(format!("at={t:?}"));
}
if let Some(t) = &s.struct_actual_text {
parts.push(format!("struct_at={t:?}"));
}
if let Some(a) = &s.artifact {
let sub = a.subtype.as_deref().unwrap_or("?");
let params = if a.has_params { "+params" } else { "" };
let pagination = if a.pagination { "+pagination" } else { "" };
parts.push(format!("artifact={sub}{params}{pagination}"));
}
if let Some(t) = &s.hidden_text_before {
parts.push(format!("hidden_before={t:?}"));
}
if parts.is_empty() {
String::new()
} else {
format!(" | {}", parts.join(" "))
}
}
fn print_region(i: usize, r: &Region) {
outln!(
"-- region {i}: band {}, column {}/{} x={:.1} y={:.1} w={:.1} h={:.1}",
r.band,
r.column + 1,
r.columns,
r.rect.left,
r.rect.top,
r.rect.width(),
r.rect.height()
);
}
fn print_block(
i: usize,
b: &Block,
words: bool,
prev_base: &mut Option<f32>,
furniture: Option<Reason>,
) {
let r = &b.bbox;
outln!(
"[{i:>3}] x={:>5.1} y={:>5.1} w={:>5.1} h={:>5.1} {} line{} {:.1}pt {}{}",
r.left,
r.top,
r.width(),
r.height(),
b.lines.len(),
if b.lines.len() == 1 { "" } else { "s" },
b.size,
b.style.label(),
furniture.map_or(String::new(), |r| format!(" [furniture: {}]", r.label()))
);
let text: Vec<String> = b.lines.iter().map(|l| l.text()).collect();
outln!(" {}", text.join(" ⏎ "));
if words {
for l in &b.lines {
let parts: Vec<String> = l
.words
.iter()
.map(|w| {
format!(
"{}{:?}@{:.1}{}",
if w.glued { "+" } else { "" },
w.text,
w.bbox.left,
if w.style == l.style && (w.size - l.size).abs() < 0.1 {
String::new()
} else {
format!("[{:.1}pt {}]", w.size, w.style.label())
}
)
})
.collect();
let step = prev_base.map_or(String::from("-"), |p: f32| {
format!("{:.2}", (l.baseline - p) / l.size.max(0.1))
});
*prev_base = Some(l.baseline);
let max_gap = l
.words
.windows(2)
.map(|w| w[1].bbox.left - w[0].bbox.right)
.fold(0.0f32, f32::max)
/ l.size.max(0.1);
outln!(
" | x={:.1} base={:.1} {:.1}pt step={step}em gap={max_gap:.2}em: {}",
l.bbox.left,
l.baseline,
l.size,
parts.join(" ")
);
}
}
}