pub mod cmr10; pub mod math; pub mod paragraph; pub mod pdf; pub mod render; pub mod tfm; pub use cmr10::Cmr10Metrics; pub use paragraph::{ HorizontalBox, HorizontalItem, Paragraph, ParagraphFont, ParagraphStyle, layout_items, layout_paragraph, layout_paragraph_with_font, text_items, text_items_with_font, }; pub use render::{DisplayItem, DisplayList}; use std::collections::hash_map::DefaultHasher; use std::hash::{Hash, Hasher}; pub type UnitId = u64; #[derive(Clone, Debug, PartialEq, Eq, Hash, serde::Serialize, serde::Deserialize)] pub struct VerticalBox { pub width: i64, pub height: i64, } #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, serde::Serialize, serde::Deserialize)] pub enum CellAlignment { Left, Center, Right, } #[derive(Clone, Debug, PartialEq, Eq, Hash, serde::Serialize, serde::Deserialize)] pub struct HalignCell { pub text: String, pub span: usize, pub alignment: CellAlignment, } #[derive(Clone, Debug, PartialEq, Eq, Hash, serde::Serialize, serde::Deserialize)] pub struct HalignRow { pub cells: Vec, pub rule: bool, } /// A laid-out `\halign` table: natural column widths plus row rules. #[derive(Clone, Debug, PartialEq, Eq, Hash, serde::Serialize, serde::Deserialize)] pub struct Halign { pub rows: Vec, pub column_widths: Vec, pub width: i64, pub height: i64, pub line_height: i64, } #[derive(Clone, Debug, PartialEq, Eq, Hash, serde::Serialize, serde::Deserialize)] pub enum VerticalItem { Box(VerticalBox), Rule { width: i64, height: i64, }, Glue(i64), Penalty(i64), Insertion(Insertion), Mark(Mark), Float(Float), Halign(Halign), Paragraph(Paragraph), Math { atom: crate::math::MathAtom, width: i64, height: i64, depth: i64, }, } impl Halign { /// Split a tall table at row boundaries so each chunk fits `max_height`. /// /// Column widths are preserved so the fragments still line up when the /// page builder places them on consecutive pages. pub fn split_for_height(&self, max_height: i64) -> Vec { if self.rows.is_empty() { return vec![self.clone()]; } let max_height = max_height.max(self.line_height); let mut chunks = Vec::new(); let mut start = 0_usize; let mut height = 0_i64; for (index, row) in self.rows.iter().enumerate() { let row_height = if row.rule { 26_214 } else { self.line_height }; if index > start && height + row_height > max_height { chunks.push(Self { rows: self.rows[start..index].to_vec(), column_widths: self.column_widths.clone(), width: self.width, height, line_height: self.line_height, }); start = index; height = 0; } height += row_height; } chunks.push(Self { rows: self.rows[start..].to_vec(), column_widths: self.column_widths.clone(), width: self.width, height, line_height: self.line_height, }); chunks } /// The horizontal rectangle occupied by a cell's text: `(x, width)`. /// /// Spanned cells include the intercolumn gaps they cover. The x offset is /// the aligned start inside that rectangle. pub fn cell_box(&self, row_index: usize, cell_index: usize) -> Option<(i64, i64)> { let row = self.rows.get(row_index)?; let cell = row.cells.get(cell_index)?; let mut column = 0_usize; for previous in &row.cells[..cell_index] { column += previous.span.max(1); } let span = cell .span .max(1) .min(self.column_widths.len().saturating_sub(column)); if span == 0 { return None; } let intercolumn = if self.column_widths.len() > 1 { (self.width - self.column_widths.iter().copied().sum::()) / (self.column_widths.len() as i64 - 1) } else { 0 }; let gaps = intercolumn * (span.saturating_sub(1) as i64); let width = self.column_widths[column..column + span] .iter() .sum::() + gaps; let x: i64 = self.column_widths[..column].iter().sum::() + intercolumn * column as i64; let text_width = cell .text .chars() .map(|character| { if character.is_whitespace() { 4 * 65_536 } else { 10 * 65_536 } }) .sum::(); let offset = match cell.alignment { CellAlignment::Left => 0, CellAlignment::Center => (width - text_width).max(0) / 2, CellAlignment::Right => (width - text_width).max(0), }; Some((x + offset, width)) } } /// Vertical material reserved at the bottom of a page (footnotes etc.). #[derive(Clone, Debug, PartialEq, Eq, Hash, serde::Serialize, serde::Deserialize)] pub struct Insertion { pub class: u8, pub height: i64, pub items: Vec, } /// Running mark material for headers and footers. #[derive(Clone, Debug, PartialEq, Eq, Hash, serde::Serialize, serde::Deserialize)] pub struct Mark { pub class: u8, pub text: String, } #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, serde::Serialize, serde::Deserialize)] pub enum FloatPlacement { Top, Bottom, } /// Deferred float material. Only top placement is implemented so far. #[derive(Clone, Debug, PartialEq, Eq, Hash, serde::Serialize, serde::Deserialize)] pub struct Float { pub placement: FloatPlacement, pub width: i64, pub height: i64, /// Vertical material carried by the float. Empty for a dimension-only float. #[serde(default)] pub content: Vec, } impl Float { /// Natural height of the float's vertical material. pub fn content_height(&self) -> i64 { self.content .iter() .map(|item| match item { VerticalItem::Box(box_) => box_.height, VerticalItem::Rule { height, .. } => *height, VerticalItem::Glue(height) => *height, VerticalItem::Halign(halign) => halign.height, VerticalItem::Paragraph(paragraph) => paragraph.height, VerticalItem::Math { height, depth, .. } => height + depth, _ => 0, }) .sum() } } #[derive(Clone, Debug, PartialEq, Eq, serde::Serialize, serde::Deserialize)] pub struct Unit { pub id: UnitId, pub source: String, pub items: Vec, /// Present when this unit was built from text and can be re-flowed by /// []. Structural units (halign, floats, insertions) are not /// editable through a plain source string. #[serde(default)] pub paragraph_style: Option, } impl Unit { /// Build a simple `\halign` table with natural column widths. pub fn halign(id: UnitId, rows: Vec, column_count: usize, intercolumn: i64) -> Self { let intercolumn = intercolumn.saturating_mul(65_536); let mut column_widths = vec![0_i64; column_count]; for row in &rows { let mut column = 0_usize; for cell in &row.cells { let span = cell.span.max(1).min(column_count.saturating_sub(column)); if span == 1 { let width: i64 = cell .text .chars() .map(|character| { if character.is_whitespace() { 4 * 65_536 } else { 10 * 65_536 } }) .sum(); if let Some(slot) = column_widths.get_mut(column) { *slot = (*slot).max(width); } } column += span; } } for row in &rows { let mut column = 0_usize; for cell in &row.cells { let span = cell.span.max(1).min(column_count.saturating_sub(column)); if span > 1 { let gaps = intercolumn * (span.saturating_sub(1) as i64); let available: i64 = column_widths[column..column + span] .iter() .copied() .sum::() + gaps; let needed: i64 = cell.text.chars().count() as i64 * 10 * 65_536; let extra = (needed - available).max(0); for offset in 0..span { column_widths[column + offset] += extra / span as i64; } } column += span; } } let gaps = intercolumn * column_count.saturating_sub(1) as i64; let width = column_widths.iter().sum::() + gaps; let line_height = 12 * 65_536; let rule_height = 26_214; // 0.4pt let height = rows .iter() .map(|row| if row.rule { rule_height } else { line_height }) .sum(); Self { id, source: "halign".to_owned(), paragraph_style: None, items: vec![VerticalItem::Halign(Halign { rows, column_widths, width, height, line_height, })], } } /// Parse a small TeX-like halign body with an `l`/`c`/`r` column template. pub fn halign_from_source( id: UnitId, source: &str, column_count: usize, intercolumn: i64, ) -> Self { let template = "l".repeat(column_count.max(1)); Self::halign_from_source_with_template(id, &template, source, intercolumn) } /// Parse an `l`/`c`/`r` column template plus a halign body. pub fn halign_from_source_with_template( id: UnitId, template: &str, source: &str, intercolumn: i64, ) -> Self { let alignments: Vec = template .chars() .map(|character| match character { 'c' => CellAlignment::Center, 'r' => CellAlignment::Right, _ => CellAlignment::Left, }) .collect(); let column_count = alignments.len().max(1); let mut rows = Vec::new(); for raw_row in source.split(r"\\") { if raw_row.trim().is_empty() { continue; } let mut raw_row = raw_row.trim(); if let Some(rest) = raw_row.strip_prefix(r"\noalign") { let rest = rest.trim_start(); if let Some(body) = rest.strip_prefix('{') { if let Some((_, tail)) = body.split_once('}') { raw_row = tail.trim(); } } } let mut rule = false; if let Some(rest) = raw_row.strip_prefix(r"\hline") { rule = true; raw_row = rest.trim(); } if rule { rows.push(HalignRow { cells: Vec::new(), rule: true, }); } if raw_row.is_empty() { continue; } let mut cells = Vec::new(); for raw_cell in raw_row.split('&') { let mut text = raw_cell.trim().to_owned(); let mut span = 1; if let Some(rest) = text.strip_prefix(r"\span") { span = 2; text = rest.trim().to_owned(); } if let Some(rest) = text.strip_prefix(r"\multispan") { let rest = rest.trim_start(); if let Some(body) = rest.strip_prefix('{') { if let Some((count, tail)) = body.split_once('}') { span = count.trim().parse().unwrap_or(1).max(1); text = tail.trim().to_owned(); } } } if let Some(rest) = text.strip_prefix(r"\omit") { text = rest.trim().to_owned(); } let column: usize = cells.iter().map(|cell: &HalignCell| cell.span.max(1)).sum(); cells.push(HalignCell { text, span, alignment: alignments .get(column) .copied() .unwrap_or(CellAlignment::Left), }); } rows.push(HalignRow { cells, rule: false }); } Self::halign(id, rows, column_count, intercolumn) } /// A running mark item, recorded on the page where it is shipped out. pub fn mark(id: UnitId, class: u8, text: &str) -> Self { Self::vertical( id, vec![VerticalItem::Mark(Mark { class, text: text.to_owned(), })], ) } /// A top/bottom float item. pub fn float(id: UnitId, placement: FloatPlacement, width: i64, height: i64) -> Self { Self::vertical( id, vec![VerticalItem::Float(Float { placement, width, height, content: Vec::new(), })], ) } /// Build a float that carries vertical material. pub fn float_with_content( id: UnitId, placement: FloatPlacement, width: i64, height: i64, content: Vec, ) -> Self { let mut unit = Self::float(id, placement, width, height); if let Some(VerticalItem::Float(float)) = unit.items.first_mut() { float.content = content; float.height = float.height.max(float.content_height()); } unit } /// A vertical penalty item, corresponding to `\penalty`. pub fn penalty(id: UnitId, value: i64) -> Self { Self::vertical(id, vec![VerticalItem::Penalty(value)]) } /// A vertical glue item, corresponding to `\vskip`. pub fn vskip(id: UnitId, height: i64) -> Self { Self::vertical(id, vec![VerticalItem::Glue(height)]) } /// A filled rule in the vertical list. pub fn rule(id: UnitId, width: i64, height: i64) -> Self { Self::vertical(id, vec![VerticalItem::Rule { width, height }]) } /// M1 paragraph builder: box/glue/penalty item stream with a /// Knuth-Plass-style word-level line breaker. pub fn paragraph(id: UnitId, source: impl Into) -> Self { Self::paragraph_with_style(id, source, ParagraphStyle::default()) } /// Build a paragraph unit with an explicit font face. pub fn paragraph_with_face(id: UnitId, source: impl Into, font: ParagraphFont) -> Self { let mut unit = Self::paragraph_with_style(id, source, ParagraphStyle::default()); if let Some(VerticalItem::Paragraph(paragraph)) = unit.items.first_mut() { paragraph.font = font; } unit } pub fn paragraph_with_style( id: UnitId, source: impl Into, style: ParagraphStyle, ) -> Self { let source = source.into(); let paragraph = layout_paragraph_with_font(&source, &style, &crate::cmr10::Cmr10Metrics::new()); Self { id, source, items: vec![VerticalItem::Paragraph(paragraph)], paragraph_style: Some(style), } } /// Build a unit from a math atom using CMR10 metrics. pub fn math( id: UnitId, atom: crate::math::MathAtom, font: &crate::cmr10::Cmr10Metrics, ) -> Self { let math_box = math::layout_math(&atom, font); Self::vertical( id, vec![VerticalItem::Math { atom, width: math_box.width, height: math_box.height, depth: math_box.depth, }], ) } /// Build a unit from arbitrary vertical material. pub fn vertical(id: UnitId, items: Vec) -> Self { Self { id, source: String::new(), items, paragraph_style: None, } } /// Build a page insertion (footnote/float material) with reserved height. pub fn insertion(id: UnitId, class: u8, height: i64, items: Vec) -> Self { Self::vertical( id, vec![VerticalItem::Insertion(Insertion { class, height, items, })], ) } } /// A TeX insertion class (`\insert` class) and its maximum share of the /// page. A value of 100 means the insertion may use the whole page. #[derive(Clone, Debug, PartialEq, Eq, serde::Serialize, serde::Deserialize)] pub struct InsertionClass { pub number: u8, pub fraction_percent: u8, } #[derive(Clone, Debug, PartialEq, Eq, serde::Serialize, serde::Deserialize)] pub struct Document { pub units: Vec, pub page_goal: i64, /// TeX-like `\topskip`: distance from the page top to the first baseline. #[serde(default)] pub top_skip: i64, /// Minimum percentage of the page that text must occupy before a bottom /// float is allowed onto the page (TeX's `\textfraction`, in percent). #[serde(default = "default_text_fraction")] pub text_fraction_percent: u8, /// `\floatpagefraction` equivalent for dedicated float pages. pub float_page_fraction_percent: u8, /// Maximum percentage of a page that bottom floats may occupy (TeX's /// `\bottomfraction`, in percent). #[serde(default = "default_bottom_fraction")] pub bottom_fraction_percent: u8, /// Maximum percentage of a text page that top floats may occupy (TeX's /// `\topfraction`, in percent). #[serde(default = "default_top_fraction")] pub top_fraction_percent: u8, /// Per-class insertion limits. Missing classes use the full page. #[serde(default)] pub insertion_classes: Vec, } fn default_text_fraction() -> u8 { 50 } fn default_bottom_fraction() -> u8 { 30 } fn default_top_fraction() -> u8 { 70 } impl Document { pub fn new(page_goal: i64, units: Vec) -> Self { Self { units, page_goal, top_skip: 0, text_fraction_percent: default_text_fraction(), float_page_fraction_percent: 50, bottom_fraction_percent: default_bottom_fraction(), top_fraction_percent: default_top_fraction(), insertion_classes: Vec::new(), } } /// Maximum height available to one insertion class on a page. pub fn insertion_class_limit(&self, class: u8) -> i64 { self.insertion_classes .iter() .find(|entry| entry.number == class) .map_or(self.page_goal, |entry| { self.page_goal * i64::from(entry.fraction_percent) / 100 }) } pub fn with_top_skip(mut self, top_skip: i64) -> Self { self.top_skip = top_skip; self } } #[derive(Clone, Debug, PartialEq, Eq, serde::Serialize, serde::Deserialize)] pub struct Page { pub items: Vec, #[serde(default)] pub insertions: Vec, #[serde(default)] pub marks: Vec, #[serde(default)] pub floats: Vec, pub sources: Vec<(UnitId, u64)>, pub hash: u64, } impl Page { fn empty() -> Self { Self { items: Vec::new(), insertions: Vec::new(), marks: Vec::new(), floats: Vec::new(), sources: Vec::new(), hash: 0, } } fn seal_in_place(&mut self) { let mut hasher = DefaultHasher::new(); self.items.hash(&mut hasher); self.insertions.hash(&mut hasher); self.marks.hash(&mut hasher); self.floats.hash(&mut hasher); self.hash = hasher.finish(); } } fn source_hash(source: &str) -> u64 { let mut hasher = DefaultHasher::new(); source.hash(&mut hasher); hasher.finish() } fn item_height(item: &VerticalItem) -> i64 { match item { VerticalItem::Box(vertical_box) => vertical_box.height, VerticalItem::Rule { height, .. } => *height, VerticalItem::Glue(amount) => (*amount).max(0), VerticalItem::Insertion(insertion) => insertion.height, VerticalItem::Float(float) => float.height, VerticalItem::Halign(halign) => halign.height, VerticalItem::Paragraph(paragraph) => paragraph.height, VerticalItem::Math { height, depth, .. } => height + depth, VerticalItem::Mark(_) | VerticalItem::Penalty(_) => 0, } } fn top_float_height(page: &Page) -> i64 { page.floats .iter() .filter(|float| float.placement == FloatPlacement::Top) .map(|float| float.height) .sum() } fn bottom_float_height(page: &Page) -> i64 { page.floats .iter() .filter(|float| float.placement == FloatPlacement::Bottom) .map(|float| float.height) .sum() } /// TeX `\topfraction`: a top float taller than this share of the page keeps /// the rest of the page free of body text. fn top_float_exceeds_page_fraction(page: &Page, page_goal: i64, percent: u8) -> bool { let height = top_float_height(page); height > 0 && page.items.is_empty() && height * 100 > i64::from(percent) * page_goal } #[derive(Clone, Debug, PartialEq, Eq, serde::Serialize, serde::Deserialize)] pub struct Checkpoint { /// Index of the next unit to execute. pub unit_index: usize, /// Number of completed pages. pub page_index: usize, /// Vertical space already used on the current page. pub used: i64, /// Page items already emitted on the current page. pub page_items: Vec, /// Insertions already attached to the current page. #[serde(default)] pub page_insertions: Vec, /// Total insertion height already reserved on the current page. #[serde(default)] pub insertion_height: i64, /// Running marks already collected on the current page. #[serde(default)] pub page_marks: Vec, /// Floats already attached to the current page. #[serde(default)] pub page_floats: Vec, } #[derive(Clone, Debug, PartialEq, Eq, serde::Serialize, serde::Deserialize)] pub struct Layout { pub pages: Vec, /// `checkpoints[i]` is the state before executing unit `i`. pub checkpoints: Vec, /// Number of pages whose content had to be rebuilt by the last edit. pub recomputed_pages: usize, /// Page indices whose sealed hash changed in the last edit. pub changed_pages: Vec, } impl Layout { pub fn page_index_for(&self, unit_index: usize) -> Option { self.checkpoints.get(unit_index).map(|c| c.page_index) } } /// Shipout hook corresponding to TeX's `\output` stage. /// /// This is deliberately small: the routine can inspect and mutate each /// assembled page (and later change page styles) but it is Rust code rather /// than an interpreted token list. pub trait OutputRoutine { fn shipout(&mut self, page: &mut Page, page_number: usize); /// TeX's output routine may decide to ship a page before it is full. /// This hook is consulted between units, so a return of `true` seals the /// current non-empty page and starts the next one. fn wants_break(&mut self, _page: &Page, _used: i64, _page_goal: i64) -> bool { false } } pub struct NoOutput; impl OutputRoutine for NoOutput { fn shipout(&mut self, _page: &mut Page, _page_number: usize) {} } pub struct Engine { layout: Layout, } impl Engine { pub fn layout(document: &Document) -> Self { Self::layout_with_output(document, &mut NoOutput) } pub fn layout_with_output(document: &Document, output: &mut impl OutputRoutine) -> Self { let mut pages = Vec::new(); let mut checkpoints = Vec::with_capacity(document.units.len()); let mut current = Page::empty(); let mut used = 0_i64; let mut insertion_height = 0_i64; for (unit_index, unit) in document.units.iter().enumerate() { if !current.items.is_empty() && output.wants_break(¤t, used, document.page_goal) { output.shipout(&mut current, pages.len() + 1); pages.push(std::mem::replace(&mut current, Page::empty())); used = document.top_skip; insertion_height = 0; } checkpoints.push(Checkpoint { unit_index, page_index: pages.len(), used, page_items: current.items.clone(), page_insertions: current.insertions.clone(), insertion_height, page_marks: current.marks.clone(), page_floats: current.floats.clone(), }); for item in &unit.items { if !matches!( item, VerticalItem::Float(_) | VerticalItem::Penalty(_) | VerticalItem::Mark(_) | VerticalItem::Insertion(_) ) && current.items.is_empty() && !current.floats.is_empty() && document.page_goal - used < document.float_page_fraction_percent as i64 * document.page_goal / 100 { pages.push(std::mem::replace(&mut current, Page::empty())); used = document.top_skip; insertion_height = 0; } match item { VerticalItem::Rule { height, .. } => { if top_float_exceeds_page_fraction( ¤t, document.page_goal, document.top_fraction_percent, ) { pages.push(std::mem::replace(&mut current, Page::empty())); used = document.top_skip; insertion_height = 0; } if current.items.is_empty() { used = document.top_skip.max(*height); } else if used + *height > document.page_goal - insertion_height - bottom_float_height(¤t) { pages.push(std::mem::replace(&mut current, Page::empty())); used = document.top_skip.max(*height); insertion_height = 0; } else { used += *height; } current.items.push(item.clone()); } VerticalItem::Box(vertical_box) => { if top_float_exceeds_page_fraction( ¤t, document.page_goal, document.top_fraction_percent, ) { pages.push(std::mem::replace(&mut current, Page::empty())); used = document.top_skip; insertion_height = 0; } if current.items.is_empty() && top_float_height(¤t) == 0 { used = document.top_skip.max(vertical_box.height); } else if used + vertical_box.height > document.page_goal - insertion_height - bottom_float_height(¤t) { pages.push(std::mem::replace(&mut current, Page::empty())); used = document.top_skip.max(vertical_box.height); insertion_height = 0; } else { used += vertical_box.height; } current.items.push(item.clone()); } VerticalItem::Halign(halign) => { let mut available = if current.items.is_empty() { document.page_goal - document.top_skip } else { document.page_goal - used - insertion_height - bottom_float_height(¤t) }; if !current.items.is_empty() && available < halign.line_height { pages.push(std::mem::replace(&mut current, Page::empty())); used = document.top_skip; insertion_height = 0; available = document.page_goal - document.top_skip; } let chunks = halign.split_for_height(available.max(halign.line_height)); for (index, chunk) in chunks.iter().enumerate() { if index > 0 { pages.push(std::mem::replace(&mut current, Page::empty())); used = document.top_skip; insertion_height = 0; } if current.items.is_empty() && top_float_height(¤t) == 0 { used = document.top_skip.max(chunk.height); } else { used += chunk.height; } current.items.push(VerticalItem::Halign(chunk.clone())); } } VerticalItem::Paragraph(paragraph) => { if top_float_exceeds_page_fraction( ¤t, document.page_goal, document.top_fraction_percent, ) { pages.push(std::mem::replace(&mut current, Page::empty())); used = document.top_skip; insertion_height = 0; } if current.items.is_empty() && top_float_height(¤t) == 0 { used = document.top_skip.max(paragraph.height); } else if used + paragraph.height > document.page_goal - insertion_height - bottom_float_height(¤t) { pages.push(std::mem::replace(&mut current, Page::empty())); used = document.top_skip.max(paragraph.height); insertion_height = 0; } else { used += paragraph.height; } current.items.push(item.clone()); } VerticalItem::Math { height, depth, .. } => { if top_float_exceeds_page_fraction( ¤t, document.page_goal, document.top_fraction_percent, ) { pages.push(std::mem::replace(&mut current, Page::empty())); used = document.top_skip; insertion_height = 0; } let amount = height + depth; if current.items.is_empty() && top_float_height(¤t) == 0 { used = document.top_skip.max(amount); } else if used + amount > document.page_goal - insertion_height - bottom_float_height(¤t) { pages.push(std::mem::replace(&mut current, Page::empty())); used = document.top_skip.max(amount); insertion_height = 0; } else { used += amount; } current.items.push(item.clone()); } VerticalItem::Glue(amount) => { if !current.items.is_empty() { used += amount; current.items.push(item.clone()); } } VerticalItem::Penalty(penalty) => { if *penalty <= -10_000 && !current.items.is_empty() { pages.push(std::mem::replace(&mut current, Page::empty())); used = document.top_skip; insertion_height = 0; } } VerticalItem::Insertion(insertion) => { let class_limit = document .insertion_class_limit(insertion.class) .min(document.page_goal.saturating_sub(document.top_skip)) .max(1); let class_height: i64 = current .insertions .iter() .filter(|entry| entry.class == insertion.class) .map(|entry| entry.height) .sum(); if (class_height + insertion.height > class_limit || insertion.height > class_limit) && !insertion.items.is_empty() { if !current.items.is_empty() || !current.insertions.is_empty() { pages.push(std::mem::replace(&mut current, Page::empty())); used = document.top_skip; insertion_height = 0; } let mut chunk = Vec::new(); let mut chunk_height = 0; for sub_item in &insertion.items { let sub_height = item_height(sub_item); if chunk_height + sub_height > class_limit && !chunk.is_empty() { current.insertions.push(Insertion { class: insertion.class, height: chunk_height, items: std::mem::take(&mut chunk), }); insertion_height = chunk_height; chunk_height = 0; pages.push(std::mem::replace(&mut current, Page::empty())); used = document.top_skip; } chunk.push(sub_item.clone()); chunk_height += sub_height; } if !chunk.is_empty() { current.insertions.push(Insertion { class: insertion.class, height: chunk_height, items: chunk, }); insertion_height = chunk_height; } } else { let goal = document.page_goal - insertion_height; if (!current.items.is_empty() || !current.insertions.is_empty()) && (used + insertion.height > goal || class_height + insertion.height > class_limit) { pages.push(std::mem::replace(&mut current, Page::empty())); used = document.top_skip; insertion_height = 0; } insertion_height += insertion.height; current.insertions.push(insertion.clone()); } } VerticalItem::Mark(mark) => { current.marks.push(mark.clone()); } VerticalItem::Float(float) => { if float.placement == FloatPlacement::Top { if !current.items.is_empty() || !current.insertions.is_empty() { pages.push(std::mem::replace(&mut current, Page::empty())); used = document.top_skip; insertion_height = 0; } if current.items.is_empty() { used = used.max(document.top_skip); } used += float.height; current.floats.push(float.clone()); } else if !current.items.is_empty() && used + float.height <= document.page_goal - insertion_height - bottom_float_height(¤t) && (used - document.top_skip - bottom_float_height(¤t)) * 100 >= document.text_fraction_percent as i64 * document.page_goal && (float.height + bottom_float_height(¤t)) * 100 <= document.bottom_fraction_percent as i64 * document.page_goal { current.floats.push(float.clone()); } else { pages.push(std::mem::replace(&mut current, Page::empty())); used = document.top_skip; insertion_height = 0; current.floats.push(float.clone()); } } } } } if !current.items.is_empty() || !current.insertions.is_empty() || !current.floats.is_empty() { pages.push(current); } for (index, unit) in document.units.iter().enumerate() { if let Some(checkpoint) = checkpoints.get(index) && let Some(page) = pages.get_mut(checkpoint.page_index) { page.sources.push((unit.id, source_hash(&unit.source))); } } for (index, page) in pages.iter_mut().enumerate() { output.shipout(page, index + 1); page.seal_in_place(); } let pages_len = pages.len(); Self { layout: Layout { pages, checkpoints, recomputed_pages: 0, changed_pages: (0..pages_len).collect(), }, } } pub fn pages(&self) -> &[Page] { &self.layout.pages } pub fn checkpoints(&self) -> &[Checkpoint] { &self.layout.checkpoints } pub fn recomputed_pages(&self) -> usize { self.layout.recomputed_pages } /// Page indices whose sealed hash changed during the last edit. pub fn changed_pages(&self) -> &[usize] { &self.layout.changed_pages } pub fn edit(&mut self, document: &Document, unit_id: UnitId, source: impl Into) { let Some(unit_index) = document.units.iter().position(|unit| unit.id == unit_id) else { self.layout = Self::layout(document).layout; self.layout.recomputed_pages = self.layout.pages.len(); self.layout.changed_pages = (0..self.layout.pages.len()).collect(); return; }; let mut next = document.clone(); let source = source.into(); let Some(style) = next.units[unit_index].paragraph_style.clone() else { next.units[unit_index].source = source; return; }; next.units[unit_index] = Unit::paragraph_with_style(unit_id, source, style); let mut checkpoint = self.layout .checkpoints .get(unit_index) .cloned() .unwrap_or(Checkpoint { unit_index, page_index: 0, used: 0, page_items: Vec::new(), page_insertions: Vec::new(), insertion_height: 0, page_marks: Vec::new(), page_floats: Vec::new(), }); let edited_height: i64 = next.units[unit_index] .items .iter() .map(|item| match item { VerticalItem::Box(vertical_box) => vertical_box.height, VerticalItem::Rule { height, .. } => *height, VerticalItem::Glue(height) => *height, VerticalItem::Penalty(_) => 0, VerticalItem::Insertion(insertion) => insertion.height, VerticalItem::Mark(_) => 0, VerticalItem::Float(float) => float.height, VerticalItem::Halign(halign) => halign.height, VerticalItem::Paragraph(paragraph) => paragraph.height, VerticalItem::Math { height, depth, .. } => height + depth, }) .sum(); if checkpoint.used + edited_height > next.page_goal && !checkpoint.page_items.is_empty() { checkpoint.page_index += 1; checkpoint.used = 0; checkpoint.page_items.clear(); } let old_pages = self.layout.pages.clone(); let mut pages = old_pages[..checkpoint.page_index].to_vec(); let mut current = Page { items: checkpoint.page_items, insertions: checkpoint.page_insertions, marks: checkpoint.page_marks, floats: checkpoint.page_floats, sources: Vec::new(), hash: 0, }; let mut used = checkpoint.used; let mut insertion_height = checkpoint.insertion_height; let mut checkpoints = self.layout.checkpoints[..unit_index].to_vec(); for (index, unit) in next.units.iter().enumerate().skip(unit_index) { checkpoints.push(Checkpoint { unit_index: index, page_index: pages.len(), used, page_items: current.items.clone(), page_insertions: current.insertions.clone(), insertion_height, page_marks: current.marks.clone(), page_floats: current.floats.clone(), }); for item in &unit.items { if !matches!( item, VerticalItem::Float(_) | VerticalItem::Penalty(_) | VerticalItem::Mark(_) | VerticalItem::Insertion(_) ) && current.items.is_empty() && !current.floats.is_empty() && document.page_goal - used < document.text_fraction_percent as i64 * document.page_goal / 100 { pages.push(std::mem::replace(&mut current, Page::empty())); used = document.top_skip; insertion_height = 0; } match item { VerticalItem::Rule { height, .. } => { if top_float_exceeds_page_fraction( ¤t, next.page_goal, next.top_fraction_percent, ) { pages.push(std::mem::replace(&mut current, Page::empty())); used = next.top_skip; insertion_height = 0; } if current.items.is_empty() { used = next.top_skip.max(*height); } else if used + *height > next.page_goal - insertion_height - bottom_float_height(¤t) { pages.push(std::mem::replace(&mut current, Page::empty())); used = next.top_skip.max(*height); insertion_height = 0; } else { used += *height; } current.items.push(item.clone()); } VerticalItem::Box(vertical_box) => { if top_float_exceeds_page_fraction( ¤t, next.page_goal, next.top_fraction_percent, ) { pages.push(std::mem::replace(&mut current, Page::empty())); used = next.top_skip; insertion_height = 0; } if current.items.is_empty() && top_float_height(¤t) == 0 { used = next.top_skip.max(vertical_box.height); } else if used + vertical_box.height > next.page_goal - insertion_height - bottom_float_height(¤t) { pages.push(std::mem::replace(&mut current, Page::empty())); used = next.top_skip.max(vertical_box.height); insertion_height = 0; } else { used += vertical_box.height; } current.items.push(item.clone()); } VerticalItem::Halign(halign) => { if current.items.is_empty() && top_float_height(¤t) == 0 { used = next.top_skip.max(halign.height); } else if used + halign.height > next.page_goal - insertion_height - bottom_float_height(¤t) { pages.push(std::mem::replace(&mut current, Page::empty())); used = next.top_skip.max(halign.height); insertion_height = 0; } else { used += halign.height; } current.items.push(item.clone()); } VerticalItem::Paragraph(paragraph) => { if top_float_exceeds_page_fraction( ¤t, next.page_goal, next.top_fraction_percent, ) { pages.push(std::mem::replace(&mut current, Page::empty())); used = next.top_skip; insertion_height = 0; } if current.items.is_empty() && top_float_height(¤t) == 0 { used = next.top_skip.max(paragraph.height); } else if used + paragraph.height > next.page_goal - insertion_height - bottom_float_height(¤t) { pages.push(std::mem::replace(&mut current, Page::empty())); used = next.top_skip.max(paragraph.height); insertion_height = 0; } else { used += paragraph.height; } current.items.push(item.clone()); } VerticalItem::Math { height, depth, .. } => { let amount = height + depth; if top_float_exceeds_page_fraction( ¤t, next.page_goal, next.top_fraction_percent, ) { pages.push(std::mem::replace(&mut current, Page::empty())); used = next.top_skip; insertion_height = 0; } if current.items.is_empty() && top_float_height(¤t) == 0 { used = next.top_skip.max(amount); } else if used + amount > next.page_goal - insertion_height - bottom_float_height(¤t) { pages.push(std::mem::replace(&mut current, Page::empty())); used = next.top_skip.max(amount); insertion_height = 0; } else { used += amount; } current.items.push(item.clone()); } VerticalItem::Glue(amount) => { if !current.items.is_empty() { used += amount; current.items.push(item.clone()); } } VerticalItem::Penalty(penalty) => { if *penalty <= -10_000 && !current.items.is_empty() { pages.push(std::mem::replace(&mut current, Page::empty())); used = next.top_skip; insertion_height = 0; } } VerticalItem::Insertion(insertion) => { let goal = next.page_goal - insertion_height; if !current.items.is_empty() && used + insertion.height > goal { pages.push(std::mem::replace(&mut current, Page::empty())); used = next.top_skip; insertion_height = 0; } insertion_height += insertion.height; current.insertions.push(insertion.clone()); } VerticalItem::Mark(mark) => { current.marks.push(mark.clone()); } VerticalItem::Float(float) => { if float.placement == FloatPlacement::Top { if !current.items.is_empty() || !current.insertions.is_empty() { pages.push(std::mem::replace(&mut current, Page::empty())); used = next.top_skip; insertion_height = 0; } used += float.height; current.floats.push(float.clone()); } else if !current.items.is_empty() && used + float.height <= next.page_goal - insertion_height - bottom_float_height(¤t) && (used - next.top_skip - bottom_float_height(¤t)) * 100 >= next.text_fraction_percent as i64 * next.page_goal && (float.height + bottom_float_height(¤t)) * 100 <= next.bottom_fraction_percent as i64 * next.page_goal { current.floats.push(float.clone()); } else { pages.push(std::mem::replace(&mut current, Page::empty())); used = document.top_skip; insertion_height = 0; current.floats.push(float.clone()); } } } } } if !current.items.is_empty() || !current.insertions.is_empty() || !current.floats.is_empty() { pages.push(current); } for page in &mut pages { page.sources.clear(); } for (index, unit) in next.units.iter().enumerate() { if let Some(checkpoint) = checkpoints.get(index) && let Some(page) = pages.get_mut(checkpoint.page_index) { page.sources.push((unit.id, source_hash(&unit.source))); } } for page in &mut pages { page.seal_in_place(); } let mut rebuilt = 0; for (index, page) in pages.iter().enumerate().skip(checkpoint.page_index) { if old_pages.get(index).is_none_or(|old| old.hash != page.hash) { rebuilt += 1; } } let changed_pages = (checkpoint.page_index..pages.len()) .filter(|index| { old_pages .get(*index) .is_none_or(|old| old.hash != pages[*index].hash) }) .collect(); self.layout = Layout { pages, checkpoints, recomputed_pages: rebuilt, changed_pages, }; } } #[cfg(test)] mod tests { use super::*; fn document() -> Document { Document::new( 50, vec![ Unit::paragraph(1, "a"), Unit::paragraph(2, "b"), Unit::paragraph(3, "c"), Unit::paragraph(4, "d"), ], ) } #[test] fn layout_splits_pages_and_records_checkpoints() { let engine = Engine::layout(&document()); assert_eq!(engine.pages().len(), 1); assert_eq!(engine.checkpoints().len(), 4); assert_eq!(engine.checkpoints()[1].unit_index, 1); } #[test] fn edit_on_second_page_only_rebuilds_second_page() { let mut document = document(); document.units.push(Unit::paragraph(5, "e")); document.units.push(Unit::paragraph(6, "f")); let mut engine = Engine::layout(&document); assert!(engine.pages().len() >= 2); engine.edit(&document, 5, "edited second page"); assert_eq!(engine.recomputed_pages(), 1); assert_eq!(engine.changed_pages(), &[1]); } #[test] fn edit_on_first_page_rebuilds_following_pages() { let mut engine = Engine::layout(&document()); engine.edit(&document(), 1, "edited first page"); assert!(engine.recomputed_pages() >= 1); } #[test] fn insertions_reserve_space_at_the_page_bottom() { let unit = Unit { id: 7, source: "footnote layout".to_owned(), paragraph_style: None, items: vec![ VerticalItem::Insertion(Insertion { class: 0, height: 30, items: vec![VerticalItem::Box(VerticalBox { width: 20, height: 30, })], }), VerticalItem::Box(VerticalBox { width: 10, height: 40, }), VerticalItem::Box(VerticalBox { width: 10, height: 40, }), ], }; let result = Engine::layout(&Document::new(100, vec![unit])); assert_eq!(result.layout.pages.len(), 2); assert_eq!(result.layout.pages[0].insertions.len(), 1); assert_eq!(result.layout.pages[0].items.len(), 1); assert_eq!(result.layout.pages[1].insertions.len(), 0); } #[test] fn output_routine_can_force_an_early_page_break() { struct BreakAfterTwo { shipped: usize, } impl OutputRoutine for BreakAfterTwo { fn shipout(&mut self, _page: &mut Page, _page_number: usize) { self.shipped += 1; } fn wants_break(&mut self, page: &Page, _used: i64, _page_goal: i64) -> bool { self.shipped == 0 && page.items.len() >= 2 } } let units = (0..4) .map(|index| Unit { id: index, source: String::new(), paragraph_style: None, items: vec![VerticalItem::Box(VerticalBox { width: 10, height: 10, })], }) .collect(); let document = Document::new(30, units); let mut output = BreakAfterTwo { shipped: 0 }; let engine = Engine::layout_with_output(&document, &mut output); assert_eq!(engine.pages().len(), 2); assert_eq!(engine.pages()[0].items.len(), 2); assert_eq!(engine.pages()[1].items.len(), 2); assert!(output.shipped >= 1); } #[test] fn top_skip_sets_the_first_baseline_distance() { let unit = |id| Unit { id, source: "boxes".to_owned(), paragraph_style: None, items: vec![ VerticalItem::Box(VerticalBox { width: 10, height: 2, }), VerticalItem::Box(VerticalBox { width: 10, height: 30, }), VerticalItem::Box(VerticalBox { width: 10, height: 30, }), VerticalItem::Box(VerticalBox { width: 10, height: 30, }), ], }; let plain = Engine::layout(&Document::new(95, vec![unit(0)])); assert_eq!(plain.layout.pages.len(), 1); let with_top_skip = Engine::layout(&Document::new(95, vec![unit(1)]).with_top_skip(10)); assert_eq!(with_top_skip.layout.pages.len(), 2); } #[test] fn editing_keeps_earlier_page_sources_stable() { let mut document = Document::new( 100, vec![ Unit::paragraph(1, "a ".repeat(20)), Unit::vertical(2, vec![VerticalItem::Penalty(-10_000)]), Unit::paragraph(3, "b ".repeat(200)), ], ); let mut engine = Engine::layout(&document); let before = engine.pages()[0].hash; engine.edit(&document, 3, "c ".repeat(200)); assert_eq!(engine.pages()[0].hash, before); document.units[2].source = "c ".repeat(200); } #[test] fn vertical_penalty_can_force_a_page_break() { let unit = Unit { id: 0, source: "penalty".to_owned(), paragraph_style: None, items: vec![ VerticalItem::Box(VerticalBox { width: 10, height: 10, }), VerticalItem::Penalty(-10_000), VerticalItem::Box(VerticalBox { width: 10, height: 10, }), ], }; let engine = Engine::layout(&Document::new(100, vec![unit])); assert_eq!(engine.layout.pages.len(), 2); assert_eq!(engine.layout.pages[0].items.len(), 1); assert_eq!(engine.layout.pages[1].items.len(), 1); } #[test] fn marks_are_attached_to_pages_and_affect_the_hash() { let document = |text: &str| { Document::new( 100, vec![Unit { id: 0, source: text.to_owned(), paragraph_style: None, items: vec![ VerticalItem::Box(VerticalBox { width: 10, height: 10, }), VerticalItem::Mark(Mark { class: 0, text: text.to_owned(), }), VerticalItem::Penalty(-10_000), VerticalItem::Box(VerticalBox { width: 10, height: 10, }), ], }], ) }; let first = Engine::layout(&document("even page")); let second = Engine::layout(&document("odd page")); assert_eq!(first.layout.pages[0].marks[0].text, "even page"); assert_ne!( first.layout.pages[0].hash, second.layout.pages[0].hash, "running marks must participate in the page hash" ); } struct PageStamp { numbers: Vec, } impl OutputRoutine for PageStamp { fn shipout(&mut self, page: &mut Page, page_number: usize) { self.numbers.push(page_number); page.marks.push(Mark { class: 9, text: format!("page {page_number}"), }); } } #[test] fn output_routine_sees_and_mutates_each_page() { let mut stamp = PageStamp { numbers: Vec::new(), }; let engine = Engine::layout_with_output(&document(), &mut stamp); assert_eq!(stamp.numbers.len(), engine.layout.pages.len()); assert_eq!(stamp.numbers[0], 1); assert_eq!(engine.layout.pages[0].marks[0].text, "page 1"); } #[test] fn top_float_starts_a_new_page_when_it_arrives_late() { let unit = Unit { id: 0, source: "float".to_owned(), paragraph_style: None, items: vec![ VerticalItem::Box(VerticalBox { width: 10, height: 10, }), VerticalItem::Float(Float { placement: FloatPlacement::Top, width: 40, height: 20, content: Vec::new(), }), VerticalItem::Box(VerticalBox { width: 10, height: 10, }), ], }; let engine = Engine::layout(&Document::new(100, vec![unit])); assert_eq!(engine.layout.pages.len(), 2); assert_eq!(engine.layout.pages[0].items.len(), 1); assert_eq!(engine.layout.pages[1].floats.len(), 1); assert_eq!(engine.layout.pages[1].items.len(), 1); } #[test] fn float_page_fraction_can_keep_body_and_float_together() { let mut document = Document::new( 100, vec![ Unit::float(1, FloatPlacement::Top, 10, 50), Unit::vertical( 2, vec![VerticalItem::Box(VerticalBox { width: 10, height: 10, })], ), ], ); document.float_page_fraction_percent = 60; document.text_fraction_percent = 10; assert_eq!(Engine::layout(&document).pages().len(), 2); document.float_page_fraction_percent = 10; assert_eq!(Engine::layout(&document).pages().len(), 1); } #[test] fn insertion_class_limit_ships_the_overflow_to_the_next_page() { let rule = VerticalItem::Rule { width: 65_536, height: 200, }; let mut document = Document::new( 1000, vec![ Unit::insertion(1, 1, 200, vec![rule.clone()]), Unit::insertion(2, 1, 200, vec![rule]), ], ); document.insertion_classes = vec![InsertionClass { number: 1, fraction_percent: 30, }]; let layout = Engine::layout(&document); assert_eq!(layout.pages().len(), 2); assert_eq!(layout.pages()[0].insertions.len(), 1); assert_eq!(layout.pages()[1].insertions.len(), 1); } #[test] fn a_large_top_float_gets_a_float_page() { let mut document = Document::new(100, Vec::new()); document.top_skip = 0; document.units.push(Unit::float_with_content( 1, FloatPlacement::Top, 50, 60, vec![VerticalItem::Rule { width: 50, height: 60, }], )); document.units.push(Unit::vertical( 2, vec![VerticalItem::Box(VerticalBox { width: 10, height: 10, })], )); let engine = Engine::layout(&document); assert_eq!(engine.pages().len(), 2); assert!(engine.pages()[0].items.is_empty()); assert_eq!(engine.pages()[0].floats.len(), 1); } #[test] fn text_fraction_keeps_a_bottom_float_off_a_mostly_empty_page() { let mut document = Document::new( 100, vec![ Unit::vertical( 1, vec![VerticalItem::Box(VerticalBox { width: 10, height: 10, })], ), Unit::float(2, FloatPlacement::Bottom, 10, 50), ], ); document.top_skip = 0; document.text_fraction_percent = 50; let engine = Engine::layout(&document); assert_eq!(engine.pages().len(), 2); assert!(engine.pages()[0].floats.is_empty()); assert_eq!(engine.pages()[1].floats.len(), 1); } #[test] fn bottom_float_reserves_space_on_its_page() { let unit = Unit { id: 0, source: "bottom float".to_owned(), paragraph_style: None, items: vec![ VerticalItem::Box(VerticalBox { width: 10, height: 30, }), VerticalItem::Float(Float { placement: FloatPlacement::Bottom, width: 40, height: 30, content: Vec::new(), }), VerticalItem::Box(VerticalBox { width: 10, height: 30, }), ], }; let mut document = Document::new(60, vec![unit]); document.bottom_fraction_percent = 100; let engine = Engine::layout(&document); assert_eq!(engine.layout.pages.len(), 2); assert_eq!(engine.layout.pages[0].floats.len(), 1); assert_eq!(engine.layout.pages[0].items.len(), 1); assert_eq!(engine.layout.pages[1].items.len(), 1); } #[test] fn bottom_fraction_moves_a_tall_float_to_the_next_page() { let unit = Unit { id: 0, source: "tall bottom float".to_owned(), paragraph_style: None, items: vec![ VerticalItem::Box(VerticalBox { width: 10, height: 80, }), VerticalItem::Float(Float { placement: FloatPlacement::Bottom, width: 40, height: 50, content: Vec::new(), }), ], }; let document = Document::new(100, vec![unit]); let engine = Engine::layout(&document); assert_eq!( engine.layout.pages.len(), 2, "50% bottom float exceeds 30% limit" ); assert!(engine.layout.pages[0].floats.is_empty()); assert_eq!(engine.layout.pages[1].floats.len(), 1); } #[test] fn top_fraction_moves_body_off_a_tall_top_float() { let unit = Unit { id: 0, source: "top fraction".to_owned(), paragraph_style: None, items: vec![ VerticalItem::Float(Float { placement: FloatPlacement::Top, width: 40, height: 80, content: Vec::new(), }), VerticalItem::Box(VerticalBox { width: 10, height: 5, }), ], }; let mut document = Document::new(100, vec![unit]); document.top_skip = 0; document.float_page_fraction_percent = 10; let engine = Engine::layout(&document); assert_eq!( engine.layout.pages.len(), 2, "80% top float exceeds 70% limit" ); assert_eq!(engine.layout.pages[0].floats.len(), 1); assert!(engine.layout.pages[0].items.is_empty()); assert_eq!(engine.layout.pages[1].items.len(), 1); document.top_fraction_percent = 100; let engine = Engine::layout(&document); assert_eq!(engine.layout.pages.len(), 1); assert_eq!(engine.layout.pages[0].floats.len(), 1); assert_eq!(engine.layout.pages[0].items.len(), 1); } #[test] fn edited_layout_respects_top_fraction() { let document = { let mut document = Document::new( 100, vec![ Unit::float(0, FloatPlacement::Top, 40, 80), Unit::paragraph(1, "body text"), ], ); document.top_skip = 0; document.text_fraction_percent = 0; document.float_page_fraction_percent = 10; document }; let mut engine = Engine::layout(&document); assert_eq!(engine.pages().len(), 2); engine.edit(&document, 1, "edited body text".to_string()); assert_eq!( engine.pages().len(), 2, "edited layout must keep topfraction" ); assert_eq!(engine.pages()[0].floats.len(), 1); assert!(engine.pages()[0].items.is_empty()); } #[test] fn edited_layout_respects_bottom_fraction() { let document = { let mut document = Document::new( 100, vec![ Unit::paragraph(0, "body text"), Unit::float(1, FloatPlacement::Bottom, 40, 50), ], ); document.top_skip = 0; document.text_fraction_percent = 0; document.bottom_fraction_percent = 30; document.float_page_fraction_percent = 10; document }; let mut engine = Engine::layout(&document); assert_eq!(engine.pages().len(), 2); assert!(engine.pages()[0].floats.is_empty()); engine.edit(&document, 0, "edited body text".to_string()); assert_eq!( engine.pages().len(), 2, "edited layout must keep bottomfraction" ); assert!(engine.pages()[0].floats.is_empty()); assert_eq!(engine.pages()[1].floats.len(), 1); } #[test] fn edit_ignores_structural_units() { let rows = vec![HalignRow { cells: vec![HalignCell { text: "A".to_owned(), span: 1, alignment: CellAlignment::Left, }], rule: false, }]; let document = Document::new(100, vec![Unit::halign(0, rows, 1, 0)]); let mut engine = Engine::layout(&document); let before: Vec<_> = engine.pages().iter().map(|page| page.items.len()).collect(); engine.edit(&document, 0, "replacement text"); assert_eq!(engine.recomputed_pages(), 0); let after: Vec<_> = engine.pages().iter().map(|page| page.items.len()).collect(); assert_eq!(before, after); } #[test] fn ligature_boxes_paint_their_component_letters() { let unit = Unit::paragraph(1, "office"); let page = Page { items: unit.items, insertions: Vec::new(), marks: Vec::new(), floats: Vec::new(), sources: Vec::new(), hash: 0, }; let list = page.display_list(); assert!(list.items.iter().any(|item| matches!( item, crate::render::DisplayItem::Text { text, .. } if text == "ff" ))); } #[test] fn paragraph_widths_come_from_cmr10_not_fixed_cells() { let width = |source: &str| { let unit = Unit::paragraph(1, source); match &unit.items[0] { VerticalItem::Paragraph(paragraph) => paragraph.width, other => panic!("expected paragraph, got {other:?}"), } }; assert!( width("mmm") > width("iii"), "Computer Modern m is wider than i" ); } #[test] fn tall_insertions_split_across_pages() { let document = Document::new( 100, vec![Unit::insertion( 1, 0, 120, vec![ VerticalItem::Box(VerticalBox { width: 10, height: 40, }), VerticalItem::Box(VerticalBox { width: 10, height: 40, }), VerticalItem::Box(VerticalBox { width: 10, height: 40, }), ], )], ); let engine = Engine::layout(&document); assert_eq!(engine.pages().len(), 2); assert_eq!(engine.pages()[0].insertions[0].height, 80); assert_eq!(engine.pages()[1].insertions[0].height, 40); } #[test] fn insertion_reserves_page_height() { let boxed = |height: i64| VerticalItem::Box(VerticalBox { width: 100, height }); let document = Document::new( 100, vec![ Unit::vertical(0, vec![boxed(30)]), Unit::insertion(1, 1, 20, vec![boxed(15)]), Unit::vertical(2, vec![boxed(30)]), Unit::vertical(3, vec![boxed(30)]), ], ); let layout = Engine::layout(&document); assert_eq!(layout.pages().len(), 2); assert_eq!(layout.pages()[0].insertions.len(), 1); assert_eq!(layout.pages()[1].insertions.len(), 0); } #[test] fn halign_aligns_cells_inside_their_columns() { let rows = vec![ HalignRow { cells: vec![ HalignCell { text: "A".to_owned(), span: 1, alignment: CellAlignment::Left, }, HalignCell { text: "B".to_owned(), span: 1, alignment: CellAlignment::Left, }, ], rule: false, }, HalignRow { cells: vec![ HalignCell { text: "longword".to_owned(), span: 1, alignment: CellAlignment::Left, }, HalignCell { text: "C".to_owned(), span: 1, alignment: CellAlignment::Right, }, ], rule: true, }, HalignRow { cells: vec![HalignCell { text: "TOTAL".to_owned(), span: 2, alignment: CellAlignment::Center, }], rule: false, }, ]; let unit = Unit::halign(0, rows, 2, 20); let VerticalItem::Halign(halign) = &unit.items[0] else { panic!("expected a halign item"); }; assert_eq!(halign.cell_box(0, 0), Some((0, 5242880))); assert_eq!(halign.cell_box(1, 1), Some((6553600, 655360))); assert_eq!(halign.cell_box(2, 0), Some((1966080, 7208960))); } #[test] fn multi_page_pdf_lists_each_page() { let document = Document::new(400, vec![Unit::paragraph(1, "a"), Unit::paragraph(2, "b")]); let engine = Engine::layout(&document); let list = engine.pages()[0].display_list(); let pages = vec![list.clone(), list]; let pdf = crate::pdf::display_lists_to_pdf(&pages, 400 * 65_536); let text = String::from_utf8_lossy(&pdf); assert!(text.contains("/Count 2")); assert_eq!(text.matches("/Type /Page ").count(), 2); } #[test] fn special_content_reaches_the_pdf_stream() { use crate::render::DisplayList; let mut list = DisplayList { width: 612 * 65_536, height: 792 * 65_536, items: Vec::new(), images: Vec::new(), }; list.special("0.5 g 10 10 20 20 re f"); let pdf = crate::pdf::display_list_to_pdf(&list, 792 * 65_536); assert!(String::from_utf8_lossy(&pdf).contains("0.5 g 10 10 20 20 re f")); } #[test] fn insertion_contents_reach_the_display_list() { let page = Page { items: vec![VerticalItem::Insertion(Insertion { class: 0, height: 20 * 65_536, items: vec![VerticalItem::Rule { width: 100 * 65_536, height: 2 * 65_536, }], })], insertions: Vec::new(), marks: Vec::new(), floats: Vec::new(), sources: Vec::new(), hash: 0, }; let list = page.display_list(); assert!(list.items.iter().any(|item| matches!( item, crate::render::DisplayItem::Rule { width, .. } if *width == 100 * 65_536 ))); } #[test] fn float_placeholders_are_painted_at_page_edges() { let page = Page { items: vec![VerticalItem::Box(VerticalBox { width: 100 * 65_536, height: 20 * 65_536, })], insertions: Vec::new(), marks: Vec::new(), floats: vec![ Float { placement: FloatPlacement::Top, width: 50 * 65_536, height: 15 * 65_536, content: Vec::new(), }, Float { placement: FloatPlacement::Bottom, width: 60 * 65_536, height: 10 * 65_536, content: Vec::new(), }, ], sources: Vec::new(), hash: 0, }; let list = page.display_list_with_goal(700 * 65_536); assert!(list.items.iter().any(|item| matches!( item, crate::render::DisplayItem::Rule { y, width, height, .. } if *y == 0 && *width == 50 * 65_536 && *height == 15 * 65_536 ))); assert!(list.items.iter().any(|item| matches!( item, crate::render::DisplayItem::Rule { y, width, height, .. } if *y == 690 * 65_536 && *width == 60 * 65_536 && *height == 10 * 65_536 ))); } #[test] fn footnote_separator_sits_above_the_insertion_area() { let page = Page { items: vec![ VerticalItem::Box(VerticalBox { width: 100 * 65_536, height: 100 * 65_536, }), VerticalItem::Insertion(Insertion { class: 0, height: 20 * 65_536, items: vec![VerticalItem::Rule { width: 100 * 65_536, height: 2 * 65_536, }], }), ], insertions: Vec::new(), marks: Vec::new(), floats: Vec::new(), sources: Vec::new(), hash: 0, }; let list = page.display_list_with_goal(700 * 65_536); let separator = list.items.iter().find_map(|item| match item { crate::render::DisplayItem::Rule { y, width, .. } if *width == 40 * 65_536 => Some(*y), _ => None, }); let y = separator.expect("separator rule"); assert!(y > 690 * 65_536); assert!(y < 700 * 65_536); } #[test] fn insertion_classes_stack_from_the_page_bottom() { let page = Page { items: vec![ VerticalItem::Insertion(Insertion { class: 1, height: 10 * 65_536, items: vec![VerticalItem::Rule { width: 10 * 65_536, height: 10 * 65_536, }], }), VerticalItem::Insertion(Insertion { class: 0, height: 10 * 65_536, items: vec![VerticalItem::Rule { width: 10 * 65_536, height: 10 * 65_536, }], }), ], insertions: Vec::new(), marks: Vec::new(), floats: Vec::new(), sources: Vec::new(), hash: 0, }; let list = page.display_list_with_goal(100 * 65_536); let mut rules: Vec = list .items .iter() .filter_map(|item| match item { crate::render::DisplayItem::Rule { y, width, .. } if *width == 10 * 65_536 => { Some(*y) } _ => None, }) .collect(); rules.sort_unstable(); assert_eq!(rules.len(), 2); assert_eq!(rules[0], 78 * 65_536); assert_eq!(rules[1], 90 * 65_536); } #[test] fn insertion_material_sits_at_the_page_bottom() { let page = Page { items: vec![ VerticalItem::Box(VerticalBox { width: 100 * 65_536, height: 100 * 65_536, }), VerticalItem::Insertion(Insertion { class: 0, height: 20 * 65_536, items: vec![VerticalItem::Rule { width: 100 * 65_536, height: 2 * 65_536, }], }), ], insertions: Vec::new(), marks: Vec::new(), floats: Vec::new(), sources: Vec::new(), hash: 0, }; let list = page.display_list_with_goal(700 * 65_536); let rule = list.items.iter().find_map(|item| match item { crate::render::DisplayItem::Rule { y, .. } => Some(*y), _ => None, }); assert!(rule.expect("insertion rule") >= 697 * 65_536); } #[test] fn link_rectangles_become_pdf_annotations() { use crate::render::DisplayList; let mut list = DisplayList { width: 612 * 65_536, height: 792 * 65_536, items: Vec::new(), images: Vec::new(), }; list.link( 72 * 65_536, 700 * 65_536, 100 * 65_536, 12 * 65_536, "https://example.com/paper", ); let pdf = crate::pdf::display_list_to_pdf(&list, 792 * 65_536); let text = String::from_utf8_lossy(&pdf); assert!(text.contains("/Subtype /Link")); assert!(text.contains("/A << /S /URI /URI (https://example.com/paper) >>")); assert!(text.contains("/Annots [")); } #[test] fn image_xobject_is_embedded_and_painted() { use crate::render::{DisplayItem, DisplayList, PdfImage}; let mut list = DisplayList { width: 612 * 65_536, height: 792 * 65_536, items: Vec::new(), images: Vec::new(), }; let index = list.add_image(PdfImage { width: 1, height: 1, rgb: vec![255, 0, 0], }); list.push(DisplayItem::Image { x: 0, y: 0, width: 10 * 65_536, height: 10 * 65_536, index, }); let pdf = crate::pdf::display_list_to_pdf(&list, 792 * 65_536); let text = String::from_utf8_lossy(&pdf); assert!(text.contains("/Subtype /Image")); assert!(text.contains("/XObject << /Im0")); assert!(text.contains("/Im0 Do")); } #[test] fn display_list_writes_a_minimal_pdf() { let document = Document::new(400, vec![Unit::paragraph(1, "hello")]); let engine = Engine::layout(&document); let list = engine.pages()[0].display_list(); let pdf = crate::pdf::display_list_to_pdf(&list, 400 * 65_536); let text = String::from_utf8_lossy(&pdf); assert!(text.starts_with("%PDF-1.4")); assert!(text.contains("/Type /Page ")); assert!(text.contains("/BaseFont /LiberationSerif")); assert!(text.contains("/Subtype /Type0")); assert!(text.contains("/FontFile2")); assert!(text.contains("/ToUnicode")); assert!(text.contains("Tj")); assert!(text.trim_end().ends_with("%%EOF")); } #[test] fn pdf_embeds_only_the_used_faces() { let document = Document::new(400, vec![Unit::paragraph(1, "roman only")]); let engine = Engine::layout(&document); let list = engine.pages()[0].display_list(); let pdf = crate::pdf::display_list_to_pdf(&list, 400 * 65_536); let text = String::from_utf8_lossy(&pdf); assert_eq!(text.matches("/Subtype /Type0").count(), 1); assert!(pdf.len() < 60_000, "{}", pdf.len()); assert!(!text.contains("/BaseFont /LiberationSerif-Bold")); assert!(!text.contains("/BaseFont /LiberationMono")); } #[test] fn sans_paragraph_paints_with_the_sans_face() { let unit = Unit::paragraph_with_face(1, "sans face", ParagraphFont::Sans); let page = Page { items: unit.items, insertions: Vec::new(), marks: Vec::new(), floats: Vec::new(), sources: Vec::new(), hash: 0, }; let svg = page.display_list().to_svg(); assert!(svg.contains("font-family=\"sans-serif\"")); } #[test] fn mono_paragraph_paints_with_a_mono_face() { let unit = Unit::paragraph_with_face(1, "code 123", ParagraphFont::Mono); let page = Page { items: unit.items, insertions: Vec::new(), marks: Vec::new(), floats: Vec::new(), sources: Vec::new(), hash: 0, }; let svg = page.display_list().to_svg(); assert!(svg.contains("font-family=\"monospace\"")); } #[test] fn bold_paragraph_paints_with_a_bold_face() { let document = Document::new( 2_000_000, vec![Unit::paragraph_with_face(1, "bold", ParagraphFont::Bold)], ); let layout = Engine::layout(&document); let list = layout.pages()[0].display_list(); assert!(list.items.iter().any(|item| matches!( item, crate::render::DisplayItem::Text { font: crate::render::FontFace::Bold, .. } ))); } #[test] fn italic_paragraph_paints_with_an_italic_face() { let document = Document::new( 2_000_000, vec![Unit::paragraph_with_face( 1, "italic", ParagraphFont::Italic, )], ); let layout = Engine::layout(&document); let list = layout.pages()[0].display_list(); assert!(list.items.iter().any(|item| matches!( item, crate::render::DisplayItem::Text { font: crate::render::FontFace::Italic, .. } ))); } #[test] fn italic_paragraph_pdf_uses_the_italic_resource() { let document = Document::new( 2_000_000, vec![Unit::paragraph_with_face( 1, "italic", ParagraphFont::Italic, )], ); let layout = Engine::layout(&document); let list = layout.pages()[0].display_list(); let pdf = crate::pdf::display_list_to_pdf(&list, 400 * 65_536); let text = String::from_utf8_lossy(&pdf); assert!(text.contains("/BaseFont /LiberationSerif-Italic")); assert!(text.contains("BT /F3")); } #[test] fn pdf_writer_uses_a_bold_font_resource() { let mut list = crate::render::DisplayList::default(); list.push(crate::render::DisplayItem::Text { x: 10, y: 20, size: 10 * 65_536, text: "bold".to_owned(), font: crate::render::FontFace::Bold, }); let pdf = crate::pdf::display_list_to_pdf(&list, 400 * 65_536); let text = String::from_utf8_lossy(&pdf); assert!(text.contains("/BaseFont /LiberationSerif-Bold")); assert!(text.contains("/F2 ")); assert!(text.contains("/W [")); assert!(text.contains("BT /F2")); } #[test] fn svg_reflects_display_font_faces() { let mut list = crate::render::DisplayList::default(); for (index, font) in [ crate::render::FontFace::Roman, crate::render::FontFace::Bold, crate::render::FontFace::Italic, crate::render::FontFace::Mono, ] .into_iter() .enumerate() { list.push(crate::render::DisplayItem::Text { x: 10, y: 20 + index as i64 * 20, size: 10 * 65_536, text: format!("face{index}"), font, }); } let svg = list.to_svg(); assert!(svg.contains("font-family=\"serif\">face0")); assert!(svg.contains("font-weight=\"bold\">face1")); assert!(svg.contains("font-style=\"italic\">face2")); assert!(svg.contains("font-family=\"monospace\">face3")); } #[test] fn binomial_is_painted_with_parentheses() { let document = Document::new( 1000, vec![Unit::math( 1, crate::math::parse_math("\\binom{n}{k}"), &Cmr10Metrics::default(), )], ); let engine = Engine::layout(&document); let list = engine.pages()[0].display_list(); let texts: Vec<_> = list .items .iter() .filter_map(|item| match item { DisplayItem::Text { text, .. } => Some(text.as_str()), _ => None, }) .collect(); assert!(texts.contains(&"(")); assert!(texts.contains(&")")); assert!(texts.contains(&"n")); assert!(texts.contains(&"k")); } #[test] fn sqrt_degree_is_painted_before_the_radical() { let document = Document::new( 1000, vec![Unit::math( 1, crate::math::parse_math("\\sqrt[3]{x}"), &Cmr10Metrics::default(), )], ); let engine = Engine::layout(&document); let list = engine.pages()[0].display_list(); let texts: Vec<_> = list .items .iter() .filter_map(|item| match item { DisplayItem::Text { text, .. } => Some(text.as_str()), _ => None, }) .collect(); assert!(texts.contains(&"3")); assert!(texts.contains(&"x")); let degree_x = list .items .iter() .find_map(|item| match item { DisplayItem::Text { text, x, .. } if text == "3" => Some(*x), _ => None, }) .unwrap(); let radical_x = list .items .iter() .find_map(|item| match item { DisplayItem::Text { text, x, .. } if text == "√" => Some(*x), _ => None, }) .unwrap(); assert!(radical_x > degree_x); } #[test] fn overbrace_paints_a_brace_bar() { let document = Document::new( 1000, vec![Unit::math( 1, crate::math::parse_math("\\overbrace{x}"), &Cmr10Metrics::default(), )], ); let engine = Engine::layout(&document); let list = engine.pages()[0].display_list(); let rules = list .items .iter() .filter(|item| matches!(item, DisplayItem::Rule { .. })) .count(); assert!( rules >= 3, "expected a brace bar and two ticks, got {rules}" ); } #[test] fn display_list_paints_limits_above_and_below() { let document = Document::new( 1000, vec![Unit::math( 1, crate::math::parse_math("\\sum_{i=1}^{n}"), &Cmr10Metrics::default(), )], ); let engine = Engine::layout(&document); let list = engine.pages()[0].display_list(); let texts = list .items .iter() .filter(|item| matches!(item, DisplayItem::Text { .. })) .count(); assert!(texts >= 4, "expected sum plus both limits, got {texts}"); } #[test] fn math_display_list_paints_symbols_and_fraction_rule() { let atom = crate::math::parse_math("x + \\frac{a}{b}"); let document = Document::new( 400, vec![Unit::math(1, atom, &crate::cmr10::Cmr10Metrics::new())], ); let engine = Engine::layout(&document); let list = engine.pages()[0].display_list(); let text = list .items .iter() .filter(|item| matches!(item, DisplayItem::Text { .. })) .count(); let rules = list .items .iter() .filter(|item| matches!(item, DisplayItem::Rule { .. })) .count(); assert!(text >= 4, "expected math glyphs, got {text}"); assert!(rules >= 1, "expected a fraction rule"); let svg = list.to_svg(); assert!(svg.contains(">x")); } #[test] fn bottom_float_content_is_painted_at_the_page_bottom() { let mut document = Document::new(100, Vec::new()); document.top_skip = 0; document.text_fraction_percent = 0; document.units.push(Unit::vertical( 1, vec![VerticalItem::Box(VerticalBox { width: 10, height: 10, })], )); document.units.push(Unit::float_with_content( 2, FloatPlacement::Bottom, 30, 20, vec![VerticalItem::Rule { width: 30, height: 2, }], )); let engine = Engine::layout(&document); let list = engine.pages()[0].display_list_with_goal(100); assert!(list.items.iter().any(|item| matches!( item, DisplayItem::Rule { y: 80, width: 30, height: 2, .. } ))); } #[test] fn float_content_is_painted_at_the_top_of_the_page() { let mut document = Document::new(1000, Vec::new()); document.top_skip = 0; document.units.push(Unit::float_with_content( 1, FloatPlacement::Top, 100, 20, vec![VerticalItem::Rule { width: 80, height: 2, }], )); document.units.push(Unit::paragraph(2, "hello world")); let engine = Engine::layout(&document); let list = engine.pages()[0].display_list(); assert!(list.items.iter().any(|item| matches!( item, DisplayItem::Rule { y: 0, width: 80, height: 2, .. } ))); let text_y = list .items .iter() .filter_map(|item| match item { DisplayItem::Text { y, text, .. } if text == "h" => Some(y), _ => None, }) .min() .unwrap(); assert!(*text_y >= 20, "body text starts below the top float"); } #[test] fn paragraph_display_list_paints_characters() { let document = Document::new(400, vec![Unit::paragraph(1, "hello world")]); let engine = Engine::layout(&document); let list = engine.pages()[0].display_list(); let texts = list .items .iter() .filter(|item| matches!(item, DisplayItem::Text { .. })) .count(); assert!(texts >= 10, "expected painted characters, got {texts}"); let svg = list.to_svg(); assert!(svg.contains(">h")); assert!(svg.contains(">w")); } #[test] fn halign_text_is_painted_at_ten_points() { let unit = Unit::halign_from_source(1, r"A & B", 2, 10); let document = Document::new(2_000_000, vec![unit]); let engine = Engine::layout(&document); let list = engine.pages()[0].display_list(); let size = list.items.iter().find_map(|item| match item { DisplayItem::Text { size, .. } => Some(*size), _ => None, }); assert_eq!(size, Some(10 * 65_536)); } #[test] fn halign_display_list_paints_cells_and_rules() { let unit = Unit::halign_from_source(1, r"A & B \\ \hline C & D", 2, 10); let document = Document::new(2_000_000, vec![unit]); let engine = Engine::layout(&document); let list = engine.pages()[0].display_list(); let texts = list .items .iter() .filter(|item| matches!(item, DisplayItem::Text { .. })) .count(); let rules = list .items .iter() .filter(|item| matches!(item, DisplayItem::Rule { .. })) .count(); assert_eq!(texts, 4); assert_eq!(rules, 1); let svg = list.to_svg(); assert!(svg.contains(">A")); assert!(svg.contains(" = serde_json::from_str(&encoded).unwrap(); assert_eq!(engine.checkpoints(), decoded.as_slice()); } }