use super::links::*;
use super::patterns::*;
use super::text::*;
use super::*;
use crate::analysis::blocks::LIST_LABEL;
use crate::analysis::lines::split_at_gaps;
use crate::analysis::page::{DocStats, PageData};
use crate::analysis::tables::extract_grid;
use crate::backend::FontInfo;
use crate::common::geom::Rect;
use crate::config::AnalyzeOptions;
use crate::model::FloatKind;
use crate::model::Line;
use crate::model::Loc;
use crate::model::*;
use std::collections::{HashMap, HashSet};
const SUPERSCRIPT: i8 = 1;
#[derive(Debug, Clone, Copy, PartialEq)]
pub struct AssembleConfig {
pub author_row_baseline_tolerance_pt: f32,
pub equation_margin_pt: f32,
pub table_cell_gap_em: f32,
pub mark_min_word_letters_count: usize,
pub note_max_pages_before: usize,
pub note_max_pages_after: usize,
pub min_target_set_count: usize,
pub cover_min_area_ratio: f32,
pub cover_max_lines_count: usize,
}
impl Default for AssembleConfig {
fn default() -> Self {
Self {
author_row_baseline_tolerance_pt: 2.0,
equation_margin_pt: 2.5,
table_cell_gap_em: 0.55,
mark_min_word_letters_count: 2,
note_max_pages_before: 1,
note_max_pages_after: 2,
min_target_set_count: 2,
cover_min_area_ratio: 0.6,
cover_max_lines_count: 12,
}
}
}
struct Assembler<'a> {
text: &'a TextBuilder<'a>,
pages: &'a [PageData],
opts: &'a AnalyzeOptions,
cfg: &'a AssembleConfig,
blocks: Vec<Block>,
anchors: HashSet<String>,
loose: Vec<Vec<PLine>>,
title_parts: Vec<String>,
eq_counter: usize,
}
struct TextContent {
kind: BlockKind,
built: Built,
rows: Vec<Vec<Span>>,
anchor: Option<String>,
}
pub(crate) fn build_document(
nodes: Vec<Node>,
pages: &[PageData],
stats: &DocStats,
fonts: &[FontInfo],
mut meta: Meta,
furniture: Vec<Vec<Line>>,
opts: AnalyzeOptions,
) -> (Document, Vec<Vec<PLine>>) {
let vocab = build_vocab(nodes.iter().filter_map(|node| match &node.kind {
NodeKind::Text(block) | NodeKind::Footnote(block) => Some(block.lines.as_slice()),
NodeKind::Float(float) => Some(float.caption.as_slice()),
_ => None,
}));
let text = TextBuilder {
fonts,
vocab: &vocab,
cfg: &opts.layout.semantics.text,
};
let mut assembler = Assembler {
text: &text,
pages,
opts: &opts,
cfg: &opts.layout.semantics.assemble,
blocks: Vec::new(),
anchors: HashSet::new(),
loose: furniture_lines(furniture, pages.len(), &text),
title_parts: Vec::new(),
eq_counter: 0,
};
for node in nodes {
assembler.push_node(node);
}
let Assembler {
mut blocks,
loose,
title_parts,
cfg,
..
} = assembler;
link_blocks(&mut blocks, cfg);
link_contents(&mut blocks);
if !title_parts.is_empty() {
meta.title = Some(title_parts.join(" ").split_whitespace().collect::<Vec<_>>().join(" "));
}
let doc = Document {
meta,
pages: pages
.iter()
.map(|page| PageInfo {
width: page.width,
height: page.height,
})
.collect(),
body_size: stats.body_size,
leading: stats.leading,
body_font: fonts
.get(stats.body_font as usize)
.map(|font| font.name.clone())
.unwrap_or_default(),
math_font: String::new(),
pictures: Vec::new(),
blocks,
};
(doc, loose)
}
pub(crate) fn count_math_glyphs(counts: &mut HashMap<u16, usize>, lines: &[Line], fonts: &[FontInfo]) {
for glyph in lines.iter().flat_map(|line| &line.glyphs) {
if fonts.get(glyph.font as usize).is_some_and(|font| font.math) {
*counts.entry(glyph.font).or_default() += 1;
}
}
}
pub(crate) fn main_math_font(counts: &HashMap<u16, usize>, fonts: &[FontInfo]) -> String {
counts
.iter()
.map(|(&font, &count)| (font, count))
.max_by_key(|&(font, count)| (count, std::cmp::Reverse(font)))
.and_then(|(font, _)| fonts.get(font as usize))
.map(|font| font.name.clone())
.unwrap_or_default()
}
pub(crate) fn is_footnote_symbol(text: &str) -> bool {
matches!(text, "∗" | "†" | "‡" | "§" | "¶" | "*")
}
impl Assembler<'_> {
fn push_node(&mut self, node: Node) {
let id = self.blocks.len();
let loc = node.loc;
let block = match node.kind {
NodeKind::Text(text_block) => {
let bbox = lines_bbox(&text_block.lines);
let content = self.text_content(node.class, &text_block.lines, node.strip_prefix);
let mut block = block_with_text(id, content.kind, loc, bbox, content.built);
block.rows = content.rows;
block.anchor = content.anchor;
block.lines = text_block.lines;
block
}
NodeKind::Footnote(text_block) => self.footnote_block(id, loc, text_block),
NodeKind::Equation(equation) => self.equation_block(id, loc, equation),
NodeKind::Float(float) => self.float_block(id, loc, float),
};
self.blocks.push(block);
}
fn unique_anchor(&mut self, base: String) -> String {
unique_anchor(&mut self.anchors, base)
}
fn text_content(&mut self, class: Class, lines: &[Line], strip_prefix: usize) -> TextContent {
let mut rows = Vec::new();
let mut anchor = None;
let (kind, built) = match class {
Class::Title => {
let built = self.text.build(lines, 0, BOLD);
self.title_parts.push(spans_text(&built.spans));
(BlockKind::Title, built)
}
Class::Authors => {
rows = self.author_rows(lines);
(BlockKind::Authors, self.text.build(lines, 0, 0))
}
Class::Note => (BlockKind::Note, self.text.build(lines, 0, 0)),
Class::Heading { level, number } => {
let built = self.text.build(lines, 0, BOLD);
let base = match &number {
Some(num) => format!("sec-{num}"),
None => format!("sec-{}", slug(&spans_text(&built.spans))),
};
anchor = Some(self.unique_anchor(base));
(BlockKind::Heading { level }, built)
}
Class::ListItem { bullet } => {
let built = self.text.build(lines, if bullet { 1 } else { 0 }, 0);
let marker = if bullet {
None
} else {
let text = spans_text(&built.spans);
LIST_LABEL.find(&text).map(|label| label.as_str().trim().to_string())
};
(BlockKind::ListItem { marker, level: 0 }, built)
}
Class::ListContinuation => (BlockKind::ListContinuation, self.text.build(lines, 0, 0)),
Class::Reference => {
let built = self.text.build(lines, 0, 0);
let label = reference_label(&spans_text(&built.spans));
if let Some(label) = &label {
anchor = Some(self.unique_anchor(format!("ref-{}", slug(label))));
}
(BlockKind::Reference { label }, built)
}
Class::Paragraph { in_abstract } => {
let mut built = self.text.build(lines, 0, 0);
if strip_prefix > 0 {
strip_chars(&mut built.spans, strip_prefix);
}
(BlockKind::Paragraph { in_abstract }, built)
}
Class::Code => {
let mut built = self.text.build(lines, 0, 0);
rows = super::code::code_rows(lines, self.text.fonts);
built.spans = rows.join(&Span::plain("\n"));
(BlockKind::Code, built)
}
Class::ContentsEntry { level, page } => {
let mut built = self.text.build(lines, 0, 0);
super::contents::strip_page_label(&mut built.spans, &page);
(BlockKind::ContentsEntry { level, page }, built)
}
Class::Unknown => (
BlockKind::Paragraph { in_abstract: false },
self.text.build(lines, 0, 0),
),
};
TextContent {
kind,
built,
rows,
anchor,
}
}
fn author_rows(&self, lines: &[Line]) -> Vec<Vec<Span>> {
let mut rows: Vec<Vec<Span>> = Vec::new();
let mut last_baseline = f32::NEG_INFINITY;
for line in lines {
let mut spans = self.text.line_spans(line);
if (line.baseline - last_baseline).abs() < self.cfg.author_row_baseline_tolerance_pt && !rows.is_empty() {
let row: &mut Vec<Span> = rows.last_mut().unwrap();
row.push(Span::plain("\u{2003}"));
row.append(&mut spans);
} else {
rows.push(spans);
}
last_baseline = line.baseline;
}
rows
}
fn footnote_block(&mut self, id: usize, loc: Loc, text_block: TextBlock) -> Block {
let bbox = lines_bbox(&text_block.lines);
let first = &text_block.lines[0];
let mut skip = first
.glyphs
.iter()
.take_while(|glyph| glyph.script == SUPERSCRIPT)
.count();
if skip == 0
&& first
.glyphs
.first()
.is_some_and(|glyph| is_footnote_symbol(&glyph.text))
{
skip = 1;
}
let mut dropped = 0;
if skip == 0 {
let digits = first
.glyphs
.iter()
.take_while(|glyph| glyph.text.chars().all(|ch| ch.is_ascii_digit()) && !glyph.text.is_empty())
.count();
if digits > 0 && first.glyphs.get(digits).is_some_and(|glyph| glyph.text == ".") {
skip = digits;
dropped = 1;
}
}
if skip == 0
&& first
.glyphs
.first()
.is_some_and(|glyph| matches!(glyph.text.as_str(), "•" | "▪"))
{
dropped = 1;
}
let marker: String = first.glyphs[..skip].iter().map(|glyph| glyph.text.as_str()).collect();
let built = self.text.build(&text_block.lines, skip + dropped, 0);
let anchor = (!marker.is_empty()).then(|| self.unique_anchor(format!("fn-{}", slug_marker(&marker))));
let mut block = block_with_text(id, BlockKind::Footnote { marker }, loc, bbox, built);
block.anchor = anchor;
block.lines = text_block.lines;
block
}
fn equation_block(&mut self, id: usize, loc: Loc, equation: EquationBlock) -> Block {
let mut lines = equation.lines;
lines.sort_by(|a, b| a.baseline.total_cmp(&b.baseline).then(a.bbox.x0.total_cmp(&b.bbox.x0)));
let read = |line: &Line| {
if line.glyphs.iter().any(LineGlyph::is_fraction_term) {
self.text
.line_spans(line)
.iter()
.map(|span| span.text.as_str())
.collect::<String>()
} else {
line.text()
}
};
let alt = lines.iter().map(read).collect::<Vec<_>>().join(" ");
let margin = self.cfg.equation_margin_pt;
let rect = equation
.bbox
.inflate(margin, margin)
.intersect(&self.pages[loc.page].rect());
let anchor = match &equation.number {
Some(num) => Some(self.unique_anchor(format!("eq-{}", num.trim_matches(['(', ')'])))),
None => {
self.eq_counter += 1;
Some(self.unique_anchor(format!("eq-u{}", self.eq_counter)))
}
};
if let Some(line) = equation.number_line {
let spans = self.text.line_spans(&line);
self.loose[loc.page].push(PLine {
line,
spans,
kind: "eqno",
});
}
let image = ImageSpec::region(loc.page, rect, true);
let kind = BlockKind::Equation {
image: Some(image),
number: equation.number,
};
let mut block = new_block(id, kind, loc, rect);
block.spans = vec![Span::plain(alt)];
block.line_texts = lines.iter().map(|line| line.text()).collect();
block.eq_runs = self.text.eq_runs(&lines);
block.anchor = anchor;
block.lines = lines;
block
}
fn cover_region(&self, page: usize, rect: Rect) -> Rect {
let Some(data) = self.pages.get(page) else { return rect };
let edge = page == 0 || page + 1 == self.pages.len();
let page_rect = Rect::new(0.0, 0.0, data.width, data.height);
if edge
&& self.pages.len() > 1
&& data.line_count() <= self.cfg.cover_max_lines_count
&& rect.area() >= self.cfg.cover_min_area_ratio * page_rect.area()
{
page_rect
} else {
rect
}
}
fn float_block(&mut self, id: usize, loc: Loc, float: Float) -> Block {
let built = self.text.build(&float.caption, 0, 0);
let anchor = float.label.as_ref().map(|label| {
let num = label.rsplit(' ').next().unwrap_or("");
let prefix = match float.kind {
FloatKind::Table => "tab",
FloatKind::Algorithm => "alg",
_ => "fig",
};
self.unique_anchor(format!("{prefix}-{num}"))
});
let mut rows = Vec::new();
if !float.inner_text.is_empty() {
rows.push(vec![Span::plain(float.inner_text.clone())]);
}
let table = self.float_table(&float);
let region = float.region.map(|rect| self.cover_region(float.page, rect));
let kind = BlockKind::Figure {
kind: float.kind,
image: region.map(|rect| ImageSpec::region(float.page, rect, false)),
label: float.label.clone(),
};
let mut block = block_with_text(id, kind, loc, float.bbox, built);
block.rows = rows;
block.anchor = anchor;
block.lines = float.caption;
block.inner_spans = float
.inner_lines
.iter()
.map(|line| self.text.line_spans(line))
.collect();
block.inner_lines = float.inner_lines;
block.table = table;
block
}
fn float_table(&self, float: &Float) -> Option<Table> {
let tabular = float.kind == FloatKind::Table || (float.kind == FloatKind::Graphic && float.table_like);
match float.region {
Some(region) if self.opts.tables && tabular && !float.complex => {
let pieces: Vec<Line> = float
.inner_lines
.iter()
.flat_map(|line| {
split_at_gaps(line, self.cfg.table_cell_gap_em * line.size, &self.opts.layout.lines)
})
.collect();
extract_grid(
region,
&pieces,
&float.hrules,
&float.vrules,
&self.opts.layout.tables,
&self.opts.layout.lines,
)
.map(|grid| self.text.table(grid))
}
_ => None,
}
}
}
fn furniture_lines(furniture: Vec<Vec<Line>>, n_pages: usize, text: &TextBuilder<'_>) -> Vec<Vec<PLine>> {
let mut loose: Vec<Vec<PLine>> = vec![Vec::new(); n_pages];
for (page_idx, lines) in furniture.into_iter().enumerate() {
for line in lines {
let spans = text.line_spans(&line);
loose[page_idx].push(PLine {
line,
spans,
kind: "header",
});
}
}
loose
}
fn new_block(id: usize, kind: BlockKind, loc: Loc, bbox: Rect) -> Block {
Block {
page: loc.page,
bbox,
loc,
..Block::new(id, kind)
}
}
fn block_with_text(id: usize, kind: BlockKind, loc: Loc, bbox: Rect, built: Built) -> Block {
let mut block = new_block(id, kind, loc, bbox);
block.spans = built.spans;
block.line_texts = built.line_texts;
block.hlines = built.hlines;
block
}
fn lines_bbox(lines: &[Line]) -> Rect {
lines.iter().fold(Rect::EMPTY, |bbox, line| bbox.union(&line.bbox))
}
fn spans_text(spans: &[Span]) -> String {
spans.iter().map(|span| span.text.as_str()).collect()
}
pub(crate) fn reference_label(text: &str) -> Option<String> {
REF_LABEL
.captures(text.trim())
.map(|captures| captures.name("a").or(captures.name("b")).unwrap().as_str().to_string())
}
pub(crate) fn slug_marker(marker: &str) -> String {
marker
.chars()
.map(|ch| match ch {
'∗' | '*' => "star".to_string(),
'†' => "dagger".to_string(),
'‡' => "ddagger".to_string(),
'§' => "sect".to_string(),
'¶' => "para".to_string(),
ch if ch.is_alphanumeric() => ch.to_string(),
_ => "x".to_string(),
})
.collect()
}
pub(crate) fn link_blocks(blocks: &mut [Block], cfg: &AssembleConfig) {
let targets = LinkTargets::new(
blocks
.iter()
.enumerate()
.filter_map(|(index, block)| block.anchor.as_deref().map(|anchor| (index, anchor))),
cfg.min_target_set_count,
);
let notes: Vec<(String, usize, usize, String)> = blocks
.iter()
.enumerate()
.filter_map(|(idx, block)| match (&block.kind, &block.anchor) {
(BlockKind::Footnote { marker }, Some(anchor)) if marker.chars().all(|ch| ch.is_ascii_digit()) => {
Some((marker.clone(), block.page, idx, anchor.clone()))
}
_ => None,
})
.collect();
for (index, block) in blocks.iter_mut().enumerate() {
let linkable = !matches!(
block.kind,
BlockKind::Equation { .. } | BlockKind::Title | BlockKind::Heading { .. }
);
if linkable {
link_cross_references(block, &targets, index);
}
if !matches!(block.kind, BlockKind::Footnote { .. }) {
let page = block.page;
let note_for = |mark: &str| {
notes
.iter()
.filter(|(marker, note_page, ..)| {
marker == mark
&& *note_page + cfg.note_max_pages_before >= page
&& *note_page <= page + cfg.note_max_pages_after
})
.min_by_key(|(_, note_page, note_idx, _)| {
(*note_page < page, note_page.abs_diff(page), note_idx.abs_diff(index))
})
.map(|(.., anchor)| anchor.clone())
};
link_footnote_marks(&mut block.spans, ¬e_for, cfg);
}
}
}
pub(crate) fn link_contents(blocks: &mut [Block]) {
let headings: Vec<(usize, String)> = blocks
.iter()
.enumerate()
.filter(|(_, block)| matches!(block.kind, BlockKind::Heading { .. }) && block.anchor.is_some())
.map(|(idx, block)| (idx, super::contents::title_key(&spans_text(&block.spans))))
.collect();
let mut from = 0;
for idx in 0..blocks.len() {
if !matches!(blocks[idx].kind, BlockKind::ContentsEntry { .. }) {
continue;
}
let key = super::contents::title_key(&spans_text(&blocks[idx].spans));
if key.is_empty() {
continue;
}
let found = headings[from..]
.iter()
.position(|(heading, heading_key)| *heading > idx && *heading_key == key);
if let Some(pos) = found {
let anchor = blocks[headings[from + pos].0].anchor.clone();
from += pos + 1;
for span in &mut blocks[idx].spans {
if span.href.is_none() {
span.href = anchor.as_ref().map(|anchor| format!("#{anchor}"));
}
}
}
}
}
fn link_cross_references(block: &mut Block, targets: &LinkTargets, at: usize) {
let own = block.anchor.clone();
let spans = std::mem::take(&mut block.spans);
block.spans = link_spans(spans, targets, at, own.as_deref());
let rows = std::mem::take(&mut block.rows);
block.rows = rows.into_iter().map(|row| link_spans(row, targets, at, None)).collect();
for hline in block.hlines.iter_mut() {
let spans = std::mem::take(&mut hline.spans);
hline.spans = link_spans(spans, targets, at, own.as_deref());
}
if let Some(table) = block.table.as_mut() {
for cell in table.rows.iter_mut().flatten() {
let spans = std::mem::take(&mut cell.spans);
cell.spans = link_spans(spans, targets, at, None);
}
}
}
fn link_footnote_marks(spans: &mut [Span], note_for: &dyn Fn(&str) -> Option<String>, cfg: &AssembleConfig) {
for i in 0..spans.len() {
let span = &spans[i];
if span.style & SUP != 0 && span.style & MATH == 0 && span.href.is_none() {
let exponent = is_exponent(spans, i, cfg);
if let (false, Some(anchor)) = (exponent, note_for(span.text.trim())) {
spans[i].href = Some(format!("#{anchor}"));
}
}
}
}
fn is_exponent(spans: &[Span], i: usize, cfg: &AssembleConfig) -> bool {
i == 0 || spans[i - 1].style & SUP != 0 || {
let prev = spans[i - 1].text.trim_end();
let run = prev.chars().rev().take_while(|ch| ch.is_alphabetic()).count();
match prev.chars().last() {
Some(ch) if ch.is_ascii_digit() => true,
Some(')' | ']' | '}') => true,
Some(ch) if ch.is_alphabetic() => run < cfg.mark_min_word_letters_count,
Some(_) => false,
None => true,
}
}
}