use pdf_oxide::annotations::Annotation;
use pdf_oxide::geometry::Rect;
use pdf_oxide::layout::TextChar;
use serde::Serialize;
use crate::document::has_quads;
#[derive(Copy, Clone, Debug, PartialEq, Serialize)]
pub enum GlyphSpace {
TopDownTop,
TopDownBottom,
BottomUp,
}
impl GlyphSpace {
pub(crate) const FALLBACK: GlyphSpace = GlyphSpace::BottomUp;
pub(crate) fn infer(chars: &[TextChar], page_height: f32, debug: bool) -> Option<Self> {
let usable: Vec<&TextChar> = chars
.iter()
.filter(|c| c.bbox.height > 0.1 && !c.char.is_whitespace())
.collect();
if usable.len() < 20 {
if debug {
eprintln!(
"geometry: {} usable glyphs, too few to infer from",
usable.len()
);
}
return None;
}
let n = (usable.len() / 20).max(3);
let mean_y = |slice: &[&TextChar]| -> f32 {
slice.iter().map(|c| c.bbox.y).sum::<f32>() / slice.len() as f32
};
let head = mean_y(&usable[..n]);
let tail = mean_y(&usable[usable.len() - n..]);
let y_grows_downward = head < tail;
let baseline_semantics = usable.iter().all(|c| (c.origin_y - c.bbox.y).abs() < 0.01);
let escapes_as_top = usable
.iter()
.filter(|c| c.bbox.y < -1.0 || c.bbox.y + c.bbox.height > page_height + 1.0)
.count();
let escapes_as_bottom = usable
.iter()
.filter(|c| c.bbox.y - c.bbox.height < -1.0 || c.bbox.y > page_height + 1.0)
.count();
let space = if !y_grows_downward {
GlyphSpace::BottomUp
} else if baseline_semantics || escapes_as_bottom < escapes_as_top {
GlyphSpace::TopDownBottom
} else {
GlyphSpace::TopDownTop
};
if debug {
eprintln!(
"geometry: first-glyph mean y {head:.1}, last-glyph mean y {tail:.1} => y grows {}",
if y_grows_downward {
"downward"
} else {
"upward"
}
);
eprintln!(
"geometry: bbox.y == origin_y for all glyphs: {baseline_semantics} \
(baseline semantics)"
);
eprintln!(
"geometry: off-page glyphs if y is top edge: {escapes_as_top}, \
if bottom edge: {escapes_as_bottom} => inferred {space:?}"
);
}
Some(space)
}
pub(crate) fn to_top_down(self, b: &Rect, page_height: f32) -> (f32, f32) {
match self {
GlyphSpace::TopDownTop => (b.y, b.y + b.height),
GlyphSpace::TopDownBottom => (b.y - b.height, b.y),
GlyphSpace::BottomUp => (page_height - (b.y + b.height), page_height - b.y),
}
}
}
pub(crate) fn to_page_frame(
mut chars: Vec<TextChar>,
media_x0: f32,
media_y0: f32,
) -> Vec<TextChar> {
if media_x0 == 0.0 && media_y0 == 0.0 {
return chars;
}
for c in &mut chars {
c.bbox.x -= media_x0;
c.bbox.y -= media_y0;
c.origin_x -= media_x0;
c.origin_y -= media_y0;
}
chars
}
pub(crate) fn glyph_span(space: GlyphSpace, c: &TextChar, page_height: f32) -> (f32, f32) {
if c.ascent == 0.0 && c.descent == 0.0 {
return space.to_top_down(&c.bbox, page_height);
}
let above = c.origin_y + c.ascent;
let below = c.origin_y + c.descent;
match space {
GlyphSpace::BottomUp => (page_height - above, page_height - below),
GlyphSpace::TopDownTop | GlyphSpace::TopDownBottom => {
(c.origin_y - c.ascent, c.origin_y - c.descent)
}
}
}
pub(crate) fn baseline_key(space: GlyphSpace, c: &TextChar, page_height: f32) -> f32 {
match space {
GlyphSpace::BottomUp => page_height - c.origin_y,
GlyphSpace::TopDownTop | GlyphSpace::TopDownBottom => c.origin_y,
}
}
pub(crate) fn debug_geometry(
page: usize,
my0: f32,
my1: f32,
chars: Option<&[TextChar]>,
annots: &[Annotation],
) {
let Some(cs) = chars else { return };
let Some(a) = annots.iter().find(|a| has_quads(a)) else {
return;
};
eprintln!("page {}: mediabox y {my0:.1}..{my1:.1}", page + 1);
for c in cs.iter().filter(|c| !c.char.is_whitespace()).take(3) {
eprintln!(
" glyph {:?} bbox=({:.1}, {:.1}, {:.1}, {:.1}) origin_y={:.1}",
c.char, c.bbox.x, c.bbox.y, c.bbox.width, c.bbox.height, c.origin_y
);
}
if let Some(q) = a.quad_points.as_ref().and_then(|q| q.first()) {
eprintln!(" first quad {q:?}");
}
}