use crate::common::geom::Rect;
use crate::model::{Block, BlockKind, Document, Line, LineGlyph, PLine, Span};
const TOUCH_PT: f32 = 0.6;
const TRIM_GAP_PT: f32 = 0.3;
const FIGURE_TRIM_MAX_PT: f32 = 8.0;
#[derive(Debug, Clone)]
pub struct Cut {
pub page: usize,
pub block: usize,
pub kind: &'static str,
pub glyphs: usize,
pub rect: Rect,
pub examples: Vec<String>,
}
fn cuts(rect: &Rect, ink: &Rect) -> bool {
let overlap = rect.intersect(ink);
!overlap.is_unset()
&& overlap.width() > TOUCH_PT
&& overlap.height() > TOUCH_PT
&& !rect.inflate(TOUCH_PT, TOUCH_PT).contains(ink)
}
fn inks(lines: &[Line]) -> impl Iterator<Item = Rect> + '_ {
lines
.iter()
.flat_map(|line| line.glyphs.iter())
.filter(|glyph| !glyph.text.trim().is_empty() && !glyph.ink.is_unset())
.map(|glyph| glyph.ink)
}
struct PageBlocks {
touching: Vec<Vec<usize>>,
on: Vec<Vec<usize>>,
}
impl PageBlocks {
fn new(doc: &Document) -> Self {
let mut touching: Vec<Vec<usize>> = vec![Vec::new(); doc.pages.len()];
let mut on: Vec<Vec<usize>> = vec![Vec::new(); doc.pages.len()];
for (idx, block) in doc.blocks.iter().enumerate() {
if let Some(list) = on.get_mut(block.page) {
list.push(idx);
}
for line in block.lines.iter().chain(&block.inner_lines) {
if let Some(list) = touching.get_mut(line.page)
&& list.last() != Some(&idx)
{
list.push(idx);
}
}
}
Self { touching, on }
}
}
fn page_glyphs_with<T>(
doc: &Document,
loose: &[Vec<PLine>],
blocks: &PageBlocks,
page: usize,
extra: impl Fn(&LineGlyph) -> T,
) -> Vec<(Rect, Option<usize>, T)> {
let mut out = Vec::new();
let mut push = |line: &Line, owner: Option<usize>| {
out.extend(
line.glyphs
.iter()
.filter(|glyph| !glyph.text.trim().is_empty() && !glyph.ink.is_unset())
.map(|glyph| (glyph.ink, owner, extra(glyph))),
);
};
for &idx in &blocks.touching[page] {
let block = &doc.blocks[idx];
let caption_owner = if matches!(block.kind, BlockKind::Figure { .. }) {
None
} else {
Some(idx)
};
let own = block.lines.iter().map(|line| (line, caption_owner));
let inner = block.inner_lines.iter().map(|line| (line, Some(idx)));
for (line, owner) in own.chain(inner).filter(|(line, _)| line.page == page) {
push(line, owner);
}
}
if let Some(lines) = loose.get(page) {
for pline in lines.iter().filter(|pline| pline.kind != "eqno") {
push(&pline.line, None);
}
}
out
}
fn page_glyphs(doc: &Document, loose: &[Vec<PLine>], blocks: &PageBlocks, page: usize) -> Vec<(Rect, Option<usize>)> {
page_glyphs_with(doc, loose, blocks, page, |_| ())
.into_iter()
.map(|(ink, owner, ())| (ink, owner))
.collect()
}
fn block_kind_name(kind: &BlockKind) -> &'static str {
match kind {
BlockKind::Equation { .. } => "equation",
BlockKind::Figure { .. } => "figure",
BlockKind::Paragraph { .. } => "paragraph",
BlockKind::Heading { .. } => "heading",
BlockKind::Footnote { .. } => "footnote",
_ => "other",
}
}
fn picture(block: &Block) -> Option<(Rect, &'static str)> {
match &block.kind {
BlockKind::Equation { image, .. } => Some((image.rect, "equation")),
BlockKind::Figure { image: Some(image), .. } if block.table.is_none() => Some((image.rect, "figure")),
_ => None,
}
}
pub fn cut_glyphs(doc: &Document, loose: &[Vec<PLine>]) -> Vec<Cut> {
let mut out = Vec::new();
let blocks = PageBlocks::new(doc);
for page in 0..doc.pages.len() {
let glyphs = page_glyphs_with(doc, loose, &blocks, page, |glyph| glyph.text.clone());
for &idx in &blocks.on[page] {
let block = &doc.blocks[idx];
let Some((rect, kind)) = picture(block) else { continue };
let cut: Vec<&(Rect, Option<usize>, String)> = glyphs
.iter()
.filter(|(ink, owner, _)| *owner != Some(idx) && cuts(&rect, ink))
.collect();
if !cut.is_empty() {
let examples = cut
.iter()
.take(6)
.map(|(ink, owner, text)| {
let of = owner.map_or("loose", |other| block_kind_name(&doc.blocks[other].kind));
format!("{text}@{:.0},{:.0}({of})", ink.x0, ink.y0)
})
.collect();
out.push(Cut {
page,
block: idx,
kind,
glyphs: cut.len(),
rect,
examples,
});
}
}
}
out
}
fn own_ink(block: &Block) -> Rect {
inks(&block.lines).fold(Rect::EMPTY, |acc, ink| acc.union(&ink))
}
fn set_region(block: &mut Block, rect: Rect) {
if let BlockKind::Equation { image, .. } = &mut block.kind {
image.rect = rect;
}
block.bbox = rect;
}
pub(crate) fn fit_equation_crops(doc: &mut Document, loose: &[Vec<PLine>]) {
let mut merged = false;
let mut blocks = PageBlocks::new(doc);
for page in 0..doc.pages.len() {
while let Some((keep, absorb)) = overlapping_equations(doc, loose, &blocks, page) {
merge_equations(doc, keep, absorb);
merged = true;
blocks = PageBlocks::new(doc);
}
trim_regions(doc, loose, &blocks, page);
}
if merged {
for (id, block) in doc.blocks.iter_mut().enumerate() {
block.id = id;
}
single_column_zones(doc);
}
}
fn single_column_zones(doc: &mut Document) {
let mut used: std::collections::HashSet<(usize, usize)> = std::collections::HashSet::new();
for block in &doc.blocks {
if block.loc.zone_cols > 1 && block.loc.col > 0 {
used.insert((block.loc.page, block.loc.zone));
}
}
for block in doc.blocks.iter_mut() {
if block.loc.zone_cols > 1 && !used.contains(&(block.loc.page, block.loc.zone)) {
block.loc.zone_cols = 1;
block.loc.col = 0;
}
}
}
fn overlapping_equations(
doc: &Document,
loose: &[Vec<PLine>],
blocks: &PageBlocks,
page: usize,
) -> Option<(usize, usize)> {
let glyphs = page_glyphs(doc, loose, blocks, page);
let is_eq = |idx: usize| matches!(doc.blocks[idx].kind, BlockKind::Equation { .. });
for &idx in &blocks.on[page] {
let block = &doc.blocks[idx];
let BlockKind::Equation { image, .. } = &block.kind else {
continue;
};
let own = own_ink(block);
for (ink, owner) in &glyphs {
let Some(other) = *owner else { continue };
if other == idx || !is_eq(other) {
continue;
}
let overlap = image.rect.intersect(ink);
let reaches = !overlap.is_unset() && overlap.width() > TOUCH_PT && overlap.height() > TOUCH_PT;
let into_ink = !own.intersect(ink).is_unset() || cuts(&image.rect, ink);
if reaches && into_ink {
return Some((idx.min(other), idx.max(other)));
}
}
}
None
}
fn merge_equations(doc: &mut Document, keep: usize, absorb: usize) {
let gone = doc.blocks.remove(absorb);
let block = &mut doc.blocks[keep];
let (gone_rect, gone_number) = match gone.kind {
BlockKind::Equation { image, number } => (image.rect, number),
_ => return,
};
let rect = block.bbox.union(&gone_rect);
if let BlockKind::Equation { number, .. } = &mut block.kind
&& number.is_none()
&& gone_number.is_some()
{
*number = gone_number;
if gone.anchor.is_some() {
block.anchor = gone.anchor;
}
}
block.lines.extend(gone.lines);
block
.lines
.sort_by(|a, b| a.baseline.total_cmp(&b.baseline).then(a.bbox.x0.total_cmp(&b.bbox.x0)));
block.line_texts = block.lines.iter().map(|line| line.text()).collect();
block.spans = vec![Span::plain(block.line_texts.join(" "))];
block.eq_runs.extend(gone.eq_runs);
set_region(block, rect);
}
fn trim_regions(doc: &mut Document, loose: &[Vec<PLine>], blocks: &PageBlocks, page: usize) {
let glyphs = page_glyphs(doc, loose, blocks, page);
for &idx in &blocks.on[page] {
let block = &doc.blocks[idx];
if matches!(block.kind, BlockKind::Figure { .. }) {
trim_figure(&mut doc.blocks[idx], idx, &glyphs);
continue;
}
let BlockKind::Equation { image, .. } = &block.kind else {
continue;
};
let own = own_ink(block);
if own.is_unset() {
continue;
}
let mut rect = image.rect.union(&own);
for (ink, owner) in &glyphs {
if *owner == Some(idx) || !cuts(&rect, ink) {
continue;
}
if ink.y1 <= own.y0 {
rect.y0 = rect.y0.max(ink.y1 + TRIM_GAP_PT).min(own.y0);
} else if ink.y0 >= own.y1 {
rect.y1 = rect.y1.min(ink.y0 - TRIM_GAP_PT).max(own.y1);
} else if ink.x1 <= own.x0 {
rect.x0 = rect.x0.max(ink.x1 + TRIM_GAP_PT).min(own.x0);
} else if ink.x0 >= own.x1 {
rect.x1 = rect.x1.min(ink.x0 - TRIM_GAP_PT).max(own.x1);
}
}
set_region(&mut doc.blocks[idx], rect);
}
}
fn trim_figure(block: &mut Block, idx: usize, glyphs: &[(Rect, Option<usize>)]) {
let BlockKind::Figure { image: Some(image), .. } = &mut block.kind else {
return;
};
if block.table.is_some() {
return;
}
let mut rect = image.rect;
for (ink, owner) in glyphs {
if *owner == Some(idx) || !cuts(&rect, ink) {
continue;
}
let depths = [
ink.y1 - rect.y0, rect.y1 - ink.y0, ink.x1 - rect.x0, rect.x1 - ink.x0, ];
let (edge, depth) = depths
.iter()
.enumerate()
.min_by(|a, b| a.1.total_cmp(b.1))
.map(|(edge, depth)| (edge, *depth))
.unwrap();
if depth > FIGURE_TRIM_MAX_PT {
continue;
}
match edge {
0 => rect.y0 = ink.y1 + TRIM_GAP_PT,
1 => rect.y1 = ink.y0 - TRIM_GAP_PT,
2 => rect.x0 = ink.x1 + TRIM_GAP_PT,
_ => rect.x1 = ink.x0 - TRIM_GAP_PT,
}
}
if rect.width() > 1.0 && rect.height() > 1.0 {
image.rect = rect;
}
}