pub mod cmr10; pub mod math; pub mod page; pub mod paragraph; pub mod pdf; pub mod render; mod subset; pub mod tfm; pub use cmr10::Cmr10Metrics; use page::{PageBuilder, VerticalGlue, VerticalNode}; 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, /// `[h]`: the float stays in the body flow, surrounded by `\intextsep`. Here, } /// Deferred float material for the top, bottom, or in-text placements. #[derive(Clone, Debug, PartialEq, Eq, Hash, serde::Serialize, serde::Deserialize)] pub struct Float { pub placement: FloatPlacement, pub width: i64, pub height: i64, /// TeX floatsep: space inserted before this float when another float of /// the same placement already sits on the page. #[serde(default)] pub gap_before: i64, /// TeX's `\intextsep` below an in-text float, so the renderer advances the /// body flow by the same gap the page builder reserved. #[serde(default)] pub gap_after: 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, gap_before: 0, gap_after: 0, 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 { Self::paragraph_with_style_and_face(id, source, ParagraphStyle::default(), font) } pub fn paragraph_with_style( id: UnitId, source: impl Into, style: ParagraphStyle, ) -> Self { Self::paragraph_with_style_and_face(id, source, style, ParagraphFont::Roman) } /// Build a paragraph unit with both an explicit style and font face. pub fn paragraph_with_style_and_face( id: UnitId, source: impl Into, style: ParagraphStyle, font: ParagraphFont, ) -> Self { let source = source.into(); let metrics = crate::cmr10::Cmr10Metrics::for_paragraph_font(font); let mut paragraph = layout_paragraph_with_font(&source, &style, &metrics); paragraph.font = font; 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, /// TeX's `\dimen`: an absolute cap on this class's height on one /// page. `None` uses only the percentage share. #[serde(default)] pub max_height: Option, /// TeX's `\skip`: space inserted before this class on a page. /// `None` falls back to `Document::insertion_skip`. #[serde(default)] pub skip: Option, } #[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, /// TeX's `\topnumber`: maximum top floats on one page. #[serde(default = "default_top_number")] pub top_number: u8, /// TeX's `\bottomnumber`: maximum bottom floats on one page. #[serde(default = "default_bottom_number")] pub bottom_number: u8, /// TeX's `\totalnumber`: maximum floats of any placement on one page. #[serde(default = "default_total_number")] pub total_number: u8, /// Per-class insertion limits. Missing classes use the full page. #[serde(default)] pub insertion_classes: Vec, /// TeX's `\skip\footins`: space reserved between the page body and the /// first insertion class on a page. Zero by default for compatibility. #[serde(default)] pub insertion_skip: i64, /// TeX floatsep: vertical space between two floats of the same placement /// on one page. Defaults to 12pt. #[serde(default = "default_float_sep")] pub float_sep: i64, /// TeX's `\textfloatsep`: space between body text and the float area at /// the top or bottom of a text page. Defaults to 20pt. #[serde(default = "default_text_float_sep")] pub text_float_sep: i64, /// TeX's `\intextsep`: space above and below an `[h]` float that stays in /// the body flow. Defaults to 12pt. #[serde(default = "default_in_text_sep")] pub in_text_sep: i64, /// TeX `\parskip`: vertical glue inserted between paragraphs. #[serde(default)] pub par_skip: i64, } fn default_text_fraction() -> u8 { 50 } fn default_float_sep() -> i64 { 12 * 65_536 } fn default_text_float_sep() -> i64 { 20 * 65_536 } fn default_in_text_sep() -> i64 { 12 * 65_536 } fn default_bottom_fraction() -> u8 { 30 } fn default_top_fraction() -> u8 { 70 } fn default_top_number() -> u8 { 2 } fn default_bottom_number() -> u8 { 1 } fn default_total_number() -> u8 { 12 } 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(), top_number: default_top_number(), bottom_number: default_bottom_number(), total_number: default_total_number(), insertion_classes: Vec::new(), insertion_skip: 0, float_sep: default_float_sep(), text_float_sep: default_text_float_sep(), in_text_sep: default_in_text_sep(), par_skip: 0, } } /// 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| { let fraction = self.page_goal * i64::from(entry.fraction_percent) / 100; entry .max_height .map_or(fraction, |absolute| fraction.min(absolute)) }) } pub fn with_top_skip(mut self, top_skip: i64) -> Self { self.top_skip = top_skip; self } /// TeX's `\skip`, falling back to the document-wide /// `insertion_skip` for classes without an explicit skip. pub fn insertion_skip_for(&self, class: u8) -> i64 { self.insertion_classes .iter() .find(|entry| entry.number == class) .and_then(|entry| entry.skip) .unwrap_or(self.insertion_skip) } } #[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() } /// Convert a document into the vertical list consumed by [`PageBuilder`]. /// /// Only single-item units can be expressed as page-builder nodes today, so /// floats and insertions make this return `None` and keep the incremental /// builder in charge. fn document_nodes(document: &Document) -> Option> { let mut nodes = Vec::with_capacity(document.units.len()); for unit in &document.units { let [item] = unit.items.as_slice() else { return None; }; nodes.push(match item { VerticalItem::Box(vertical_box) => VerticalNode::Box { height: vertical_box.height, depth: 0, }, VerticalItem::Rule { height, .. } => VerticalNode::Box { height: *height, depth: 0, }, VerticalItem::Math { height, depth, .. } => VerticalNode::Box { height: *height, depth: *depth, }, VerticalItem::Paragraph(paragraph) => VerticalNode::Box { height: paragraph.height, depth: 0, }, VerticalItem::Halign(halign) => VerticalNode::Box { height: halign.height, depth: 0, }, VerticalItem::Glue(height) => VerticalNode::Glue(VerticalGlue::new(*height, 0, 0)), VerticalItem::Penalty(value) => VerticalNode::Penalty(*value), VerticalItem::Mark(mark) => VerticalNode::Mark(mark.clone()), VerticalItem::Insertion(_) | VerticalItem::Float(_) => return None, }); } Some(nodes) } 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 + float.gap_before) .sum() } fn bottom_float_height(page: &Page) -> i64 { page.floats .iter() .filter(|float| float.placement == FloatPlacement::Bottom) .map(|float| float.height + float.gap_before) .sum() } /// Space reserved above the bottom float area: the floats themselves plus /// `\textfloatsep` once the page carries a bottom float. /// True when a page already carries float material at the top of the body /// column, so a first body item must not reset the vertical cursor. fn page_has_top_float_material(page: &Page) -> bool { page.floats .iter() .any(|float| matches!(float.placement, FloatPlacement::Top | FloatPlacement::Here)) } fn bottom_float_area(page: &Page, text_float_sep: i64) -> i64 { let height = bottom_float_height(page); if height > 0 { height + text_float_sep.max(0) } else { height } } /// 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 } fn is_body_item(item: &VerticalItem) -> bool { matches!( item, VerticalItem::Box(_) | VerticalItem::Rule { .. } | VerticalItem::Halign(_) | VerticalItem::Paragraph(_) | VerticalItem::Math { .. } ) } #[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; } if is_body_item(item) && current.items.is_empty() && top_float_height(¤t) > 0 { used += document.text_float_sep.max(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() && !page_has_top_float_material(¤t) { used = document.top_skip.max(*height); } else if used + *height > document.page_goal - insertion_height - bottom_float_area(¤t, document.text_float_sep) { 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() && !page_has_top_float_material(¤t) { used = document.top_skip.max(vertical_box.height); } else if used + vertical_box.height > document.page_goal - insertion_height - bottom_float_area(¤t, document.text_float_sep) { 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() && !page_has_top_float_material(¤t) { document.page_goal - document.top_skip } else { document.page_goal - used - insertion_height - bottom_float_area(¤t, document.text_float_sep) }; 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() && !page_has_top_float_material(¤t) { 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; } let par_skip = if current.items.is_empty() { 0 } else { document.par_skip.max(0) }; if current.items.is_empty() && !page_has_top_float_material(¤t) { used = document.top_skip.max(paragraph.height); } else if used + par_skip + paragraph.height > document.page_goal - insertion_height - bottom_float_area(¤t, document.text_float_sep) { pages.push(std::mem::replace(&mut current, Page::empty())); used = document.top_skip.max(paragraph.height); insertion_height = 0; } else { if par_skip > 0 { current.items.push(VerticalItem::Glue(par_skip)); } used += par_skip + 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() && !page_has_top_float_material(¤t) { used = document.top_skip.max(amount); } else if used + amount > document.page_goal - insertion_height - bottom_float_area(¤t, document.text_float_sep) { 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 gap = if current.insertions.is_empty() { document.insertion_skip_for(insertion.class).max(0) } else { 0 }; let capacity = document .page_goal .saturating_sub(document.top_skip) .saturating_sub(gap) .max(1); if insertion_height + insertion.height > capacity && (!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 class_limit = document .insertion_class_limit(insertion.class) .min( document .page_goal .saturating_sub(document.top_skip) .saturating_sub(gap), ) .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; let mut chunk_gap = gap; 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_gap + chunk_height; chunk_height = 0; pages.push(std::mem::replace(&mut current, Page::empty())); used = document.top_skip; chunk_gap = gap; } 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_gap + chunk_height; } } else { let goal = document.page_goal - insertion_height; if (!current.items.is_empty() || !current.insertions.is_empty()) && (used + gap + 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 += gap + insertion.height; current.insertions.push(insertion.clone()); } } VerticalItem::Mark(mark) => { current.marks.push(mark.clone()); } VerticalItem::Float(float) => { if float.placement == FloatPlacement::Top { let existing_top: i64 = current .floats .iter() .filter(|entry| entry.placement == FloatPlacement::Top) .map(|entry| entry.height + entry.gap_before) .sum(); let top_count = current .floats .iter() .filter(|entry| entry.placement == FloatPlacement::Top) .count(); let top_gap = if top_count > 0 { document.float_sep.max(0) } else { 0 }; let text_gap = if top_count == 0 { document.text_float_sep.max(0) } else { 0 }; let fits_on_current = !current.items.is_empty() && top_count < usize::from(document.top_number) && current.floats.len() < usize::from(document.total_number) && used + text_gap + top_gap + float.height <= document.page_goal - insertion_height && (existing_top + top_gap + float.height) * 100 <= i64::from(document.top_fraction_percent) * document.page_goal; if fits_on_current { let mut placed = float.clone(); placed.gap_before = top_gap; used += text_gap + top_gap + float.height; current.floats.push(placed); continue; } 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() && current.floats.is_empty() { used = 0; } let gap = if current .floats .iter() .any(|entry| entry.placement == FloatPlacement::Top) { document.float_sep.max(0) } else { 0 }; let mut placed = float.clone(); placed.gap_before = gap; used += gap + float.height; current.floats.push(placed); } else if float.placement == FloatPlacement::Here { let has_content = !current.items.is_empty() || !current.floats.is_empty(); let sep_in = if has_content { document.in_text_sep.max(0) } else { 0 }; let sep_out = document.in_text_sep.max(0); let fits_here = has_content && current.floats.len() < usize::from(document.total_number) && used + sep_in + float.height + sep_out <= document.page_goal - insertion_height - bottom_float_area(¤t, document.text_float_sep); if fits_here { let mut placed = float.clone(); placed.gap_before = sep_in; placed.gap_after = sep_out; used += sep_in + float.height + sep_out; current.items.push(VerticalItem::Float(placed.clone())); current.floats.push(placed); } else { if !current.items.is_empty() || !current.floats.is_empty() { pages.push(std::mem::replace(&mut current, Page::empty())); used = document.top_skip; insertion_height = 0; } let mut placed = float.clone(); placed.gap_before = 0; placed.gap_after = sep_out; used = if current.floats.is_empty() { float.height } else { used + float.height } + sep_out; current.items.push(VerticalItem::Float(placed.clone())); current.floats.push(placed); } } else { let existing_bottom = bottom_float_height(¤t); let bottom_count = current .floats .iter() .filter(|entry| entry.placement == FloatPlacement::Bottom) .count(); let bottom_gap = if bottom_count > 0 { document.float_sep.max(0) } else { 0 }; let text_gap = if bottom_count == 0 { document.text_float_sep.max(0) } else { 0 }; if !current.items.is_empty() && bottom_count < usize::from(document.bottom_number) && current.floats.len() < usize::from(document.total_number) && used + text_gap + bottom_gap + float.height <= document.page_goal - insertion_height - existing_bottom && (used - document.top_skip - existing_bottom) * 100 >= document.text_fraction_percent as i64 * document.page_goal && (float.height + bottom_gap + existing_bottom) * 100 <= document.bottom_fraction_percent as i64 * document.page_goal { let mut placed = float.clone(); placed.gap_before = bottom_gap; current.floats.push(placed); } 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 } /// Lay out a document with TeX's page builder instead of the greedy /// scrolling builder. /// /// This is the staged P2 integration: it accepts documents whose units are /// single vertical items (boxes, rules, paragraphs, math, haligns, glue, /// penalties and marks). Floats and insertions still make it return `None`, /// because their page interaction belongs to the incremental builder for /// now. pub fn layout_paged(document: &Document) -> Option { let nodes = document_nodes(document)?; let builder = PageBuilder { page_goal: document.page_goal, top_skip: document.top_skip, max_depth: 0, }; let mut pages = Vec::new(); for fragment in builder.build(&nodes) { let mut items = Vec::new(); let mut marks = Vec::new(); let mut sources = Vec::new(); for unit in &document.units[fragment.start..fragment.end] { let item = unit.items.first()?.clone(); if let VerticalItem::Mark(mark) = &item { marks.push(mark.clone()); } else { items.push(item); } sources.push((unit.id, source_hash(&unit.source))); } let mut page = Page::empty(); page.items = items; page.marks = marks; page.sources = sources; page.seal_in_place(); pages.push(page); } let count = pages.len(); Some(Self { layout: Layout { pages, checkpoints: Vec::new(), recomputed_pages: 0, changed_pages: (0..count).collect(), }, }) } /// Rebuild a paged layout wholesale and report which page hashes changed. fn replace_with_paged(&mut self, document: &Document) { let previous = std::mem::take(&mut self.layout.pages); let mut layout = Self::layout_paged(document) .unwrap_or_else(|| Self::layout(document)) .layout; layout.changed_pages = layout .pages .iter() .enumerate() .filter(|(index, page)| { previous .get(*index) .map_or(true, |old| old.hash != page.hash) }) .map(|(index, _)| index) .collect(); layout.recomputed_pages = layout.pages.len(); self.layout = layout; } 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; }; let font = next.units[unit_index] .items .iter() .find_map(|item| match item { VerticalItem::Paragraph(paragraph) => Some(paragraph.font), _ => None, }) .unwrap_or(ParagraphFont::Roman); next.units[unit_index] = Unit::paragraph_with_style_and_face(unit_id, source, style, font); if self.layout.checkpoints.is_empty() { self.replace_with_paged(&next); return; } self.relayout_from(&next, unit_index); } /// Rebuild pages from the checkpoint before `start_index`, keeping every /// sealed page before it. This generalizes `edit` to structural changes: /// callers may add, remove or replace units at and after `start_index` as /// long as the prefix is unchanged. pub fn relayout_from(&mut self, document: &Document, start_index: usize) { if self.layout.checkpoints.is_empty() { self.replace_with_paged(document); return; } if start_index == 0 || start_index >= self.layout.checkpoints.len() { 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; } self.relayout_from_checkpoint(document, start_index); } fn relayout_from_checkpoint(&mut self, next: &Document, start_index: usize) { let mut checkpoint = self.layout .checkpoints .get(start_index) .cloned() .unwrap_or(Checkpoint { unit_index: start_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[start_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[..start_index].to_vec(); for (index, unit) in next.units.iter().enumerate().skip(start_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() && next.page_goal - used < next.float_page_fraction_percent as i64 * next.page_goal / 100 { pages.push(std::mem::replace(&mut current, Page::empty())); used = next.top_skip; insertion_height = 0; } if is_body_item(item) && current.items.is_empty() && top_float_height(¤t) > 0 { used += next.text_float_sep.max(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() && !page_has_top_float_material(¤t) { used = next.top_skip.max(*height); } else if used + *height > next.page_goal - insertion_height - bottom_float_area(¤t, next.text_float_sep) { 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() && !page_has_top_float_material(¤t) { used = next.top_skip.max(vertical_box.height); } else if used + vertical_box.height > next.page_goal - insertion_height - bottom_float_area(¤t, next.text_float_sep) { 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() && !page_has_top_float_material(¤t) { used = next.top_skip.max(halign.height); } else if used + halign.height > next.page_goal - insertion_height - bottom_float_area(¤t, next.text_float_sep) { 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; } let par_skip = if current.items.is_empty() { 0 } else { next.par_skip.max(0) }; if current.items.is_empty() && !page_has_top_float_material(¤t) { used = next.top_skip.max(paragraph.height); } else if used + par_skip + paragraph.height > next.page_goal - insertion_height - bottom_float_area(¤t, next.text_float_sep) { pages.push(std::mem::replace(&mut current, Page::empty())); used = next.top_skip.max(paragraph.height); insertion_height = 0; } else { if par_skip > 0 { current.items.push(VerticalItem::Glue(par_skip)); } used += par_skip + 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() && !page_has_top_float_material(¤t) { used = next.top_skip.max(amount); } else if used + amount > next.page_goal - insertion_height - bottom_float_area(¤t, next.text_float_sep) { 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 gap = if current.insertions.is_empty() { next.insertion_skip_for(insertion.class).max(0) } else { 0 }; let capacity = next .page_goal .saturating_sub(next.top_skip) .saturating_sub(gap) .max(1); let class_limit = next .insertion_class_limit(insertion.class) .min(capacity) .max(1); let class_height: i64 = current .insertions .iter() .filter(|entry| entry.class == insertion.class) .map(|entry| entry.height) .sum(); let exceeds = class_height + insertion.height > class_limit || insertion_height + insertion.height > capacity || used + gap + insertion.height > next.page_goal; if exceeds && !current.items.is_empty() { pages.push(std::mem::replace(&mut current, Page::empty())); used = next.top_skip; insertion_height = 0; } insertion_height += gap + insertion.height; current.insertions.push(insertion.clone()); } VerticalItem::Mark(mark) => { current.marks.push(mark.clone()); } VerticalItem::Float(float) => { if float.placement == FloatPlacement::Top { let existing_top: i64 = current .floats .iter() .filter(|entry| entry.placement == FloatPlacement::Top) .map(|entry| entry.height + entry.gap_before) .sum(); let top_count = current .floats .iter() .filter(|entry| entry.placement == FloatPlacement::Top) .count(); let top_gap = if top_count > 0 { next.float_sep.max(0) } else { 0 }; let text_gap = if top_count == 0 { next.text_float_sep.max(0) } else { 0 }; let fits_on_current = !current.items.is_empty() && top_count < usize::from(next.top_number) && current.floats.len() < usize::from(next.total_number) && used + text_gap + top_gap + float.height <= next.page_goal - insertion_height && (existing_top + top_gap + float.height) * 100 <= i64::from(next.top_fraction_percent) * next.page_goal; if fits_on_current { let mut placed = float.clone(); placed.gap_before = top_gap; used += text_gap + top_gap + float.height; current.floats.push(placed); continue; } 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; } if current.items.is_empty() && current.floats.is_empty() { used = 0; } let gap = if current .floats .iter() .any(|entry| entry.placement == FloatPlacement::Top) { next.float_sep.max(0) } else { 0 }; let mut placed = float.clone(); placed.gap_before = gap; used += gap + float.height; current.floats.push(placed); } else if float.placement == FloatPlacement::Here { let has_content = !current.items.is_empty() || !current.floats.is_empty(); let sep_in = if has_content { next.in_text_sep.max(0) } else { 0 }; let sep_out = next.in_text_sep.max(0); let fits_here = has_content && current.floats.len() < usize::from(next.total_number) && used + sep_in + float.height + sep_out <= next.page_goal - insertion_height - bottom_float_area(¤t, next.text_float_sep); if fits_here { let mut placed = float.clone(); placed.gap_before = sep_in; placed.gap_after = sep_out; used += sep_in + float.height + sep_out; current.items.push(VerticalItem::Float(placed.clone())); current.floats.push(placed); } else { if !current.items.is_empty() || !current.floats.is_empty() { pages.push(std::mem::replace(&mut current, Page::empty())); used = next.top_skip; insertion_height = 0; } let mut placed = float.clone(); placed.gap_before = 0; placed.gap_after = sep_out; used = if current.floats.is_empty() { float.height } else { used + float.height } + sep_out; current.items.push(VerticalItem::Float(placed.clone())); current.floats.push(placed); } } else { let existing_bottom = bottom_float_height(¤t); let bottom_count = current .floats .iter() .filter(|entry| entry.placement == FloatPlacement::Bottom) .count(); let bottom_gap = if bottom_count > 0 { next.float_sep.max(0) } else { 0 }; let text_gap = if bottom_count == 0 { next.text_float_sep.max(0) } else { 0 }; if !current.items.is_empty() && bottom_count < usize::from(next.bottom_number) && current.floats.len() < usize::from(next.total_number) && used + text_gap + bottom_gap + float.height <= next.page_goal - insertion_height - existing_bottom && (used - next.top_skip - existing_bottom) * 100 >= next.text_fraction_percent as i64 * next.page_goal && (float.height + bottom_gap + existing_bottom) * 100 <= next.bottom_fraction_percent as i64 * next.page_goal { let mut placed = float.clone(); placed.gap_before = bottom_gap; current.floats.push(placed); } else { pages.push(std::mem::replace(&mut current, Page::empty())); used = next.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 bold_paragraphs_use_cmbx10_advances() { fn width(unit: &Unit) -> i64 { match unit.items.first() { Some(VerticalItem::Paragraph(paragraph)) => paragraph.width, _ => panic!("expected paragraph"), } } let text = "mmmmmmmmmm iiiiiiiiii"; let roman = Unit::paragraph_with_face(1, text, ParagraphFont::Roman); let bold = Unit::paragraph_with_face(2, text, ParagraphFont::Bold); assert_ne!(width(&roman), width(&bold)); } #[test] fn editing_a_paragraph_preserves_its_font_face() { let document = Document::new( 51, vec![Unit::paragraph_with_face( 1, "bold text", ParagraphFont::Bold, )], ); let mut engine = Engine::layout(&document); engine.edit(&document, 1, "edited bold text"); let list = engine.pages()[0].display_list(); assert!(list.items.iter().any(|item| matches!( item, crate::render::DisplayItem::Text { font: crate::render::FontFace::Bold, .. } ))); } #[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); // Keep the replacement to a single line so it cannot spill onto a // third page; this test is about the checkpoint replay boundary. engine.edit(&document, 5, "g"); 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_cannot_fit() { let unit = Unit { id: 0, source: "float".to_owned(), paragraph_style: None, items: vec![ VerticalItem::Box(VerticalBox { width: 10, height: 10, }), VerticalItem::Float(Float { gap_before: 0, gap_after: 0, placement: FloatPlacement::Top, width: 40, height: 95, 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(), 3); 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(), 0); assert_eq!(engine.layout.pages[2].items.len(), 1); } #[test] fn a_late_top_float_that_fits_joins_the_current_page() { let unit = Unit { id: 0, source: "float".to_owned(), paragraph_style: None, items: vec![ VerticalItem::Box(VerticalBox { width: 10, height: 10, }), VerticalItem::Float(Float { gap_before: 0, gap_after: 0, placement: FloatPlacement::Top, width: 40, height: 20, content: Vec::new(), }), VerticalItem::Box(VerticalBox { width: 10, height: 10, }), ], }; let mut document = Document::new(100, vec![unit]); document.text_float_sep = 0; 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(), 2); } #[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; document.text_float_sep = 0; 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, max_height: None, skip: None, }]; 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 insertions_from_multiple_classes_respect_the_page_height() { let rule = VerticalItem::Rule { width: 65_536, height: 60, }; let mut document = Document::new( 100, vec![ Unit::insertion(1, 1, 60, vec![rule.clone()]), Unit::insertion(2, 2, 60, vec![rule]), ], ); document.top_skip = 0; document.insertion_classes = vec![ InsertionClass { number: 1, fraction_percent: 60, max_height: None, skip: None, }, InsertionClass { number: 2, fraction_percent: 60, max_height: None, skip: None, }, ]; 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 insertion_class_absolute_limit_caps_the_class_height() { let rule = VerticalItem::Rule { width: 65_536, height: 100, }; let mut document = Document::new( 1000, vec![ Unit::insertion(1, 1, 100, vec![rule.clone()]), Unit::insertion(2, 1, 100, vec![rule]), ], ); document.insertion_classes = vec![InsertionClass { number: 1, fraction_percent: 100, max_height: Some(150), skip: None, }]; 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 top_number_limits_top_floats_per_page() { let mut document = Document::new( 1000, vec![ Unit::paragraph(0, "alpha"), Unit::float(1, FloatPlacement::Top, 10, 100), Unit::paragraph(2, "beta"), Unit::float(3, FloatPlacement::Top, 10, 100), Unit::paragraph(4, "gamma"), Unit::float(5, FloatPlacement::Top, 10, 100), ], ); document.top_number = 1; document.total_number = 10; document.text_float_sep = 0; let engine = Engine::layout(&document); assert_eq!(engine.pages().len(), 3); for page in engine.pages() { assert!( page.floats .iter() .filter(|float| float.placement == FloatPlacement::Top) .count() <= 1 ); } } #[test] fn total_number_limits_mixed_float_placements() { let mut document = Document::new( 1000, vec![ Unit::float(0, FloatPlacement::Top, 10, 100), Unit::paragraph(1, "alpha"), Unit::float(2, FloatPlacement::Bottom, 10, 100), ], ); document.top_number = 5; document.bottom_number = 5; document.total_number = 1; document.text_fraction_percent = 0; document.text_float_sep = 0; let engine = Engine::layout(&document); assert_eq!(engine.pages().len(), 2); assert_eq!(engine.pages()[0].floats.len(), 1); assert_eq!(engine.pages()[0].floats[0].placement, FloatPlacement::Top); assert_eq!(engine.pages()[1].floats.len(), 1); assert_eq!( engine.pages()[1].floats[0].placement, FloatPlacement::Bottom ); } #[test] fn edited_layout_respects_float_number_limits() { let mut document = Document::new( 1000, vec![ Unit::paragraph(0, "alpha"), Unit::float(1, FloatPlacement::Top, 10, 100), Unit::paragraph(2, "beta"), Unit::float(3, FloatPlacement::Top, 10, 100), ], ); document.top_number = 1; document.total_number = 10; document.text_float_sep = 0; let mut engine = Engine::layout(&document); let mut edited = Document::new( 1000, vec![ Unit::paragraph(0, "alpha changed"), Unit::float(1, FloatPlacement::Top, 10, 100), Unit::paragraph(2, "beta"), Unit::float(3, FloatPlacement::Top, 10, 100), ], ); edited.text_float_sep = 0; engine.edit(&edited, 1, "alpha changed"); assert_eq!(engine.pages().len(), 2); for page in engine.pages() { assert!( page.floats .iter() .filter(|float| float.placement == FloatPlacement::Top) .count() <= 1 ); } } #[test] fn relayout_from_keeps_the_unchanged_page_prefix() { let first = Unit::paragraph(0, "alpha"); let mut document = Document::new( 20, vec![ first.clone(), Unit::paragraph(1, "beta"), Unit::paragraph(2, "gamma"), ], ); let mut engine = Engine::layout(&document); let prefix_hash = engine.pages()[0].hash; document = Document::new( 20, vec![ first, Unit::paragraph(3, "inserted"), Unit::paragraph(1, "beta changed"), Unit::paragraph(2, "gamma"), ], ); engine.relayout_from(&document, 1); assert_eq!(engine.pages()[0].hash, prefix_hash); assert!(engine.pages().len() >= 2); assert!(engine.changed_pages().iter().all(|page| *page >= 1)); } #[test] fn incremental_layout_respects_insertion_class_limits() { let rule = VerticalItem::Rule { width: 65_536, height: 200, }; let mut document = Document::new( 1000, vec![ Unit::paragraph(1, "body"), Unit::insertion(2, 1, 200, vec![rule.clone()]), Unit::insertion(3, 1, 200, vec![rule]), ], ); document.insertion_classes = vec![InsertionClass { number: 1, fraction_percent: 30, max_height: None, skip: None, }]; let mut engine = Engine::layout(&document); assert_eq!(engine.pages().len(), 2); assert_eq!(engine.pages()[0].insertions.len(), 1); engine.edit(&document, 1, "changed body"); assert_eq!(engine.pages().len(), 2); assert_eq!(engine.pages()[0].insertions.len(), 1); assert_eq!(engine.pages()[1].insertions.len(), 1); } #[test] fn insertion_class_skip_reserves_space_for_that_class() { let insertion = |id| { Unit::insertion( id, 1, 480, vec![VerticalItem::Rule { width: 65_536, height: 480, }], ) }; let mut document = Document::new(1000, vec![insertion(1), insertion(2)]); document.insertion_classes = vec![InsertionClass { number: 1, fraction_percent: 100, max_height: None, skip: Some(50), }]; 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); document.insertion_classes[0].skip = None; assert_eq!(Engine::layout(&document).pages().len(), 1); } #[test] fn incremental_layout_respects_insertion_class_skip() { let mut style = ParagraphStyle::default(); style.line_height = 500; let mut document = Document::new( 1000, vec![ Unit::paragraph_with_style(1, "body", style), Unit::insertion( 2, 1, 480, vec![VerticalItem::Rule { width: 65_536, height: 480, }], ), ], ); document.insertion_classes = vec![InsertionClass { number: 1, fraction_percent: 100, max_height: None, skip: Some(50), }]; let mut engine = Engine::layout(&document); assert_eq!(engine.pages().len(), 2); engine.edit(&document, 0, "changed body"); assert_eq!(engine.pages().len(), 2); } #[test] fn insertion_skip_reserves_space_before_the_first_insertion() { let insertion = || { Unit::insertion( 2, 1, 80, vec![VerticalItem::Rule { width: 65_536, height: 80, }], ) }; let mut document = Document::new(100, vec![Unit::rule(1, 10, 10), insertion()]); document.insertion_classes = vec![InsertionClass { number: 1, fraction_percent: 100, max_height: None, skip: None, }]; assert_eq!(Engine::layout(&document).pages().len(), 1); document.insertion_skip = 20; let layout = Engine::layout(&document); assert_eq!(layout.pages().len(), 2); assert_eq!(layout.pages()[0].insertions.len(), 0); assert_eq!(layout.pages()[1].insertions.len(), 1); // A body plus insertion plus skip that exactly fills the page must not // be pushed to a second page. let mut exact = Document::new( 100, vec![ Unit::rule(1, 10, 10), Unit::insertion( 2, 1, 70, vec![VerticalItem::Rule { width: 65_536, height: 70, }], ), ], ); exact.insertion_skip = 20; exact.insertion_classes = vec![InsertionClass { number: 1, fraction_percent: 100, max_height: None, skip: None, }]; assert_eq!(Engine::layout(&exact).pages().len(), 1); } #[test] fn incremental_layout_places_a_fitting_late_top_float_the_same_way() { let mut document = Document::new( 100, vec![ Unit::paragraph(1, "body text"), Unit::float(2, FloatPlacement::Top, 40, 20), Unit::paragraph(3, "more text"), ], ); document.top_skip = 0; let mut engine = Engine::layout(&document); let full_pages = engine.pages().len(); let full_floats = engine.pages()[0].floats.len(); engine.edit(&document, 3, "changed text"); assert_eq!(engine.pages().len(), full_pages); assert_eq!(engine.pages()[0].floats.len(), full_floats); } #[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 { gap_before: 0, gap_after: 0, 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; document.text_float_sep = 0; 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 { gap_before: 0, gap_after: 0, 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 { gap_before: 0, gap_after: 0, 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; document.text_float_sep = 0; 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 edited_layout_respects_float_page_fraction() { let document = { let mut document = Document::new( 100, vec![ Unit::float(0, FloatPlacement::Top, 40, 60), Unit::paragraph(1, "body text"), ], ); document.top_skip = 0; document.text_fraction_percent = 0; document.float_page_fraction_percent = 60; document }; let mut engine = Engine::layout(&document); assert_eq!(engine.pages().len(), 2); assert!(engine.pages()[0].items.is_empty()); engine.edit(&document, 1, "edited body text".to_string()); assert_eq!( engine.pages().len(), 2, "edited layout must keep float-page fraction" ); assert!(engine.pages()[0].items.is_empty()); } #[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 { gap_before: 0, gap_after: 0, placement: FloatPlacement::Top, width: 50 * 65_536, height: 15 * 65_536, content: Vec::new(), }, Float { gap_before: 0, gap_after: 0, 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("/Filter /FlateDecode")); assert!(text.contains("/ToUnicode")); assert!(text.contains("Tj")); assert!(text.trim_end().ends_with("%%EOF")); } #[test] fn pdf_subset_keeps_only_used_glyphs() { let document = Document::new(400, vec![Unit::paragraph(1, "caf\u{e9}")]); 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); let length1 = text .split("/Length1 ") .nth(1) .and_then(|rest| rest.split_whitespace().next()) .and_then(|value| value.parse::().ok()) .expect("FontFile2 /Length1"); assert!( length1 < crate::pdf::full_face_size(crate::render::FontFace::Roman), "subset {length1} should be smaller than the full face {}", crate::pdf::full_face_size(crate::render::FontFace::Roman) ); assert!(text.contains("/Filter /FlateDecode")); } #[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.text_float_sep = 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.text_float_sep = 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(" = page .display_list() .items .iter() .filter_map(|item| match item { DisplayItem::Rule { y, height: 100, .. } => Some(*y), _ => None, }) .collect(); assert_eq!(ys, vec![0, 150]); engine.edit(&document, 3, "changed body"); assert_eq!(engine.pages()[0].floats[1].gap_before, 50); } #[test] fn text_float_sep_keeps_body_below_top_floats() { let mut document = Document::new( 1000, vec![ Unit::float(1, FloatPlacement::Top, 100, 100), Unit::float(2, FloatPlacement::Top, 100, 100), Unit::rule(3, 100, 10), ], ); document.top_skip = 0; document.float_sep = 50; document.text_float_sep = 30; let engine = Engine::layout(&document); let page = &engine.pages()[0]; assert_eq!(page.floats.len(), 2); let ys: Vec = page .display_list_with_layout(1000, document.text_float_sep) .items .iter() .filter_map(|item| match item { DisplayItem::Rule { y, height: 10, .. } => Some(*y), _ => None, }) .collect(); assert_eq!( ys, vec![280], "body starts after both floats, floatsep, and textfloatsep" ); } #[test] fn text_float_sep_separates_body_from_bottom_floats() { fn document(text_float_sep: i64) -> Document { let mut document = Document::new( 1000, vec![ Unit::rule(1, 100, 800), Unit::float_with_content( 2, FloatPlacement::Bottom, 100, 80, vec![VerticalItem::Rule { width: 100, height: 80, }], ), ], ); document.top_skip = 0; document.text_float_sep = text_float_sep; document } assert_eq!(Engine::layout(&document(0)).pages().len(), 1); assert_eq!( Engine::layout(&document(200)).pages().len(), 2, "a 200pt separation no longer leaves room for the bottom float" ); let document = document(30); let engine = Engine::layout(&document); assert_eq!(engine.pages().len(), 1); let ys: Vec = engine.pages()[0] .display_list_with_layout(1000, 30) .items .iter() .filter_map(|item| match item { DisplayItem::Rule { y, height: 80, .. } => Some(*y), _ => None, }) .collect(); assert_eq!(ys, vec![920], "bottom float sits below the text separation"); } #[test] fn text_float_sep_is_counted_once_for_a_late_top_float() { let mut document = Document::new( 1000, vec![ Unit::rule(1, 100, 10), Unit::float(2, FloatPlacement::Top, 100, 100), Unit::rule(3, 100, 10), ], ); document.top_skip = 0; document.text_float_sep = 30; let engine = Engine::layout(&document); let page = &engine.pages()[0]; assert_eq!(page.floats.len(), 1); let ys: Vec = page .display_list_with_layout(1000, document.text_float_sep) .items .iter() .filter_map(|item| match item { DisplayItem::Rule { y, height: 10, .. } => Some(*y), _ => None, }) .collect(); assert_eq!( ys, vec![130, 140], "the late float reserves one textfloatsep" ); } #[test] fn incremental_layout_honours_text_float_sep() { let mut document = Document::new( 1000, vec![ Unit::float(1, FloatPlacement::Top, 100, 100), Unit::paragraph(2, "body"), ], ); document.top_skip = 0; document.text_float_sep = 30; let mut engine = Engine::layout(&document); fn body_y(engine: &Engine) -> i64 { engine.pages()[0] .display_list_with_layout(1000, 30) .items .iter() .filter_map(|item| match item { DisplayItem::Text { y, text, .. } if text == "b" => Some(*y), _ => None, }) .min() .expect("body glyph") } let initial = body_y(&engine); assert!(initial >= 130, "body starts below the reserved separation"); engine.edit(&document, 2, "changed body"); assert!(body_y(&engine) >= 130); } #[test] fn float_height_covers_its_content() { let unit = Unit::float_with_content( 1, FloatPlacement::Top, 100, 5, vec![VerticalItem::Rule { width: 100, height: 30, }], ); let VerticalItem::Float(float) = &unit.items[0] else { panic!("expected float"); }; assert_eq!(float.height, 30); assert_eq!(float.content_height(), 30); } #[test] fn float_carries_vertical_content() { let unit = Unit::float_with_content( 1, FloatPlacement::Top, 100, 20, vec![VerticalItem::Rule { width: 100, height: 2, }], ); let VerticalItem::Float(float) = &unit.items[0] else { panic!("expected float"); }; assert_eq!(float.content.len(), 1); let encoded = serde_json::to_string(float).unwrap(); let decoded: Float = serde_json::from_str(&encoded).unwrap(); assert_eq!(decoded.content.len(), 1); } #[test] fn mark_and_float_constructors_build_page_items() { let mut document = Document::new( 100, vec![ Unit::mark(1, 0, "Intro"), Unit::float(2, FloatPlacement::Top, 50, 20), Unit::vertical( 3, vec![VerticalItem::Box(VerticalBox { width: 100, height: 50, })], ), ], ); document.text_float_sep = 0; let engine = Engine::layout(&document); assert_eq!(engine.pages().len(), 1); assert_eq!(engine.pages()[0].marks[0].text, "Intro"); assert_eq!(engine.pages()[0].floats.len(), 1); } #[test] fn forced_penalty_between_boxes_starts_a_page() { let block = |id| { Unit::vertical( id, vec![VerticalItem::Box(VerticalBox { width: 100, height: 30, })], ) }; let document = Document::new(100, vec![block(1), Unit::penalty(2, -10_000), block(3)]); let engine = Engine::layout(&document); assert_eq!(engine.pages().len(), 2); } #[test] fn vskip_consumes_vertical_space() { let block = |id| { Unit::vertical( id, vec![VerticalItem::Box(VerticalBox { width: 100, height: 30, })], ) }; let document = Document::new(50, vec![block(1), Unit::vskip(2, 10), block(3)]); let engine = Engine::layout(&document); assert_eq!(engine.pages().len(), 2); } #[test] fn vertical_rules_consume_page_height() { let unit = Unit::rule(1, 100, 60); let document = Document::new(100, vec![unit]); let engine = Engine::layout(&document); assert_eq!(engine.pages().len(), 1); let unit = Unit::rule(2, 100, 60); let document = Document::new(100, vec![unit.clone(), unit]); let engine = Engine::layout(&document); assert_eq!(engine.pages().len(), 2); } #[test] fn halign_skips_noalign_material() { let unit = Unit::halign_from_source(1, r"A & B \\ \noalign{\vskip 4pt} C & D", 2, 10); let VerticalItem::Halign(table) = &unit.items[0] else { panic!("expected halign") }; assert_eq!(table.rows.len(), 2); assert_eq!(table.rows[1].cells[0].text, "C"); } #[test] fn halign_template_centers_and_right_aligns_cells() { let unit = Unit::halign_from_source_with_template(1, "lcr", r"A & B & C", 10); let VerticalItem::Halign(halign) = &unit.items[0] else { panic!("expected halign"); }; assert_eq!(halign.rows[0].cells[1].alignment, CellAlignment::Center); assert_eq!(halign.rows[0].cells[2].alignment, CellAlignment::Right); } #[test] fn halign_source_parses_hline_rules() { let unit = Unit::halign_from_source(1, r"A & B \\ \hline C & D", 2, 10); let VerticalItem::Halign(halign) = &unit.items[0] else { panic!("expected halign"); }; assert!(halign.rows.iter().any(|row| row.rule)); assert_eq!(halign.rows.last().unwrap().cells.len(), 2); } #[test] fn halign_source_parses_omit_span_and_multispan() { let unit = Unit::halign_from_source(1, r"A & B \\ \omit C & \multispan{2} D", 3, 10); let VerticalItem::Halign(halign) = &unit.items[0] else { panic!("expected halign"); }; assert_eq!(halign.rows.len(), 2); assert_eq!(halign.rows[1].cells[0].text, "C"); assert_eq!(halign.rows[1].cells[0].span, 1); assert_eq!(halign.rows[1].cells[1].span, 2); } #[test] fn halign_computes_natural_column_widths() { 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.column_widths, vec![5242880, 655360]); assert_eq!(halign.width, 7208960); assert_eq!(halign.height, 1_599_078); } #[test] fn halign_splits_at_row_boundaries() { let rows = vec![ HalignRow { cells: vec![HalignCell { text: "A".to_owned(), span: 1, alignment: CellAlignment::Left, }], rule: false, }, HalignRow { cells: vec![HalignCell { text: "B".to_owned(), span: 1, alignment: CellAlignment::Left, }], rule: false, }, HalignRow { cells: vec![HalignCell { text: "C".to_owned(), span: 1, alignment: CellAlignment::Left, }], rule: false, }, ]; let unit = Unit::halign(0, rows, 1, 0); let VerticalItem::Halign(halign) = &unit.items[0] else { panic!("expected halign"); }; let chunks = halign.split_for_height(1_700_000); assert_eq!(chunks.len(), 2); assert_eq!(chunks[0].rows.len(), 2); assert_eq!(chunks[1].rows.len(), 1); assert_eq!(chunks[0].height, 2 * halign.line_height); assert_eq!(chunks[1].height, halign.line_height); } #[test] fn tall_halign_splits_across_pages() { let rows = vec![ HalignRow { cells: vec![HalignCell { text: "A".to_owned(), span: 1, alignment: CellAlignment::Left, }], rule: false, }, HalignRow { cells: vec![HalignCell { text: "B".to_owned(), span: 1, alignment: CellAlignment::Left, }], rule: false, }, HalignRow { cells: vec![HalignCell { text: "C".to_owned(), span: 1, alignment: CellAlignment::Left, }], rule: false, }, ]; let document = Document::new(2_000_000, vec![Unit::halign(0, rows, 1, 0)]); let layout = Engine::layout(&document); assert_eq!(layout.pages().len(), 2); assert_eq!(layout.pages()[0].items.len(), 1); assert_eq!(layout.pages()[1].items.len(), 1); } #[test] fn checkpoint_round_trips_through_serde() { let engine = Engine::layout(&document()); let encoded = serde_json::to_string(engine.checkpoints()).unwrap(); let decoded: Vec = serde_json::from_str(&encoded).unwrap(); assert_eq!(engine.checkpoints(), decoded.as_slice()); } #[test] fn here_float_reserves_intextsep_above_and_below() { let mut document = Document::new( 1000, vec![ Unit::rule(1, 100, 10), Unit::float(2, FloatPlacement::Here, 40, 20), Unit::rule(3, 100, 10), ], ); document.top_skip = 0; document.in_text_sep = 30; document.text_float_sep = 0; let engine = Engine::layout(&document); assert_eq!(engine.pages().len(), 1); let list = engine.pages()[0].display_list_with_layout(1000, 0); let float_y = list .items .iter() .find_map(|item| match item { DisplayItem::Rule { y, width: 40, height: 20, .. } => Some(*y), _ => None, }) .expect("here float is painted"); assert_eq!(float_y, 40, "intextsep keeps the float below the body"); let body: Vec = list .items .iter() .filter_map(|item| match item { DisplayItem::Rule { y, width: 100, height: 10, .. } => Some(*y), _ => None, }) .collect(); assert_eq!(body, vec![0, 90], "intextsep separates the float and body"); } #[test] fn here_float_moves_to_a_new_page_when_it_does_not_fit() { let mut document = Document::new( 100, vec![ Unit::rule(1, 100, 70), Unit::float(2, FloatPlacement::Here, 40, 20), Unit::rule(3, 100, 10), ], ); document.top_skip = 0; document.in_text_sep = 10; document.text_float_sep = 0; let engine = Engine::layout(&document); assert_eq!(engine.pages().len(), 2); assert!(engine.pages()[0].floats.is_empty()); let page = &engine.pages()[1]; assert_eq!(page.floats.len(), 1); assert_eq!(page.floats[0].placement, FloatPlacement::Here); assert_eq!(page.items.len(), 2, "float and trailing body item"); let ys: Vec<(i64, i64)> = page .display_list_with_layout(100, 0) .items .iter() .filter_map(|item| match item { DisplayItem::Rule { y, height, .. } => Some((*y, *height)), _ => None, }) .collect(); assert_eq!(ys, vec![(0, 20), (30, 10)]); } #[test] fn incremental_layout_keeps_here_floats_in_flow() { let mut document = Document::new( 1000, vec![ Unit::paragraph(0, "alpha"), Unit::float(1, FloatPlacement::Here, 40, 20), Unit::paragraph(2, "beta"), ], ); document.in_text_sep = 30; document.text_float_sep = 0; let mut engine = Engine::layout(&document); let mut edited = Document::new( 1000, vec![ Unit::paragraph(0, "alpha changed"), Unit::float(1, FloatPlacement::Here, 40, 20), Unit::paragraph(2, "beta"), ], ); edited.text_float_sep = 0; edited.in_text_sep = 30; engine.edit(&edited, 0, "alpha changed"); assert_eq!(engine.pages().len(), 1); assert_eq!(engine.pages()[0].floats.len(), 1); assert_eq!(engine.pages()[0].floats[0].placement, FloatPlacement::Here); } #[test] fn top_float_pages_do_not_consume_topskip() { let unit = Unit { id: 0, source: "top float".to_owned(), paragraph_style: None, items: vec![ VerticalItem::Float(Float { placement: FloatPlacement::Top, width: 40, height: 20, gap_before: 0, gap_after: 0, content: Vec::new(), }), VerticalItem::Box(VerticalBox { width: 10, height: 60, }), ], }; let mut document = Document::new(100, vec![unit]); document.top_skip = 20; document.text_float_sep = 10; document.float_page_fraction_percent = 10; let engine = Engine::layout(&document); assert_eq!( engine.pages().len(), 1, "topskip must not push the body off a float page" ); let list = engine.pages()[0].display_list_with_layout(100, 10); let float_y = list .items .iter() .filter_map(|item| match item { DisplayItem::Rule { y, height: 20, .. } => Some(*y), _ => None, }) .min() .unwrap(); assert_eq!(float_y, 0, "the float starts at the top margin"); } #[test] fn paged_layout_breaks_simple_vertical_lists() { let document = Document::new( 100, vec![ Unit::rule(1, 100, 60), Unit::vskip(2, 0), Unit::rule(3, 100, 60), Unit::vskip(4, 0), Unit::rule(5, 100, 60), ], ); let engine = Engine::layout_paged(&document).expect("simple documents are page-buildable"); assert_eq!(engine.pages().len(), 3); assert_eq!(engine.pages()[0].sources, vec![(1, source_hash(""))]); assert!(engine.pages().iter().all(|page| page.hash != 0)); } #[test] fn paged_layout_refuses_floats_and_insertions() { let floated = Document::new(100, vec![Unit::float(1, FloatPlacement::Top, 100, 20)]); assert!(Engine::layout_paged(&floated).is_none()); let insertion = Document::new(100, vec![Unit::insertion(1, 0, 10, Vec::new())]); assert!(Engine::layout_paged(&insertion).is_none()); } #[test] fn paged_layout_edit_relayouts_and_reports_changes() { let style = ParagraphStyle { line_width: 100 * 65_536, line_height: 12 * 65_536, ..ParagraphStyle::default() }; let document = Document::new( 20 * 65_536, vec![ Unit::paragraph_with_style_and_face( 1, "alpha beta", style.clone(), ParagraphFont::Roman, ), Unit::vskip(2, 0), Unit::paragraph_with_style_and_face(3, "gamma delta", style, ParagraphFont::Roman), ], ); let mut engine = Engine::layout_paged(&document).expect("paragraphs are page-buildable"); assert_eq!(engine.pages().len(), 2); let first = engine.pages()[0].hash; engine.edit(&document, 3, "epsilon zeta"); assert_eq!(engine.pages()[0].hash, first); assert!(engine.changed_pages().contains(&1)); assert_eq!(engine.recomputed_pages(), engine.pages().len()); } }