use crate::extract::{PageRuns, TextRun};
const BASELINE_TOL_EMS: f32 = 0.45;
const WORD_GAP_EMS: f32 = 0.25;
pub struct Row {
pub baseline: f32,
pub runs: Vec<TextRun>,
}
pub fn assemble(page: &PageRuns, page_index: usize) -> Vec<Row> {
let mut rows: Vec<Row> = Vec::new();
for run in page
.runs
.iter()
.filter(|r| r.page == page_index && !r.text.trim().is_empty())
{
let y = run.bbox.1;
let mut best: Option<(usize, f32)> = None;
for (i, row) in rows.iter().enumerate() {
let d = (row.baseline - y).abs();
if d <= baseline_tol(row, run) && best.map_or(true, |(_, bd)| d < bd) {
best = Some((i, d));
}
}
match best {
Some((i, _)) => rows[i].runs.push(run.clone()),
None => rows.push(Row {
baseline: y,
runs: vec![run.clone()],
}),
}
}
rows.sort_by(|a, b| b.baseline.total_cmp(&a.baseline));
for row in &mut rows {
let monotonic = row
.runs
.windows(2)
.all(|w| w[1].bbox.0 >= w[0].bbox.0 - 1.0);
if !monotonic {
row.runs.sort_by(|a, b| a.bbox.0.total_cmp(&b.bbox.0));
}
}
rows
}
fn baseline_tol(row: &Row, run: &TextRun) -> f32 {
let row_size = row.runs.iter().map(|r| r.font_size).fold(0.0f32, f32::max);
BASELINE_TOL_EMS * row_size.max(run.font_size)
}
pub fn advance_est(text: &str, em: f32) -> f32 {
text.chars().map(char_width_ems).sum::<f32>() * em
}
fn char_width_ems(c: char) -> f32 {
match c {
' ' | '\u{a0}' => 0.24,
'i' | 'j' | 'l' | 't' | 'f' | 'r' | '.' | ',' | ';' | ':' | '\'' | '\u{2018}'
| '\u{2019}' | '!' | '(' | ')' | '[' | ']' | '|' | '-' => 0.30,
'm' | 'w' => 0.72,
'M' | 'W' => 0.85,
'\u{2014}' => 0.90,
c if c.is_ascii_uppercase() => 0.62,
c if c.is_ascii_digit() => 0.50,
_ => 0.46,
}
}
pub fn width_est(run: &TextRun) -> f32 {
let reported = run.bbox.2 - run.bbox.0;
let estimated = advance_est(run.text.trim_end(), run.font_size);
if reported >= 0.5 * estimated && reported <= 1.6 * estimated {
reported
} else {
estimated
}
}
pub fn join_runs(runs: &[TextRun]) -> String {
let mut text = String::new();
let mut prev_end: Option<(f32, f32)> = None; for run in runs {
if let Some((end_x, em)) = prev_end {
let gap = run.bbox.0 - end_x;
let em = em.min(run.font_size);
let threshold = if text.trim_end().ends_with([':', ';']) {
0.12 * em
} else {
WORD_GAP_EMS * em
};
if gap > threshold && !text.ends_with(' ') && !run.text.starts_with(' ') {
text.push(' ');
}
}
text.extend(run.text.chars().filter(|c| !c.is_control() || *c == '\t'));
prev_end = Some((run.bbox.0 + width_est(run), run.font_size));
}
text
}
#[cfg(test)]
mod tests {
use super::*;
use crate::layout::testutil::{page, run};
#[test]
fn rows_cluster_by_baseline_scaled_tolerance() {
let p = page(vec![
run("alpha", 72.0, 700.0, 10.0, 0),
run("beta", 150.0, 701.5, 10.0, 0), run("gamma", 72.0, 688.0, 10.0, 0), ]);
let rows = assemble(&p, 0);
assert_eq!(rows.len(), 2);
assert_eq!(rows[0].runs.len(), 2);
assert_eq!(rows[1].runs[0].text, "gamma");
}
#[test]
fn superscript_joins_its_line() {
let p = page(vec![
run("see note", 72.0, 500.0, 10.0, 0),
run("1", 120.0, 503.5, 6.0, 0), ]);
let rows = assemble(&p, 0);
assert_eq!(rows.len(), 1);
}
#[test]
fn join_inserts_spaces_only_at_real_gaps() {
let a = run("Wo", 100.0, 700.0, 10.0, 0);
let b = run("rd", 100.0 + width_est(&a), 700.0, 10.0, 0);
let c = run("next", b.bbox.0 + width_est(&b) + 3.0, 700.0, 10.0, 0);
assert_eq!(join_runs(&[a, b, c]), "Word next");
}
#[test]
fn implausible_reported_extent_falls_back_to_estimate() {
let mut r = run("twenty four characters!!", 72.0, 700.0, 10.0, 0);
r.bbox.2 = r.bbox.0 + 400.0;
let w = width_est(&r);
assert!(w < 150.0, "drifted x1 must not be trusted, got {w}");
r.bbox.2 = r.bbox.0 + 10.0;
let w = width_est(&r);
assert!(w > 60.0, "collapsed x1 must not be trusted, got {w}");
}
}