use std::collections::BTreeMap;
use pdfium_render::prelude::*;
use super::{Artifact, Char, CharKind, CharSource, Figure, Rect, Style};
use crate::tags::{Elem, Mark, MarkValue, ObjMarks, RawPage};
pub fn page_chars(page: &PdfPage, raw: Option<&RawPage>) -> Vec<Char> {
let page_h = page.height().value;
let Ok(text) = page.text() else {
return Vec::new();
};
let chars = text.chars();
let total = chars.len();
let signals = raw
.map(|r| PageSignals::new(&r.object_marks(), &r.char_objects(), &r.structure()))
.filter(|s| s.char_count() == total);
let figures = figure_forms(page);
let mut out = Vec::new();
for i in 0..total {
let Ok(c) = chars.get(i as PdfPageTextCharIndex) else {
continue;
};
let Some(ch) = c.unicode_char() else { continue };
let Ok(r) = c.loose_bounds() else { continue };
let generated = c.is_generated().unwrap_or(false);
let size = c.scaled_font_size().value;
let bbox = Rect::new(
r.left().value,
page_h - r.top().value,
r.right().value,
page_h - r.bottom().value,
);
let finite = [bbox.left, bbox.top, bbox.right, bbox.bottom, size]
.iter()
.all(|v| v.is_finite());
if !finite {
continue;
}
let baseline = match c.origin_y() {
Ok(y) if y.value.is_finite() => page_h - y.value,
_ => bbox.bottom,
};
let raw_name = c.font_name();
let font = strip_subset(&raw_name).to_string();
let style = style_from_font(
&font,
c.font_is_bold_reenforced(),
c.font_is_italic(),
c.font_is_fixed_pitch(),
);
let (ch, kind) = classify(ch, || c.is_hyphen().unwrap_or(ch == '\u{2}'));
let mut source = signals.as_ref().map(|s| s.source(i)).unwrap_or_default();
source.figure = signals.as_ref().and_then(|s| s.form_of(i)).and_then(|t| {
let rect = figures.get(t as usize).copied().flatten()?;
Some(Figure { object: t, rect })
});
out.extend(split_ligature(Char {
ch,
bbox,
baseline,
size,
font,
style,
generated,
kind,
source,
}));
}
out
}
pub fn classify(ch: char, is_hyphen: impl FnOnce() -> bool) -> (char, CharKind) {
if !matches!(ch, '\u{2}' | '-' | '\u{2010}' | '\u{AD}') {
return (ch, CharKind::Text);
}
if is_hyphen() {
('-', CharKind::LineEndHyphen)
} else if ch == '\u{AD}' {
(ch, CharKind::SoftHyphen)
} else {
(ch, CharKind::Text)
}
}
pub fn ligature_letters(ch: char) -> Option<&'static str> {
Some(match ch {
'\u{FB00}' => "ff",
'\u{FB01}' => "fi",
'\u{FB02}' => "fl",
'\u{FB03}' => "ffi",
'\u{FB04}' => "ffl",
'\u{FB05}' | '\u{FB06}' => "st",
_ => return None,
})
}
pub fn split_ligature(c: Char) -> Vec<Char> {
let Some(letters) = ligature_letters(c.ch) else {
return vec![c];
};
let n = letters.chars().count() as f32;
let w = c.bbox.width() / n;
letters
.chars()
.enumerate()
.map(|(i, ch)| {
let left = c.bbox.left + w * i as f32;
Char {
ch,
bbox: Rect::new(left, c.bbox.top, left + w, c.bbox.bottom),
..c.clone()
}
})
.collect()
}
#[derive(Clone, Debug, Default, PartialEq)]
struct ObjSignals {
mcid: Option<i32>,
actual_text: Option<String>,
artifact: Option<Artifact>,
has_chars: bool,
}
#[derive(Clone, Debug, Default)]
pub struct PageSignals {
char_obj: Vec<Option<u32>>,
objects: Vec<ObjSignals>,
struct_actual: BTreeMap<i32, String>,
struct_heading: BTreeMap<i32, u8>,
char_form: Vec<Option<u32>>,
}
impl PageSignals {
pub fn new(marks: &[ObjMarks], char_paths: &[Option<Vec<usize>>], tree: &[Elem]) -> Self {
let mut objects = Vec::new();
let mut index = BTreeMap::new();
for (i, m) in marks.iter().enumerate() {
flatten(m, vec![i], &[], &mut objects, &mut index, 0);
}
let char_obj: Vec<Option<u32>> = char_paths
.iter()
.map(|p| p.as_ref().and_then(|p| index.get(p).copied()))
.collect();
for o in char_obj.iter().flatten() {
if let Some(obj) = objects.get_mut(*o as usize) {
obj.has_chars = true;
}
}
let char_form = char_paths
.iter()
.map(|p| match p.as_deref() {
Some([top, _, ..]) => u32::try_from(*top).ok(),
_ => None,
})
.collect();
let mut struct_actual = BTreeMap::new();
for e in tree {
collect_struct_actual(e, None, &mut struct_actual, 0);
}
let mut struct_heading = BTreeMap::new();
for e in tree {
collect_struct_heading(e, None, &mut struct_heading, 0);
}
PageSignals {
char_obj,
objects,
struct_actual,
struct_heading,
char_form,
}
}
pub fn form_of(&self, i: usize) -> Option<u32> {
self.char_form.get(i).copied().flatten()
}
pub fn char_count(&self) -> usize {
self.char_obj.len()
}
pub fn source(&self, i: usize) -> CharSource {
let Some(o) = self.char_obj.get(i).copied().flatten() else {
return CharSource::default();
};
let Some(obj) = self.objects.get(o as usize) else {
return CharSource::default();
};
let first = i == 0 || self.char_obj.get(i - 1).copied().flatten() != Some(o);
let hidden_text_before = if first && o > 0 {
self.objects
.get(o as usize - 1)
.filter(|p| !p.has_chars)
.and_then(|p| p.actual_text.clone())
} else {
None
};
CharSource {
object: Some(o),
mcid: obj.mcid,
actual_text: obj.actual_text.clone(),
struct_actual_text: obj.mcid.and_then(|m| self.struct_actual.get(&m).cloned()),
struct_heading: obj.mcid.and_then(|m| self.struct_heading.get(&m).copied()),
artifact: obj.artifact.clone(),
hidden_text_before,
figure: None,
}
}
}
const MAX_DEPTH: usize = 64;
fn flatten<'m>(
m: &'m ObjMarks,
path: Vec<usize>,
outer: &[&'m Mark],
objects: &mut Vec<ObjSignals>,
index: &mut BTreeMap<Vec<usize>, u32>,
depth: usize,
) {
let Ok(flat) = u32::try_from(objects.len()) else {
return;
};
let mut chain: Vec<&Mark> = outer.to_vec();
chain.extend(m.marks.iter());
objects.push(obj_signals(&chain));
if depth < MAX_DEPTH {
for (j, child) in m.children.iter().enumerate() {
let mut p = path.clone();
p.push(j);
flatten(child, p, &chain, objects, index, depth + 1);
}
}
index.insert(path, flat);
}
fn obj_signals(chain: &[&Mark]) -> ObjSignals {
let mcid = chain.iter().rev().find_map(|m| match m.get("MCID") {
Some(MarkValue::Int(v)) => Some(*v),
_ => None,
});
let actual_text = chain
.iter()
.rev()
.find_map(|m| m.str_param("ActualText"))
.map(str::to_string);
let artifact = chain
.iter()
.rev()
.find(|m| m.name == "Artifact")
.map(|m| Artifact {
subtype: match m.get("Subtype") {
Some(MarkValue::Name(s) | MarkValue::Str(s)) => Some(s.clone()),
_ => None,
},
has_params: !m.params.is_empty(),
pagination: m.get("Subtype").is_some()
|| matches!(m.get("Type"), Some(MarkValue::Name(t)) if t == "Pagination"),
});
ObjSignals {
mcid,
actual_text,
artifact,
has_chars: false,
}
}
fn collect_struct_actual(
e: &Elem,
inherited: Option<&str>,
out: &mut BTreeMap<i32, String>,
depth: usize,
) {
let at = e.actual_text.as_deref().or(inherited);
if let Some(at) = at {
for m in &e.mcids {
out.entry(*m).or_insert_with(|| at.to_string());
}
}
if depth < MAX_DEPTH {
for c in &e.children {
collect_struct_actual(c, at, out, depth + 1);
}
}
}
fn collect_struct_heading(
e: &Elem,
inherited: Option<u8>,
out: &mut BTreeMap<i32, u8>,
depth: usize,
) {
let own = e
.kind
.strip_prefix('H')
.and_then(|n| n.parse::<u8>().ok())
.filter(|n| (1..=6).contains(n));
let level = own.or(inherited);
if let Some(l) = level {
for m in &e.mcids {
out.entry(*m).or_insert(l);
}
}
if depth < MAX_DEPTH {
for c in &e.children {
collect_struct_heading(c, level, out, depth + 1);
}
}
}
pub fn page_path_marks(page: &PdfPage) -> Vec<Rect> {
const MIN_SIDE: f32 = 1.0;
const MAX_SIDE: f32 = 12.0;
let page_h = page.height().value;
let mut out = Vec::new();
for obj in page.objects().iter() {
if obj.object_type() != PdfPageObjectType::Path {
continue;
}
let Ok(q) = obj.bounds() else { continue };
let r = q.to_rect();
let rect = Rect::new(
r.left().value,
page_h - r.top().value,
r.right().value,
page_h - r.bottom().value,
);
let (w, h) = (rect.width(), rect.height());
let ok = w.is_finite()
&& h.is_finite()
&& (MIN_SIDE..=MAX_SIDE).contains(&w)
&& (MIN_SIDE..=MAX_SIDE).contains(&h)
&& w <= 1.5 * h
&& h <= 1.5 * w;
if ok {
out.push(rect);
}
}
out
}
const FIGURE_MAX_PAGE_SHARE: f32 = 0.5;
pub fn figure_forms(page: &PdfPage) -> Vec<Option<Rect>> {
let page_h = page.height().value;
let page_area = page.width().value * page_h;
page.objects()
.iter()
.map(|obj| {
if obj.object_type() != PdfPageObjectType::XObjectForm {
return None;
}
let r = obj.bounds().ok()?.to_rect();
let rect = Rect::new(
r.left().value,
page_h - r.top().value,
r.right().value,
page_h - r.bottom().value,
);
let area = rect.width() * rect.height();
(area.is_finite() && page_area > 0.0 && area < FIGURE_MAX_PAGE_SHARE * page_area)
.then_some(rect)
})
.collect()
}
pub fn page_rules(page: &PdfPage) -> Vec<Rect> {
const MAX_THICK: f32 = 3.0;
const MIN_LEN: f32 = 20.0;
let page_h = page.height().value;
let mut out = Vec::new();
for obj in page.objects().iter() {
if obj.object_type() != PdfPageObjectType::Path {
continue;
}
let Ok(q) = obj.bounds() else { continue };
let r = q.to_rect();
let rect = Rect::new(
r.left().value,
page_h - r.top().value,
r.right().value,
page_h - r.bottom().value,
);
let (w, h) = (rect.width(), rect.height());
if w.is_finite() && h.is_finite() && h <= MAX_THICK && w >= MIN_LEN {
out.push(rect);
}
}
out
}
pub fn strip_subset(name: &str) -> &str {
match name.split_once('+') {
Some((tag, rest)) if tag.len() == 6 && tag.bytes().all(|b| b.is_ascii_uppercase()) => rest,
_ => name,
}
}
pub fn style_from_font(
name: &str,
force_bold: bool,
italic_flag: bool,
fixed_pitch: bool,
) -> Style {
let lower = name.to_ascii_lowercase();
let has = |words: &[&str]| words.iter().any(|w| lower.contains(w));
Style {
bold: force_bold || has(&["bold", "black", "heavy", "semibold", "demibold"]),
italic: italic_flag || has(&["italic", "oblique", "slant"]),
mono: fixed_pitch
|| has(&[
"mono",
"courier",
"consolas",
"code",
"menlo",
"typewriter",
"lmtt",
"cmtt",
]),
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn subset_prefix_is_stripped_only_when_well_formed() {
assert_eq!(
strip_subset("JUNBRM+LMRoman10-Regular"),
"LMRoman10-Regular"
);
assert_eq!(strip_subset("Arial-BoldMT"), "Arial-BoldMT");
assert_eq!(strip_subset("abc+Foo"), "abc+Foo");
assert_eq!(strip_subset("AAAAAA+"), "");
}
#[test]
fn style_comes_from_the_name() {
let s = style_from_font("LMRoman10-BoldItalic", false, false, false);
assert!(s.bold && s.italic && !s.mono);
let s = style_from_font("LMMono10-Regular", false, false, false);
assert!(s.mono && !s.bold);
let s = style_from_font("Arial-BoldMT", false, false, false);
assert!(s.bold);
let s = style_from_font("TimesNewRomanPSMT", false, false, false);
assert_eq!(s, Style::default());
}
#[test]
fn hyphens_are_classified_not_deleted() {
assert_eq!(classify('\u{2}', || true), ('-', CharKind::LineEndHyphen));
assert_eq!(classify('\u{2}', || false), ('\u{2}', CharKind::Text));
assert_eq!(
classify('\u{AD}', || false),
('\u{AD}', CharKind::SoftHyphen)
);
assert_eq!(classify('\u{AD}', || true), ('-', CharKind::LineEndHyphen));
assert_eq!(classify('-', || false), ('-', CharKind::Text));
assert_eq!(classify('a', || panic!("asked")), ('a', CharKind::Text));
}
fn letter(ch: char, left: f32, right: f32) -> Char {
Char {
ch,
bbox: Rect::new(left, 90.0, right, 102.0),
baseline: 100.0,
size: 10.0,
font: "Serif".into(),
style: Style::default(),
generated: false,
kind: CharKind::Text,
source: CharSource {
object: Some(3),
..Default::default()
},
}
}
#[test]
fn ligatures_split_into_adjacent_letters() {
let parts = split_ligature(letter('\u{FB03}', 10.0, 25.0));
let text: String = parts.iter().map(|c| c.ch).collect();
assert_eq!(text, "ffi");
let edges: Vec<(f32, f32)> = parts.iter().map(|c| (c.bbox.left, c.bbox.right)).collect();
assert_eq!(edges, [(10.0, 15.0), (15.0, 20.0), (20.0, 25.0)]);
assert!(
parts
.iter()
.all(|c| c.baseline == 100.0 && c.source.object == Some(3))
);
assert_eq!(split_ligature(letter('f', 0.0, 3.0)).len(), 1);
for (lig, s) in [('\u{FB00}', "ff"), ('\u{FB01}', "fi"), ('\u{FB02}', "fl")] {
assert_eq!(ligature_letters(lig), Some(s));
}
assert_eq!(ligature_letters('\u{FB06}'), Some("st"));
assert_eq!(ligature_letters('\u{FB07}'), None);
let mut chars = vec![letter('o', 5.0, 10.0)];
chars.extend(split_ligature(letter('\u{FB01}', 10.0, 16.0)));
chars.push(letter('m', 16.0, 22.0));
let words = crate::layout::group::words(&chars);
assert_eq!(words.len(), 1);
assert_eq!(words[0].text, "ofim");
}
fn mark(name: &str, params: &[(&str, MarkValue)]) -> Mark {
Mark {
name: name.into(),
params: params
.iter()
.map(|(k, v)| (k.to_string(), v.clone()))
.collect(),
}
}
fn obj(marks: Vec<Mark>) -> ObjMarks {
ObjMarks {
marks,
children: Vec::new(),
}
}
fn elem(kind: &str, actual: Option<&str>, mcids: Vec<i32>, children: Vec<Elem>) -> Elem {
Elem {
kind: kind.into(),
alt: None,
actual_text: actual.map(String::from),
expansion: None,
mcids,
children,
}
}
#[test]
fn page_signals_follow_achado_007() {
let str_ = |s: &str| MarkValue::Str(s.into());
let marks = vec![
obj(vec![mark("Span", &[("MCID", MarkValue::Int(60))])]),
obj(vec![
mark("Span", &[("MCID", MarkValue::Int(60))]),
mark("Span", &[("ActualText", str_("-"))]),
]),
obj(vec![mark("Span", &[("ActualText", str_("-"))])]),
obj(vec![mark("Span", &[("MCID", MarkValue::Int(61))])]),
obj(vec![mark(
"Artifact",
&[("Subtype", MarkValue::Other("name"))],
)]),
ObjMarks {
marks: vec![mark("P", &[("MCID", MarkValue::Int(7))])],
children: vec![obj(vec![mark("Span", &[("ActualText", str_("fi"))])])],
},
];
let paths = vec![
Some(vec![0]),
Some(vec![0]),
Some(vec![1]),
None, Some(vec![3]),
Some(vec![3]),
Some(vec![4]),
Some(vec![5, 0]),
Some(vec![9]), ];
let tree = vec![elem(
"P",
None,
vec![60],
vec![elem("Span", Some("\u{AD}"), vec![61], Vec::new())],
)];
let s = PageSignals::new(&marks, &paths, &tree);
assert_eq!(s.char_count(), 9);
assert_eq!(s.struct_actual.get(&61).map(String::as_str), Some("\u{AD}"));
assert!(!s.struct_actual.contains_key(&60));
let hyphen = s.source(2);
assert_eq!(hyphen.object, Some(1));
assert_eq!(hyphen.mcid, Some(60));
assert_eq!(hyphen.actual_text.as_deref(), Some("-"));
assert_eq!(hyphen.hidden_text_before, None);
assert_eq!(s.source(3), CharSource::default());
let g = s.source(4);
assert_eq!(g.hidden_text_before.as_deref(), Some("-"));
assert_eq!(g.struct_actual_text.as_deref(), Some("\u{AD}"));
assert_eq!(s.source(5).hidden_text_before, None);
let a = s.source(6).artifact.expect("artifact");
assert_eq!((a.subtype, a.has_params, a.pagination), (None, true, true));
let child = s.source(7);
assert_eq!(child.object, Some(6));
assert_eq!(child.mcid, Some(7));
assert_eq!(child.actual_text.as_deref(), Some("fi"));
assert_eq!(s.source(8), CharSource::default());
assert_eq!(s.source(99), CharSource::default());
}
}