use std::cmp::Ordering;
use super::columns::{self, Region};
use super::furniture;
use super::{Block, Char, Line, Page, Rect, Style, Word};
pub const WORD_GAP: f32 = 0.15;
pub const BACKTRACK: f32 = 0.1;
pub const BASELINE_TOL: f32 = 0.15;
pub const SIZE_TOL: f32 = 0.05;
#[cfg(test)]
pub fn words(chars: &[Char]) -> Vec<Word> {
words_with_hints(chars).0
}
pub fn words_with_hints(chars: &[Char]) -> (Vec<Word>, Vec<furniture::Hint>) {
let hint = |all_pagination: bool| {
if all_pagination {
furniture::Hint::Pagination
} else {
furniture::Hint::None
}
};
let is_pagination = |c: &Char| c.source.artifact.as_ref().is_some_and(|a| a.pagination);
let mut hints = Vec::new();
let mut pagination = false;
let mut out: Vec<Word> = Vec::new();
let mut cur: Option<Word> = None;
let mut space_pending = true;
let mut last_left = f32::NEG_INFINITY;
for (i, c) in chars.iter().enumerate() {
if c.ch.is_whitespace() || c.ch.is_control() || c.ch == '\u{FFFE}' {
if let Some(w) = cur.take() {
out.push(w);
hints.push(hint(pagination));
}
space_pending = true;
continue;
}
if c.size <= 0.0 || c.bbox.width() < 0.0 {
continue;
}
if let Some(mut w) = cur.take() {
let size = w.size.min(c.size);
let gap = c.bbox.left - w.bbox.right;
let same_base = (c.baseline - w.baseline).abs() <= BASELINE_TOL * size;
let adjacent = gap <= WORD_GAP * size && c.bbox.left >= last_left - BACKTRACK * size;
let same_font = c.font == w.font && c.style == w.style && same_size(c.size, w.size);
last_left = c.bbox.left;
if same_base && adjacent && same_font {
if w.figure != c.source.figure {
w.figure = None;
}
w.text.push(c.ch);
w.bbox = w.bbox.union(&c.bbox);
w.len += 1;
w.chars.end = i + 1;
pagination &= is_pagination(c);
cur = Some(w);
continue;
}
space_pending = !(same_base && adjacent);
out.push(w);
hints.push(hint(pagination));
}
pagination = is_pagination(c);
cur = Some(Word {
text: c.ch.to_string(),
bbox: c.bbox,
baseline: c.baseline,
size: c.size,
font: c.font.clone(),
style: c.style,
glued: !space_pending && !out.is_empty(),
len: 1,
chars: i..i + 1,
figure: c.source.figure,
});
space_pending = false;
last_left = c.bbox.left;
}
if let Some(w) = cur {
out.push(w);
hints.push(hint(pagination));
}
(out, hints)
}
fn same_size(a: f32, b: f32) -> bool {
(a - b).abs() <= SIZE_TOL * a.max(b)
}
pub const CORE: f32 = 0.6;
pub const SCRIPT_OVERLAP: f32 = 0.3;
pub const SCRIPT_MAX_RATIO: f32 = 0.9;
pub const LINE_SPLIT_GAP: f32 = 0.9;
pub const LINE_SPLIT_GAP_MONO: f32 = 3.0;
pub const JUSTIFIED_RATIO: f32 = 1.5;
pub const SENTENCE_GAP_RATIO: f32 = 3.0;
#[cfg(test)]
pub fn lines(words: Vec<Word>) -> Vec<Line> {
lines_in(words, None)
}
pub fn lines_in(words: Vec<Word>, column: Option<(f32, f32)>) -> Vec<Line> {
let mut items: Vec<(usize, Word)> = words.into_iter().enumerate().collect();
items.sort_by(|a, b| {
cmp_f32(a.1.baseline, b.1.baseline)
.then(cmp_f32(a.1.bbox.left, b.1.bbox.left))
.then(a.0.cmp(&b.0))
});
let mut clusters: Vec<Vec<(usize, Word)>> = Vec::new();
for it in items {
if let Some(c) = clusters.last_mut() {
let ref_base = c[0].1.baseline;
let size = c[0].1.size.min(it.1.size);
if (it.1.baseline - ref_base).abs() <= BASELINE_TOL * size {
c.push(it);
continue;
}
}
clusters.push(vec![it]);
}
let mut merged = vec![false; clusters.len()];
for i in 0..clusters.len() {
let (size_i, core_i, extent_i) = cluster_metrics(&clusters[i]);
let mut best: Option<(usize, f32)> = None;
for (j, other) in clusters.iter().enumerate() {
if i == j || merged[j] {
continue;
}
let (size_j, core_j, extent_j) = cluster_metrics(other);
if size_i > SCRIPT_MAX_RATIO * size_j {
continue;
}
let overlap = (core_i.1.min(core_j.1) - core_i.0.max(core_j.0)).max(0.0);
let near = extent_i.0 <= extent_j.1 + size_j && extent_i.1 >= extent_j.0 - size_j;
if near
&& overlap >= SCRIPT_OVERLAP * (core_i.1 - core_i.0)
&& best.is_none_or(|(_, o)| overlap > o)
{
best = Some((j, overlap));
}
}
if let Some((j, _)) = best {
let moved = std::mem::take(&mut clusters[i]);
clusters[j].extend(moved);
merged[i] = true;
}
}
let rows: Vec<(f32, f32)> = clusters
.iter()
.filter(|c| !c.is_empty())
.map(|c| {
let (size, core, _) = cluster_metrics(c);
(core.1, size)
})
.collect();
let mut out = Vec::new();
for mut c in clusters.into_iter().filter(|c| !c.is_empty()) {
c.sort_by(|a, b| cmp_f32(a.1.bbox.left, b.1.bbox.left).then(a.0.cmp(&b.0)));
let size = dominant_size(c.iter().map(|(_, w)| (w.size, w.len)));
let base = cluster_metrics(&c).1.1;
let has_neighbour = rows.iter().any(|&(b, sz)| {
let step = (b - base).abs();
same_size(sz, size) && step > BASELINE_TOL * size && step <= MAX_LEADING * size
});
let justified = has_neighbour && column.is_some_and(|col| is_justified(&c, col, size));
let mut part: Vec<Word> = Vec::new();
let mut prev_seq: Option<usize> = None;
let mut split_once = false;
for (seq, mut w) in c {
if let Some(last) = part.last() {
let gap = w.bbox.left - last.bbox.right;
let limit = if w.style.mono && last.style.mono {
LINE_SPLIT_GAP_MONO
} else {
LINE_SPLIT_GAP
};
let lone_marker = !split_once && part.len() == 1 && is_marker_or_number(&last.text);
if gap > limit * size && !lone_marker && !justified {
out.push(make_line(std::mem::take(&mut part)));
prev_seq = None;
split_once = true;
}
}
if prev_seq.is_none_or(|p| p + 1 != seq) {
w.glued = match part.last() {
Some(last) => w.bbox.left - last.bbox.right <= WORD_GAP * size,
None => false,
};
}
if part.is_empty() {
w.glued = false;
}
prev_seq = Some(seq);
part.push(w);
}
if !part.is_empty() {
out.push(make_line(part));
}
}
out.sort_by(|a, b| cmp_f32(a.baseline, b.baseline).then(cmp_f32(a.bbox.left, b.bbox.left)));
out
}
fn is_justified(c: &[(usize, Word)], (left, right): (f32, f32), size: f32) -> bool {
let (Some(first), Some(last)) = (c.first(), c.last()) else {
return false;
};
if c.iter().any(|(_, w)| w.style.mono) {
return false;
}
let tol = ALIGN_TOL * size;
if (first.1.bbox.left - left).abs() > tol || (right - last.1.bbox.right).abs() > tol {
return false;
}
let gaps: Vec<(f32, bool)> = c
.windows(2)
.map(|p| {
let end = p[0].1.text.chars().last();
let sentence = matches!(end, Some('.' | '!' | '?' | ':'));
(p[1].1.bbox.left - p[0].1.bbox.right, sentence)
})
.filter(|(g, _)| *g > WORD_GAP * size)
.collect();
let plain = gaps.iter().filter(|g| !g.1).map(|g| g.0);
let min = plain.clone().fold(f32::INFINITY, f32::min);
let max = plain.fold(f32::NEG_INFINITY, f32::max);
let sentence_max = gaps
.iter()
.filter(|g| g.1)
.map(|g| g.0)
.fold(f32::NEG_INFINITY, f32::max);
min.is_finite() && max <= JUSTIFIED_RATIO * min && sentence_max <= SENTENCE_GAP_RATIO * min
}
fn is_marker_or_number(t: &str) -> bool {
is_marker(t) || (t.chars().count() <= 3 && t.chars().all(|c| c.is_ascii_digit()))
}
pub const PATH_MARKER_MAX: f32 = 0.6;
pub const PATH_MARKER_MIN: f32 = 0.15;
pub const PATH_MARKER_GAP: f32 = 1.5;
pub fn attach_path_markers(lines: &mut [Line], marks: &[Rect]) {
for m in marks {
let (w, h) = (m.width(), m.height());
let target = lines.iter_mut().find(|l| {
let size = l.size;
let core = Rect::new(
l.bbox.left,
l.baseline - CORE * size,
l.bbox.right,
l.baseline,
);
let square = w <= PATH_MARKER_MAX * size
&& h <= PATH_MARKER_MAX * size
&& w >= PATH_MARKER_MIN * size
&& h >= PATH_MARKER_MIN * size
&& w <= 1.5 * h
&& h <= 1.5 * w;
let mid = (m.top + m.bottom) / 2.0;
let gap = l.bbox.left - m.right;
square
&& mid >= core.top
&& mid <= core.bottom
&& gap >= 0.0
&& gap <= PATH_MARKER_GAP * size
&& !starts_with_marker(l)
});
if let Some(l) = target {
if let Some(w) = l.words.first_mut() {
w.glued = false;
}
l.words.insert(
0,
Word {
text: "•".into(),
bbox: *m,
baseline: l.baseline,
size: l.size,
font: String::from("(vector path)"),
style: Style::default(),
glued: false,
len: 1,
chars: 0..0,
figure: None,
},
);
l.bbox = l.bbox.union(m);
}
}
}
fn cluster_metrics(c: &[(usize, Word)]) -> (f32, (f32, f32), (f32, f32)) {
let size = dominant_size(c.iter().map(|(_, w)| (w.size, w.len)));
let base = c
.iter()
.find(|(_, w)| same_size(w.size, size))
.map_or(0.0, |(_, w)| w.baseline);
let left = c
.iter()
.map(|(_, w)| w.bbox.left)
.fold(f32::INFINITY, f32::min);
let right = c
.iter()
.map(|(_, w)| w.bbox.right)
.fold(f32::NEG_INFINITY, f32::max);
(size, (base - CORE * size, base), (left, right))
}
fn make_line(words: Vec<Word>) -> Line {
let size = dominant_size(words.iter().map(|w| (w.size, w.len)));
let baseline = words
.iter()
.find(|w| same_size(w.size, size))
.map_or(0.0, |w| w.baseline);
let style = majority_style(words.iter().map(|w| (w.style, w.len)));
let bbox = union_all(words.iter().map(|w| w.bbox));
Line {
words,
bbox,
baseline,
size,
style,
}
}
pub const MAX_LEADING: f32 = 1.45;
pub const LEADING_GROWTH: f32 = 1.3;
pub const ALIGN_TOL: f32 = 0.5;
pub const MAX_FIRST_INDENT: f32 = 3.0;
pub fn blocks(lines: Vec<Line>) -> Vec<Block> {
let mut groups: Vec<Vec<Line>> = Vec::new();
for line in lines {
let mut best: Option<(usize, f32)> = None;
for (i, g) in groups.iter().enumerate() {
let Some(prev) = g.last() else { continue };
let step = line.baseline - prev.baseline;
if step <= 0.0 {
continue;
}
let bbox = union_all(g.iter().map(|l| l.bbox));
if bbox.h_overlap(&line.bbox) <= 0.0 {
continue;
}
if best.is_none_or(|(_, s)| step < s) {
best = Some((i, step));
}
}
match best {
Some((i, _)) if joins(&groups[i], &line) => groups[i].push(line),
_ => groups.push(vec![line]),
}
}
groups.into_iter().map(make_block).collect()
}
fn joins(g: &[Line], line: &Line) -> bool {
let (Some(first), Some(prev)) = (g.first(), g.last()) else {
return false;
};
let size = prev.size.max(line.size);
if !same_size(prev.size, line.size) || first.style.bold != line.style.bold {
return false;
}
if first.style.mono != line.style.mono {
return false;
}
if starts_with_marker(line) {
return false;
}
let step = line.baseline - prev.baseline;
let max_step = if g.len() >= 2 {
let lead = g[1].baseline - g[0].baseline;
(lead * LEADING_GROWTH).min(MAX_LEADING * size)
} else {
MAX_LEADING * size
};
if step > max_step {
return false;
}
let tol = ALIGN_TOL * size;
let aligned = |a: f32, b: f32| (a - b).abs() <= tol;
let left = line.bbox.left;
if first.style.mono && line.style.mono && left >= first.bbox.left - tol {
return true;
}
if aligned(left, prev.bbox.left) || aligned(line.bbox.center_x(), prev.bbox.center_x()) {
return true;
}
if g.len() == 1 {
if left < prev.bbox.left && prev.bbox.left - left <= MAX_FIRST_INDENT * size {
return true;
}
let second = prev.words.get(1).map(|w| w.bbox.left);
if second.is_some_and(|x| aligned(left, x) && x - prev.bbox.left <= MAX_FIRST_INDENT * size)
{
return true;
}
}
false
}
pub fn starts_with_marker(line: &Line) -> bool {
line.words.len() >= 2 && line.words.first().is_some_and(|w| is_marker(&w.text))
}
pub fn is_marker(t: &str) -> bool {
const BULLETS: &[&str] = &[
"•", "◦", "▪", "▫", "‣", "⁃", "–", "—", "-", "∗", "*", "·", "■", "□", "●", "○", "►", "▸",
"➢", "✓",
"\u{F0B7}",
];
if BULLETS.contains(&t) {
return true;
}
let (body, close) = match t.char_indices().last() {
Some((i, c @ ('.' | ')'))) => (&t[..i], c),
_ => return false,
};
let body = if close == ')' {
body.strip_prefix('(').unwrap_or(body)
} else {
body
};
let n = body.chars().count();
if n == 0 {
return false;
}
let digits = n <= 3 && body.chars().all(|c| c.is_ascii_digit());
let letter = n == 1 && body.chars().all(|c| c.is_ascii_alphabetic());
let roman = n <= 5 && body.chars().all(|c| "ivxlc".contains(c));
digits || letter || roman
}
fn make_block(lines: Vec<Line>) -> Block {
let size = dominant_size(
lines
.iter()
.flat_map(|l| l.words.iter().map(|w| (w.size, w.len))),
);
let style = majority_style(
lines
.iter()
.flat_map(|l| l.words.iter().map(|w| (w.style, w.len))),
);
let bbox = union_all(lines.iter().map(|l| l.bbox));
Block {
lines,
bbox,
size,
style,
region: 0,
}
}
#[cfg(test)]
pub fn blocks_from_chars(chars: &[Char], path_marks: &[Rect]) -> Vec<Block> {
layout_from_chars(chars, path_marks).1
}
#[cfg(test)]
pub fn layout_from_chars(chars: &[Char], path_marks: &[Rect]) -> (Vec<Region>, Vec<Block>) {
layout_from_words(words(chars), path_marks, &[])
}
pub fn layout_from_words(
ws: Vec<Word>,
path_marks: &[Rect],
rules: &[Rect],
) -> (Vec<Region>, Vec<Block>) {
let mut regions = Vec::new();
let mut out = Vec::new();
for (i, (region, ws)) in columns::split(ws, rules).into_iter().enumerate() {
let mut ls = lines_in(ws, Some((region.rect.left, region.rect.right)));
attach_path_markers(&mut ls, path_marks);
out.extend(blocks(ls).into_iter().map(|mut b| {
b.region = i;
b
}));
regions.push(region);
}
(regions, out)
}
#[derive(Clone, Debug, Default)]
pub struct PagePrimitives {
pub width: f32,
pub height: f32,
pub chars: Vec<Char>,
pub path_marks: Vec<Rect>,
pub rules: Vec<Rect>,
}
pub fn layout_document(pages: Vec<PagePrimitives>) -> Vec<Page> {
let (page_words, page_hints): (Vec<Vec<Word>>, Vec<Vec<furniture::Hint>>) =
pages.iter().map(|p| words_with_hints(&p.chars)).unzip();
let inputs: Vec<furniture::PageWords> = pages
.iter()
.zip(page_words.iter().zip(&page_hints))
.enumerate()
.map(|(i, (p, (ws, hs)))| furniture::PageWords {
number: i + 1,
width: p.width,
words: ws,
hints: hs,
})
.collect();
let flags = furniture::detect(&inputs);
pages
.into_iter()
.zip(page_words)
.zip(flags)
.enumerate()
.map(|(i, ((p, ws), fl))| {
let mut body = Vec::new();
let mut furn: Vec<(furniture::Reason, Vec<Word>)> = Vec::new();
for (w, r) in ws.into_iter().zip(fl) {
match r {
None => body.push(w),
Some(r) => match furn.iter_mut().find(|(k, _)| *k == r) {
Some((_, v)) => v.push(w),
None => furn.push((r, vec![w])),
},
}
}
furn.sort_by_key(|(r, _)| *r);
let (regions, blocks_) = layout_from_words(body, &p.path_marks, &p.rules);
let mut furniture: Vec<furniture::Furniture> = furn
.into_iter()
.flat_map(|(reason, ws)| {
blocks(lines_in(ws, None))
.into_iter()
.map(move |block| furniture::Furniture { block, reason })
})
.collect();
furniture.sort_by(|a, b| {
cmp_f32(a.block.bbox.top, b.block.bbox.top)
.then(cmp_f32(a.block.bbox.left, b.block.bbox.left))
});
Page {
number: i + 1,
width: p.width,
height: p.height,
regions,
blocks: blocks_,
furniture,
chars: p.chars,
}
})
.collect()
}
fn cmp_f32(a: f32, b: f32) -> Ordering {
a.total_cmp(&b)
}
fn union_all(mut it: impl Iterator<Item = Rect>) -> Rect {
let first = it.next().unwrap_or(Rect::new(0.0, 0.0, 0.0, 0.0));
it.fold(first, |acc, r| acc.union(&r))
}
fn dominant_size(it: impl Iterator<Item = (f32, usize)>) -> f32 {
let mut buckets: Vec<(i64, usize)> = Vec::new();
for (s, n) in it {
let k = (s * 10.0).round() as i64;
match buckets.iter_mut().find(|(b, _)| *b == k) {
Some((_, c)) => *c += n,
None => buckets.push((k, n)),
}
}
buckets
.into_iter()
.max_by(|a, b| a.1.cmp(&b.1).then(a.0.cmp(&b.0)))
.map_or(0.0, |(k, _)| k as f32 / 10.0)
}
fn majority_style(it: impl Iterator<Item = (Style, usize)>) -> Style {
let (mut total, mut b, mut i, mut m) = (0, 0, 0, 0);
for (s, n) in it {
total += n;
b += if s.bold { n } else { 0 };
i += if s.italic { n } else { 0 };
m += if s.mono { n } else { 0 };
}
Style {
bold: 2 * b > total,
italic: 2 * i > total,
mono: 2 * m > total,
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::layout::CharKind;
const REGULAR: Style = Style {
bold: false,
italic: false,
mono: false,
};
const BOLD: Style = Style {
bold: true,
italic: false,
mono: false,
};
const MONO: Style = Style {
bold: false,
italic: false,
mono: true,
};
fn run(text: &str, x: f32, base: f32, size: f32, style: Style) -> Vec<Char> {
let font = match (style.bold, style.mono) {
(_, true) => "Mono",
(true, _) => "Serif-Bold",
_ => "Serif",
};
let mut out = Vec::new();
let mut x = x;
for ch in text.chars() {
if ch == ' ' {
out.push(Char {
ch,
bbox: Rect::new(x, base, x, base),
baseline: base,
size,
font: font.into(),
style,
generated: true,
kind: CharKind::Text,
source: Default::default(),
});
x += 0.25 * size;
continue;
}
let w = 0.5 * size;
out.push(Char {
ch,
bbox: Rect::new(x, base - 0.9 * size, x + w, base + 0.25 * size),
baseline: base,
size,
font: font.into(),
style,
generated: false,
kind: CharKind::Text,
source: Default::default(),
});
x += w;
}
out
}
fn texts(blocks: &[Block]) -> Vec<String> {
blocks
.iter()
.map(|b| {
let ls: Vec<String> = b.lines.iter().map(Line::text).collect();
ls.join(" / ")
})
.collect()
}
fn group(chars: &[Char]) -> Vec<String> {
texts(&blocks_from_chars(chars, &[]))
}
#[test]
fn spaces_and_gaps_split_words() {
let mut c = run("ab cd", 0.0, 100.0, 10.0, REGULAR);
c.extend(run("ef", 25.5, 100.0, 10.0, REGULAR));
let w: Vec<String> = words(&c).into_iter().map(|w| w.text).collect();
assert_eq!(w, ["ab", "cd", "ef"]);
}
#[test]
fn split_text_objects_without_gap_are_one_word() {
let mut c = run("Intr", 90.0, 200.0, 24.0, BOLD);
c.extend(run("odução", 90.0 + 4.0 * 12.0 - 0.4, 200.0, 24.0, BOLD));
let w = words(&c);
assert_eq!(w.len(), 1);
assert_eq!(w[0].text, "Introdução");
}
#[test]
fn decomposed_ligature_sharing_one_box_stays_in_the_word() {
let mut c = run("e", 0.0, 100.0, 10.0, REGULAR);
let lig = Rect::new(5.0, 91.0, 10.7, 102.5);
for ch in ['f', 'i'] {
let mut x = c[0].clone();
x.ch = ch;
x.bbox = lig;
c.push(x);
}
c.extend(run("ca", 10.7, 100.0, 10.0, REGULAR));
let w = words(&c);
assert_eq!(w.len(), 1);
assert_eq!(w[0].text, "efica");
}
#[test]
fn jump_back_starts_a_new_word() {
let mut c = run("abc", 50.0, 100.0, 10.0, REGULAR);
c.extend(run("de", 0.0, 100.0, 10.0, REGULAR));
assert_eq!(words(&c).len(), 2);
}
#[test]
fn style_change_without_space_is_glued() {
let mut c = run("negrito", 0.0, 100.0, 10.0, BOLD);
c.extend(run(", fim", 35.0, 100.0, 10.0, REGULAR));
let ls = lines(words(&c));
assert_eq!(ls.len(), 1);
assert_eq!(ls[0].text(), "negrito, fim");
assert!(ls[0].words[1].glued);
}
#[test]
fn superscript_stays_on_its_line() {
let mut c = run("frase.", 0.0, 100.0, 10.0, REGULAR);
c.extend(run("1", 30.5, 96.5, 7.0, REGULAR));
c.extend(run("Linha seguinte", 0.0, 112.0, 10.0, REGULAR));
let ls = lines(words(&c));
assert_eq!(ls.len(), 2);
assert_eq!(ls[0].text(), "frase. 1");
assert_eq!(ls[0].baseline, 100.0);
assert_eq!(ls[0].size, 10.0);
}
#[test]
fn wide_gap_splits_a_row_into_cells() {
let mut c = run("LaTeX", 0.0, 100.0, 10.0, REGULAR);
c.extend(run("LuaTeX", 60.0, 100.0, 10.0, REGULAR));
let ls = lines(words(&c));
let t: Vec<String> = ls.iter().map(Line::text).collect();
assert_eq!(t, ["LaTeX", "LuaTeX"]);
}
#[test]
fn lone_leading_number_keeps_its_text() {
let mut c = run("1", 0.0, 100.0, 10.0, REGULAR);
c.extend(run("Notas", 14.1, 100.0, 10.0, REGULAR));
assert_eq!(lines(words(&c)).len(), 1);
let mut c = run("LuaTeX", 0.0, 100.0, 10.0, REGULAR);
c.extend(run("4", 50.0, 100.0, 10.0, REGULAR));
c.extend(run("Tipografia", 65.0, 100.0, 10.0, REGULAR));
assert_eq!(lines(words(&c)).len(), 3);
}
#[test]
fn monospace_runs_of_spaces_do_not_split() {
let mut c = run("let", 0.0, 100.0, 10.0, MONO);
c.extend(run("=", 27.0, 100.0, 10.0, MONO));
assert_eq!(lines(words(&c)).len(), 1);
let mut c = run("let", 0.0, 100.0, 10.0, REGULAR);
c.extend(run("=", 27.0, 100.0, 10.0, REGULAR));
assert_eq!(lines(words(&c)).len(), 2);
}
#[test]
fn paragraph_lines_form_one_block_and_a_gap_separates_paragraphs() {
let mut c = Vec::new();
c.extend(run("primeira linha", 0.0, 100.0, 10.0, REGULAR));
c.extend(run("segunda linha", 0.0, 112.0, 10.0, REGULAR));
c.extend(run("fim", 0.0, 124.0, 10.0, REGULAR));
c.extend(run("outro", 0.0, 142.0, 10.0, REGULAR));
assert_eq!(group(&c), ["primeira linha / segunda linha / fim", "outro"]);
}
#[test]
fn heading_is_its_own_block_even_with_tight_spacing() {
let mut c = run("Título", 0.0, 100.0, 14.0, BOLD);
c.extend(run("corpo do texto", 0.0, 114.0, 10.0, REGULAR));
assert_eq!(group(&c), ["Título", "corpo do texto"]);
let mut c = run("Subtítulo", 0.0, 100.0, 10.0, BOLD);
c.extend(run("corpo do texto", 0.0, 112.0, 10.0, REGULAR));
assert_eq!(group(&c), ["Subtítulo", "corpo do texto"]);
}
#[test]
fn list_items_are_separate_blocks_with_hanging_continuation() {
let mut c = Vec::new();
c.extend(run("• primeiro", 10.0, 100.0, 10.0, REGULAR));
c.extend(run("• segundo item", 10.0, 112.0, 10.0, REGULAR));
c.extend(run("continua", 17.5, 124.0, 10.0, REGULAR));
c.extend(run("1. terceiro", 10.0, 136.0, 10.0, REGULAR));
assert_eq!(
group(&c),
["• primeiro", "• segundo item / continua", "1. terceiro"]
);
}
#[test]
fn first_line_indent_and_code_indentation() {
let mut c = run("recuado", 15.0, 100.0, 10.0, REGULAR);
c.extend(run("continua", 0.0, 112.0, 10.0, REGULAR));
assert_eq!(group(&c), ["recuado / continua"]);
let mut c = run("fn main() {", 0.0, 100.0, 10.0, MONO);
c.extend(run("let x = 1;", 20.0, 112.0, 10.0, MONO));
c.extend(run("}", 0.0, 124.0, 10.0, MONO));
assert_eq!(group(&c), ["fn main() { / let x = 1; / }"]);
}
#[test]
fn different_alignment_breaks_the_block() {
let mut c = run("parágrafo um", 0.0, 100.0, 10.0, REGULAR);
c.extend(run("citação recuada", 40.0, 112.0, 10.0, REGULAR));
c.extend(run("continua", 40.0, 124.0, 10.0, REGULAR));
assert_eq!(group(&c), ["parágrafo um", "citação recuada / continua"]);
}
#[test]
fn vector_bullet_becomes_a_marker() {
let mut c = run("primeiro", 20.0, 100.0, 12.0, REGULAR);
c.extend(run("segundo", 20.0, 113.5, 12.0, REGULAR));
let marks = [
Rect::new(8.0, 94.0, 11.8, 97.8),
Rect::new(8.0, 107.5, 11.8, 111.3),
];
let b = blocks_from_chars(&c, &marks);
assert_eq!(texts(&b), ["• primeiro", "• segundo"]);
let b = blocks_from_chars(&c, &[Rect::new(8.0, 96.0, 18.0, 96.8)]);
assert_eq!(texts(&b), ["primeiro / segundo"]);
}
#[test]
fn markers() {
for m in [
"•", "–", "∗", "‣", "1.", "12)", "a)", "(iv)", "iii.", "\u{F0B7}",
] {
assert!(is_marker(m), "{m}");
}
for m in ["1", "abc.", "1234.", "texto", ")", "."] {
assert!(!is_marker(m), "{m}");
}
}
#[test]
fn dominant_size_and_majority_style() {
assert_eq!(
dominant_size([(10.0, 50), (7.0, 1), (14.0, 3)].into_iter()),
10.0
);
let bold_italic = Style {
italic: true,
..BOLD
};
let s = majority_style([(REGULAR, 33), (BOLD, 16), (bold_italic, 22)].into_iter());
assert!(s.bold && !s.italic);
}
#[test]
fn loose_justified_line_in_a_column_is_not_split() {
let mut c = run("linha anterior", 0.0, 100.0, 10.0, REGULAR);
for (i, w) in ["hifenização", "é", "um", "recurso", "de"]
.iter()
.enumerate()
{
let x = [0.0, 65.0, 80.0, 100.0, 145.0][i];
c.extend(run(w, x, 112.0, 10.0, REGULAR));
}
c.extend(run("linha seguinte", 0.0, 124.0, 10.0, REGULAR));
let ws = words(&c);
let ls = lines_in(ws.clone(), Some((0.0, 155.0)));
assert_eq!(
ls.len(),
3,
"{:?}",
ls.iter().map(Line::text).collect::<Vec<_>>()
);
assert_eq!(ls[1].text(), "hifenização é um recurso de");
assert_eq!(lines(ws).len(), 7);
}
#[test]
fn running_header_spanning_the_column_is_still_split() {
let mut c = run("TABELAS", 0.0, 20.0, 10.0, REGULAR);
c.extend(run("2", 395.0, 20.0, 10.0, REGULAR));
c.extend(run("corpo do texto", 0.0, 60.0, 10.0, REGULAR));
let ls = lines_in(words(&c), Some((0.0, 400.0)));
assert_eq!(ls.len(), 3);
}
#[test]
fn table_row_with_uneven_gaps_is_still_split() {
let mut c = Vec::new();
for base in [100.0, 112.0, 124.0] {
c.extend(run("LaTeX LuaTeX", 0.0, base, 10.0, REGULAR));
c.extend(run("4", 80.0, base, 10.0, REGULAR));
c.extend(run("Tipografia clássica", 100.0, base, 10.0, REGULAR));
}
let ls = lines_in(words(&c), Some((0.0, 197.5)));
assert_eq!(ls.len(), 9);
}
#[test]
fn two_columns_from_chars_never_share_a_line_or_block() {
let left = "alfa beta gama delta épsilon zeta";
let right = "um dois três quatro cinco seis";
let mut c = Vec::new();
for r in 0..8 {
let base = 100.0 + r as f32 * 12.0;
c.extend(run(left, 0.0, base, 10.0, REGULAR));
c.extend(run(right, 160.5, base, 10.0, REGULAR));
}
let (regions, bs) = layout_from_chars(&c, &[]);
assert_eq!(regions.len(), 2);
assert_eq!(bs.len(), 2);
assert_eq!((bs[0].region, bs[1].region), (0, 1));
assert!(bs[0].bbox.right <= 152.5 && bs[1].bbox.left >= 160.5);
assert!(bs[0].lines.iter().all(|l| l.text() == left));
}
#[test]
fn running_head_is_removed_before_the_column_split() {
let left = "alfa beta gama delta épsilon zeta";
let right = "um dois três quatro cinco seis";
let pages: Vec<PagePrimitives> = ["PALAVRAS COMPOSTAS", "CONCLUSÃO"]
.iter()
.enumerate()
.map(|(i, head)| {
let mut c = run(head, 0.0, 65.0, 10.0, REGULAR);
c.extend(run(&format!("{}", i + 2), 300.0, 65.0, 10.0, REGULAR));
for r in 0..8 {
let base = 100.0 + r as f32 * 12.0;
c.extend(run(left, 0.0, base, 10.0, REGULAR));
c.extend(run(right, 160.5, base, 10.0, REGULAR));
}
PagePrimitives {
width: 320.0,
height: 400.0,
chars: c,
..Default::default()
}
})
.collect();
for p in layout_document(pages) {
assert_eq!(p.regions.len(), 2);
assert_eq!(p.blocks.len(), 2);
assert!(
p.blocks
.iter()
.all(|b| b.lines[0].text() != "PALAVRAS COMPOSTAS")
);
assert!(p.regions.iter().all(|r| r.rect.top > 90.0));
let f: Vec<(String, furniture::Reason)> = p
.furniture
.iter()
.map(|f| (f.block.lines[0].text(), f.reason))
.collect();
assert_eq!(f.len(), 2, "{f:?}");
assert_eq!(f[1].1, furniture::Reason::Repeated);
assert_eq!(f[0].1, furniture::Reason::SharedRow);
}
}
#[test]
fn garbage_input_does_not_panic() {
let mut c = run("ok", 0.0, 100.0, 10.0, REGULAR);
let mut bad = c[0].clone();
bad.size = 0.0;
c.push(bad);
let mut junk = c[0].clone();
junk.ch = '\u{FFFE}';
c.push(junk);
let _ = blocks_from_chars(&c, &[Rect::new(f32::NAN, 0.0, 1.0, 1.0)]);
assert!(blocks_from_chars(&[], &[]).is_empty());
}
}