pub mod cmr10; pub mod math; pub mod output; pub mod page; pub mod paragraph; pub mod pdf; pub mod render; mod subset; pub mod tfm; pub mod type1; pub use cmr10::Cmr10Metrics; use std::collections::BTreeMap; pub use page::VerticalGlue; use page::{InsertionLimit, PageBuilder, PageFragment, 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 horizontal rule at a `\halign` row boundary. #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, serde::Serialize, serde::Deserialize)] pub struct HalignRule { /// Boundary the rule sits above; `rows.len()` paints below the table. pub row: usize, /// First covered column. pub start: usize, /// Last covered column (inclusive). pub end: usize, /// Thickness in scaled points (booktabs heavy/light rule widths). pub width: i64, /// Space trimmed from the left edge (`\cmidrule(lr)`). #[serde(default)] pub trim_left: i64, /// Space trimmed from the right edge (`\cmidrule(lr)`). #[serde(default)] pub trim_right: i64, } /// 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, /// Per-column `p{width}` declarations; `Some` makes the column wrap. #[serde(default)] pub column_wrap: Vec>, /// Glue before each column boundary (TeX `\tabskip`); empty falls back to /// the uniform intercolumn spacing derived from `width`. #[serde(default)] pub column_skips: Vec, /// Painted rules (booktabs heavy/light rules and partial `\cmidrule`s). #[serde(default)] pub rules: Vec, /// Extra vertical glue after each row (TeX `\noalign{\vskip ...}`). #[serde(default)] pub row_gaps: Vec, /// Leading rows repeated on the first page only (longtable `\endfirsthead`). #[serde(default)] pub first_head_len: usize, /// Rows after the first head repeated on continuation pages (`\endhead`). #[serde(default)] pub head_len: usize, /// Trailing rows painted only on the last page (`\endfoot`/`\endlastfoot`). #[serde(default)] pub foot_len: usize, 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), /// Glue with TeX stretch and shrink, used for vertical glue setting. StretchGlue(VerticalGlue), 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. /// Split the table into page-sized row chunks, repeating longtable heads /// and painting the foot block only on the last chunk. pub fn split_for_height(&self, max_height: i64) -> Vec { if self.first_head_len > 0 || self.head_len > 0 || self.foot_len > 0 { self.split_for_height_with_heads(max_height) } else { self.split_for_height_without_heads(max_height) } } fn split_for_height_with_heads(&self, max_height: i64) -> Vec { let max_height = max_height.max(self.line_height); let first_len = self.first_head_len.min(self.rows.len()); let head_len = self.head_len.min(self.rows.len().saturating_sub(first_len)); let body_start = first_len + head_len; let foot_len = self .foot_len .min(self.rows.len().saturating_sub(body_start)); let body_end = self.rows.len() - foot_len; let first_prefix: Vec = (0..first_len).collect(); let continuation_prefix: Vec = if first_len == 0 { (0..head_len).collect() } else { (first_len..body_start).collect() }; let height_of = |rows: &[usize]| -> i64 { rows.iter() .map(|&index| self.row_height(index) + self.row_gap(index)) .sum() }; let foot_rows: Vec = (body_end..self.rows.len()).collect(); let foot_height = height_of(&foot_rows); let mut chunks = Vec::new(); let mut cursor = body_start; let mut first_chunk = true; loop { let prefix = if first_chunk { &first_prefix } else { &continuation_prefix }; let mut body_rows: Vec = Vec::new(); let mut height = height_of(prefix); while cursor < body_end { let row_height = self.row_height(cursor) + self.row_gap(cursor); if !body_rows.is_empty() && height + row_height > max_height { break; } body_rows.push(cursor); height += row_height; cursor += 1; } let last = cursor >= body_end; let mut chunk_rows: Vec = Vec::new(); chunk_rows.extend(prefix.iter().copied()); chunk_rows.extend(body_rows.iter().copied()); if last && foot_len > 0 { chunk_rows.extend(foot_rows.iter().copied()); height += foot_height; } let mut rules = Vec::new(); if let (Some(first), Some(last)) = (prefix.first(), prefix.last()) { for rule in self .rules .iter() .filter(|rule| rule.row >= *first && rule.row <= last + 1) { rules.push(HalignRule { row: rule.row - first, ..*rule }); } } if let (Some(first), Some(last)) = (body_rows.first(), body_rows.last()) { let offset = prefix.len(); let lower = if prefix.is_empty() { *first } else { first + 1 }; for rule in self .rules .iter() .filter(|rule| rule.row >= lower && rule.row <= last + 1) { rules.push(HalignRule { row: offset + rule.row - first, ..*rule }); } } if last { if let (Some(first), Some(last)) = (foot_rows.first(), foot_rows.last()) { let offset = prefix.len() + body_rows.len(); for rule in self .rules .iter() .filter(|rule| rule.row > *first && rule.row <= last + 1) { rules.push(HalignRule { row: offset + rule.row - first, ..*rule }); } } } chunks.push(Self { rows: chunk_rows .iter() .map(|&index| self.rows[index].clone()) .collect(), column_widths: self.column_widths.clone(), column_wrap: self.column_wrap.clone(), column_skips: self.column_skips.clone(), rules, row_gaps: chunk_rows .iter() .map(|&index| self.row_gap(index)) .collect(), first_head_len: 0, head_len: 0, foot_len: 0, width: self.width, height, line_height: self.line_height, }); first_chunk = false; if last { break; } } chunks } fn split_for_height_without_heads(&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 in 0..self.rows.len() { let row_height = self.row_height(index) + self.row_gap(index); if index > start && height + row_height > max_height { chunks.push(Self { rows: self.rows[start..index].to_vec(), column_widths: self.column_widths.clone(), column_wrap: self.column_wrap.clone(), column_skips: self.column_skips.clone(), rules: self.rules_for_chunk(start, index), row_gaps: self .row_gaps .get(start..index) .map(<[_]>::to_vec) .unwrap_or_default(), first_head_len: 0, head_len: 0, foot_len: 0, 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(), column_wrap: self.column_wrap.clone(), column_skips: self.column_skips.clone(), rules: self.rules_for_chunk(start, self.rows.len()), row_gaps: self .row_gaps .get(start..) .map(<[_]>::to_vec) .unwrap_or_default(), first_head_len: 0, head_len: 0, foot_len: 0, width: self.width, height, line_height: self.line_height, }); chunks } /// Column index of `cell_index` inside `row`. fn cell_column(&self, row: &HalignRow, cell_index: usize) -> usize { row.cells[..cell_index.min(row.cells.len())] .iter() .map(|cell| cell.span.max(1)) .sum() } /// The aligned rectangle of a cell: `(x, width)`. pub fn cell_box(&self, row_index: usize, cell_index: usize) -> Option<(i64, i64)> { let (x, width) = self.cell_span(row_index, cell_index)?; let row = self.rows.get(row_index)?; let cell = row.cells.get(cell_index)?; let text_width = text_width(&cell.text); 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)) } /// The rectangle of the columns a cell covers, before alignment. pub fn cell_span(&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 gaps: i64 = (column..column + span - 1) .map(|boundary| self.gap_width(boundary)) .sum(); let width = self.column_widths[column..column + span] .iter() .sum::() + gaps; let x: i64 = self.column_widths[..column].iter().sum::() + (0..column) .map(|boundary| self.gap_width(boundary)) .sum::(); Some((x, width)) } /// The wrapped lines of a cell; a single line unless its column declares /// `p{width}`. pub fn cell_lines(&self, row_index: usize, cell_index: usize) -> Vec { let row = match self.rows.get(row_index) { Some(row) => row, None => return Vec::new(), }; let cell = match row.cells.get(cell_index) { Some(cell) => cell, None => return Vec::new(), }; if cell.span.max(1) == 1 { let column = self.cell_column(row, cell_index); if let Some(Some(width)) = self.column_wrap.get(column) { return wrap_cell_text(&cell.text, *width); } } vec![cell.text.clone()] } /// Height of one row, counting wrapped cell lines. /// Extra vertical glue after `row_index` (TeX `\noalign{\vskip ...}`). pub fn row_gap(&self, index: usize) -> i64 { self.row_gaps.get(index).copied().unwrap_or(0) } pub fn row_height(&self, row_index: usize) -> i64 { let row = match self.rows.get(row_index) { Some(row) => row, None => return 0, }; if row.rule { return 26_214; } let lines = (0..row.cells.len()) .map(|index| self.cell_lines(row_index, index).len()) .max() .unwrap_or(1) .max(1); self.line_height * lines as i64 } /// Uniform intercolumn spacing derived from the table width. fn uniform_intercolumn(&self) -> i64 { if self.column_widths.len() > 1 { (self.width - self.column_widths.iter().copied().sum::()) / (self.column_widths.len() as i64 - 1) } else { 0 } } /// Width of the glue before `column` (boundary `column - 1`). fn gap_width(&self, boundary: usize) -> i64 { if self.column_skips.is_empty() { self.uniform_intercolumn() } else { self.column_skips.get(boundary).copied().unwrap_or(0) } } /// Rules that belong to the page chunk covering rows `start..end`. fn rules_for_chunk(&self, start: usize, end: usize) -> Vec { self.rules .iter() .filter_map(|rule| { let belongs = (rule.row > start && rule.row <= end) || (start == 0 && rule.row == 0); if belongs { Some(HalignRule { row: rule.row - start, ..*rule }) } else { None } }) .collect() } /// Left edge of a column (including all gaps before it). fn column_offset(&self, column: usize) -> i64 { let column = column.min(self.column_widths.len()); self.column_widths[..column].iter().sum::() + (0..column) .map(|boundary| self.gap_width(boundary)) .sum::() } /// Horizontal rectangle of one rule: `(x, width)`. pub fn rule_rect(&self, rule: &HalignRule) -> (i64, i64) { let last = self.column_widths.len().saturating_sub(1); let start = rule.start.min(last); let end = rule.end.min(last).max(start); let x = self.column_offset(start) + rule.trim_left; let right = (self.column_offset(end + 1) - rule.trim_right).min(self.width); (x, (right - x).max(65_536)) } } /// Natural width of a run of text at the illustrative 10pt metrics. pub(crate) fn text_width(text: &str) -> i64 { text.chars() .map(|character| { if character.is_whitespace() { 4 * 65_536 } else { 10 * 65_536 } }) .sum() } /// Greedily wrap `text` so each line fits `width`. fn wrap_cell_text(text: &str, width: i64) -> Vec { let width = width.max(65_536); let mut lines = Vec::new(); let mut line = String::new(); let mut line_width = 0_i64; for word in text.split_whitespace() { let word_width = text_width(word); let gap = if line.is_empty() { 0 } else { 4 * 65_536 }; if !line.is_empty() && line_width + gap + word_width > width { lines.push(std::mem::take(&mut line)); line_width = 0; } if !line.is_empty() && line_width + gap <= width { line.push(' '); line_width += gap; } if word_width <= width - line_width { line.push_str(word); line_width += word_width; } else { for character in word.chars() { let character_width = if character.is_whitespace() { 4 * 65_536 } else { 10 * 65_536 }; if line_width + character_width > width && !line.is_empty() { lines.push(std::mem::take(&mut line)); line_width = 0; } line.push(character); line_width += character_width; } } } if !line.is_empty() { lines.push(line); } if lines.is_empty() { lines.push(String::new()); } lines } /// Parse a TeX dimension such as `25mm`, `2cm`, `72bp` or `10pt`. fn parse_tex_dimension(spec: &str) -> Option { let spec = spec.trim(); if spec.is_empty() { return None; } let split = spec .find(|character: char| character.is_alphabetic()) .unwrap_or(spec.len()); let (number, unit) = spec.split_at(split); let value: f64 = number.trim().parse().ok()?; let points_per_unit = match unit.trim() { "pt" => 1.0, "bp" => 72.27 / 72.0, "mm" => 72.27 / 25.4, "cm" => 72.27 / 2.54, "in" => 72.27, "em" => 10.0, _ => return None, }; Some((value * points_per_unit * 65_536.0).round() as i64) } /// Vertical glue inside `\noalign{...}`. fn noalign_gap(material: &str) -> Option { let material = material.trim(); let mut rest = material .strip_prefix(r"\vskip") .or_else(|| material.strip_prefix(r"\vspace"))? .trim_start(); if let Some(inner) = rest.strip_prefix('{') { rest = inner.split_once('}')?.0.trim(); } let spec = rest.split_whitespace().next()?; parse_tex_dimension(spec) } /// Strip booktabs rule commands from a row, recording their spans. fn take_booktabs_rules(raw: &str, row: usize, columns: usize) -> (String, Vec) { let mut rules = Vec::new(); let mut remaining = raw.trim(); loop { let trimmed = remaining.trim_start(); let end = columns.saturating_sub(1); let (width, rest) = if let Some(rest) = trimmed.strip_prefix(r"\toprule") { (Some(52_429), rest) } else if let Some(rest) = trimmed.strip_prefix(r"\bottomrule") { (Some(52_429), rest) } else if let Some(rest) = trimmed.strip_prefix(r"\midrule") { (Some(32_768), rest) } else { (None, trimmed) }; if let Some(width) = width { rules.push(HalignRule { row, start: 0, end, width, trim_left: 0, trim_right: 0, }); remaining = rest.trim_start(); continue; } if let Some(rest) = trimmed.strip_prefix(r"\cmidrule") { let mut rest = rest.trim_start(); let mut trim_left = 0_i64; let mut trim_right = 0_i64; if let Some(after_open) = rest.strip_prefix('(') { if let Some((options, tail)) = after_open.split_once(')') { if options.contains('l') { trim_left = 4 * 65_536; } if options.contains('r') { trim_right = 4 * 65_536; } rest = tail.trim_start(); } } if let Some(body) = rest.strip_prefix('{') { if let Some((span, tail)) = body.split_once('}') { let (left, right) = span.split_once('-').unwrap_or((span, span)); let start = left.trim().parse::().unwrap_or(1).saturating_sub(1); let end = right .trim() .parse::() .unwrap_or(columns) .saturating_sub(1) .min(columns.saturating_sub(1)); if start <= end { rules.push(HalignRule { row, start, end, width: 32_768, trim_left, trim_right, }); } remaining = tail.trim_start(); continue; } } } break; } (remaining.to_owned(), rules) } /// Glue overrides introduced by `@{}` / `@{\hspace{...}}` in a column template. fn parse_at_glues(template: &str) -> Vec> { let mut columns = 0_usize; let mut overrides: Vec<(usize, Option)> = Vec::new(); let mut characters = template.chars().peekable(); while let Some(character) = characters.next() { match character { 'l' | 'L' | 'c' | 'C' | 'r' | 'R' => columns += 1, 'p' | 'P' => { columns += 1; if characters.peek() == Some(&'{') { characters.next(); for inner in characters.by_ref() { if inner == '}' { break; } } } } '@' => { let mut value = Some(0_i64); if characters.peek() == Some(&'{') { characters.next(); let mut spec = String::new(); let mut depth = 0_usize; for inner in characters.by_ref() { match inner { '{' => { depth += 1; spec.push('{'); } '}' => { if depth == 0 { break; } depth -= 1; spec.push('}'); } other => spec.push(other), } } let spec = spec.trim(); if !spec.is_empty() { value = parse_at_glue(spec); } } overrides.push((columns, value)); } _ => {} } } let mut glue = vec![None; columns + 1]; for (boundary, value) in overrides { if let Some(slot) = glue.get_mut(boundary) { *slot = value; } } glue } /// Parse the body of an `@{\hspace{...}}` column expression. fn parse_at_glue(spec: &str) -> Option { let spec = spec.trim(); let rest = spec .strip_prefix(r"\hspace") .or_else(|| spec.strip_prefix(r"\hskip"))?; let rest = rest.trim_start(); let rest = rest.strip_prefix('*').unwrap_or(rest).trim_start(); let body = rest.strip_prefix('{')?.split_once('}')?.0; parse_tex_dimension(body) } /// Parse an alignment template into per-column alignment and wrap widths. fn parse_column_template(template: &str) -> (Vec, Vec>) { let mut alignments = Vec::new(); let mut wraps = Vec::new(); let mut characters = template.chars().peekable(); while let Some(character) = characters.next() { match character { 'l' | 'L' => { alignments.push(CellAlignment::Left); wraps.push(None); } 'c' | 'C' => { alignments.push(CellAlignment::Center); wraps.push(None); } 'r' | 'R' => { alignments.push(CellAlignment::Right); wraps.push(None); } 'p' | 'P' => { let mut wrap = None; if characters.peek() == Some(&'{') { characters.next(); let mut spec = String::new(); for inner in characters.by_ref() { if inner == '}' { break; } spec.push(inner); } wrap = parse_tex_dimension(&spec); } alignments.push(CellAlignment::Left); wraps.push(wrap); } '|' | ' ' => {} '@' => { if characters.peek() == Some(&'{') { characters.next(); let mut depth = 0_usize; for inner in characters.by_ref() { match inner { '{' => depth += 1, '}' => { if depth == 0 { break; } depth -= 1; } _ => {} } } } } _ => { alignments.push(CellAlignment::Left); wraps.push(None); } } } if alignments.is_empty() { alignments.push(CellAlignment::Left); wraps.push(None); } (alignments, wraps) } /// 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::StretchGlue(glue) => glue.width.max(0), 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, /// Inline styled runs for a paragraph unit, when the paragraph mixes faces. #[serde(default)] pub paragraph_runs: Option>, /// Extra vertical glue before this unit (TeX `\vskip`/`\smallskip`). #[serde(default)] pub space_before: i64, /// Stretch of the glue before this unit. #[serde(default)] pub space_stretch: i64, /// Shrink of the glue before this unit. #[serde(default)] pub space_shrink: i64, } impl Unit { /// Build a simple `\halign` table with natural column widths. pub fn halign(id: UnitId, rows: Vec, column_count: usize, intercolumn: i64) -> Self { Self::halign_with_wraps( id, rows, column_count, intercolumn, vec![None; column_count], ) } /// Build a `\halign` table, honouring `p{width}` column declarations. pub fn halign_with_wraps( id: UnitId, rows: Vec, column_count: usize, intercolumn: i64, wraps: Vec>, ) -> Self { Self::halign_with_layout(id, rows, column_count, intercolumn, wraps, Vec::new()) } /// Build a `\halign` table with explicit inter-column glue (`\tabskip`). pub fn halign_with_layout( id: UnitId, rows: Vec, column_count: usize, intercolumn: i64, wraps: Vec>, column_skips: Vec, ) -> 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 = text_width(&cell.text); if let Some(slot) = column_widths.get_mut(column) { *slot = (*slot).max(width); } } column += span; } } let span_gaps = |column: usize, span: usize| -> i64 { if column_skips.is_empty() { intercolumn * (span.saturating_sub(1) as i64) } else { column_skips .iter() .skip(column) .take(span.saturating_sub(1)) .copied() .sum() } }; 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 = span_gaps(column, span); let available: i64 = column_widths[column..column + span] .iter() .copied() .sum::() + gaps; let extra = (text_width(&cell.text) - available).max(0); for offset in 0..span { column_widths[column + offset] += extra / span as i64; } } column += span; } } for (index, wrap) in wraps.iter().enumerate() { if let (Some(width), Some(slot)) = (wrap, column_widths.get_mut(index)) { *slot = (*width).max(10 * 65_536); } } let gaps: i64 = if column_skips.is_empty() { intercolumn * column_count.saturating_sub(1) as i64 } else { column_skips.iter().copied().sum() }; let width = column_widths.iter().sum::() + gaps; let line_height = 12 * 65_536; let mut halign = Halign { rows, column_widths, column_wrap: wraps, column_skips, rules: Vec::new(), row_gaps: Vec::new(), first_head_len: 0, head_len: 0, foot_len: 0, width, height: 0, line_height, }; halign.height = (0..halign.rows.len()) .map(|index| halign.row_height(index) + halign.row_gap(index)) .sum(); Self { id, source: "halign".to_owned(), paragraph_style: None, paragraph_runs: None, space_before: 0, space_stretch: 0, space_shrink: 0, items: vec![VerticalItem::Halign(halign)], } } /// 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 { Self::halign_from_source_with_template_and_tabskips( id, template, source, intercolumn, Vec::new(), ) } /// Parse a column template and accept explicit `\tabskip` glue widths. pub fn halign_from_source_with_template_and_tabskips( id: UnitId, template: &str, source: &str, intercolumn: i64, tabskips: Vec, ) -> Self { let (alignments, wraps) = parse_column_template(template); let column_count = alignments.len().max(1); let at_glue = parse_at_glues(template); let mut rows = Vec::new(); let mut rules: Vec = Vec::new(); let mut row_gaps: Vec = Vec::new(); let mut pending_gap = 0_i64; let mut first_head_end: Option = None; let mut head_end: Option = None; let mut body_start: Option = None; for raw_row in source.split(r"\\") { if raw_row.trim().is_empty() { continue; } let (rule_text, collected) = take_booktabs_rules(raw_row.trim(), rows.len(), column_count); rules.extend(collected); let mut raw_row = rule_text.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((material, tail)) = body.split_once('}') { if let Some(gap) = noalign_gap(material) { pending_gap = gap; } raw_row = tail.trim(); } } } if let Some(rest) = raw_row.strip_prefix(r"\endfirsthead") { first_head_end = Some(rows.len()); raw_row = rest.trim(); } else if let Some(rest) = raw_row.strip_prefix(r"\endhead") { head_end = Some(rows.len()); raw_row = rest.trim(); } else if let Some(rest) = raw_row.strip_prefix(r"\endlastfoot") { body_start = Some(rows.len()); raw_row = rest.trim(); } else if let Some(rest) = raw_row.strip_prefix(r"\endfoot") { head_end.get_or_insert(rows.len()); raw_row = rest.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), }); } if !rows.is_empty() { row_gaps.resize(rows.len(), 0); row_gaps[rows.len() - 1] = pending_gap; } pending_gap = 0; rows.push(HalignRow { cells, rule: false }); } let first_len = first_head_end.unwrap_or(0); let head_end = head_end.unwrap_or(first_len); let body_start = body_start.unwrap_or(head_end); let head_len = head_end.saturating_sub(first_len); let foot_len = body_start.saturating_sub(head_end); let body_len = rows.len().saturating_sub(body_start); if foot_len > 0 { let mut reordered = Vec::with_capacity(rows.len()); reordered.extend_from_slice(&rows[..head_end]); reordered.extend_from_slice(&rows[body_start..]); reordered.extend_from_slice(&rows[head_end..body_start]); rows = reordered; for rule in rules.iter_mut() { if rule.row <= head_end { // Head rows stay at the front. } else if rule.row >= body_start { rule.row -= foot_len; } else { rule.row += body_len; } } } let mut column_skips = tabskips; if at_glue.iter().any(|value| value.is_some()) { let default_gap = intercolumn.saturating_mul(65_536); let mut merged = vec![default_gap; column_count.saturating_sub(1)]; for (slot, width) in merged.iter_mut().zip(column_skips.iter()) { *slot = *width; } for boundary in 1..column_count { if let Some(Some(width)) = at_glue.get(boundary).copied() { merged[boundary - 1] = width; } } column_skips = merged; } let mut unit = Self::halign_with_layout(id, rows, column_count, intercolumn, wraps, column_skips); if let Some(VerticalItem::Halign(halign)) = unit.items.first_mut() { halign.rules = rules; halign.first_head_len = first_len.min(halign.rows.len()); halign.head_len = head_len.min(halign.rows.len() - halign.first_head_len); halign.foot_len = foot_len.min(halign.rows.len() - halign.first_head_len - halign.head_len); if !row_gaps.is_empty() { halign.row_gaps = row_gaps; halign.height = (0..halign.rows.len()) .map(|index| halign.row_height(index) + halign.row_gap(index)) .sum(); } } unit } /// 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)]) } /// Vertical glue with explicit stretch, shrink and TeX glue order. /// /// Order 0 is ordinary glue, 1 is `\vfil`, 2 `\vfill`, 3 `\vfilll`; a /// page is set with the highest order that carries stretch. pub fn vglue(id: UnitId, width: i64, stretch: i64, shrink: i64, order: u8) -> Self { Self::vertical( id, vec![VerticalItem::StretchGlue(VerticalGlue::with_order( width, stretch, shrink, order, ))], ) } /// 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 whose text is split into styled runs. pub fn paragraph_with_style_and_runs( id: UnitId, source: impl Into, style: ParagraphStyle, runs: Vec<(ParagraphFont, String)>, ) -> Self { let source = source.into(); let paragraph = crate::paragraph::layout_paragraph_runs(&runs, &style); Self { id, source, items: vec![VerticalItem::Paragraph(paragraph)], paragraph_style: Some(style), paragraph_runs: Some(runs), space_before: 0, space_stretch: 0, space_shrink: 0, } } /// 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), paragraph_runs: None, space_before: 0, space_stretch: 0, space_shrink: 0, } } /// Build a unit from a math atom using CMR10 metrics. /// One vertical unit holding a display formula split into lines. pub fn math_lines( id: UnitId, lines: &[crate::math::MathAtom], font: &crate::cmr10::Cmr10Metrics, ) -> Self { let items = lines .iter() .map(|atom| { let math_box = crate::math::layout_math(atom, font); VerticalItem::Math { atom: atom.clone(), width: math_box.width, height: math_box.height, depth: math_box.depth, } }) .collect(); Self::vertical(id, items) } 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, paragraph_runs: None, space_before: 0, space_stretch: 0, space_shrink: 0, } } /// 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, /// TeX's `\count` in thousandths: page space reserved by this /// class per unit of insertion height. The default `1000` reserves exactly /// the insertion height; footnote and float classes differ in TeX. #[serde(default = "default_insertion_multiplier")] pub multiplier: u32, } fn default_insertion_multiplier() -> u32 { 1000 } #[derive(Clone, Debug, PartialEq, Eq, serde::Serialize, serde::Deserialize)] pub struct Document { pub units: Vec, pub page_goal: i64, /// Unit indices that start on a fresh page (TeX `\newpage` forced breaks). #[serde(default)] pub page_breaks: Vec, /// TeX `\paperwidth`: width of the output page. #[serde(default = "default_paper_width")] pub paper_width: i64, /// TeX `\paperheight`: height of the output page. #[serde(default = "default_paper_height")] pub paper_height: i64, /// TeX `\hsize`: width of the page box handed to the output routine. #[serde(default = "default_text_width")] pub text_width: i64, /// TeX-like `\topskip`: distance from the page top to the first baseline. #[serde(default)] pub top_skip: i64, /// TeX-like `\maxdepth`: depth a page box keeps below the baseline. Deeper /// material moves into the page height, as in TeX's page builder. #[serde(default)] pub max_depth: 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, /// TeX `\raggedbottom` (default) versus `\flushbottom`: when false the /// paged builder stretches each page's glue so it reaches the page goal. #[serde(default = "default_ragged_bottom")] pub ragged_bottom: bool, /// 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's `\splittopskip`: glue placed at the top of insertion material /// carried over to the next page. Defaults to 10pt. #[serde(default = "default_split_top_skip")] pub split_top_skip: i64, /// TeX's `\splitmaxdepth`: maximum depth kept for the first box of /// insertion material carried over to the next page. Any excess depth is /// moved into that box's height. Defaults to `\maxdimen` (no clamping). #[serde(default = "default_split_max_depth")] pub split_max_depth: 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, /// TeX stretch for the `\parskip` glue inserted between paragraphs. #[serde(default)] pub par_skip_stretch: i64, /// TeX shrink for the `\parskip` glue inserted between paragraphs. #[serde(default)] pub par_skip_shrink: i64, /// Extra horizontal displacement of the page origin (`\hoffset`). #[serde(default)] pub h_offset: i64, /// Extra vertical displacement of the page origin (`\voffset`). #[serde(default)] pub v_offset: i64, /// TeX `\maxdeadcycles`: how many pages the output routine may decline to /// ship before TeX ships the page itself. Defaults to 25. #[serde(default = "default_max_deadcycles")] pub max_deadcycles: i64, /// TeX `\output` token list, interpreted by [`output::OutputProgram`]. /// `None` ships every page the builder produces. #[serde(default)] pub output_routine: Option, } fn default_paper_width() -> i64 { 612 * 65_536 } fn default_paper_height() -> i64 { 792 * 65_536 } fn default_text_width() -> i64 { 345 * 65_536 } fn default_text_fraction() -> u8 { 50 } fn default_float_sep() -> i64 { 12 * 65_536 } fn default_split_max_depth() -> i64 { i64::MAX } fn default_split_top_skip() -> i64 { 10 * 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_ragged_bottom() -> bool { true } fn default_top_fraction() -> u8 { 70 } fn default_top_number() -> u8 { 2 } fn default_bottom_number() -> u8 { 1 } fn default_total_number() -> u8 { 12 } fn default_max_deadcycles() -> i64 { 25 } impl Document { pub fn new(page_goal: i64, units: Vec) -> Self { Self { units, page_goal, page_breaks: Vec::new(), paper_width: default_paper_width(), paper_height: default_paper_height(), text_width: default_text_width(), top_skip: 0, max_depth: 0, text_fraction_percent: default_text_fraction(), float_page_fraction_percent: 50, bottom_fraction_percent: default_bottom_fraction(), ragged_bottom: default_ragged_bottom(), 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, split_top_skip: default_split_top_skip(), split_max_depth: default_split_max_depth(), float_sep: default_float_sep(), text_float_sep: default_text_float_sep(), in_text_sep: default_in_text_sep(), par_skip: 0, par_skip_stretch: 0, par_skip_shrink: 0, h_offset: 0, v_offset: 0, max_deadcycles: default_max_deadcycles(), output_routine: None, } } /// Page space reserved by `height` of insertion material in `class`, /// after applying TeX's `\count` multiplier (thousandths). pub fn insertion_reserve(&self, class: u8, height: i64) -> i64 { let multiplier = self .insertion_classes .iter() .find(|entry| entry.number == class) .map_or(1000, |entry| entry.multiplier); height.saturating_mul(i64::from(multiplier)) / 1000 } /// Maximum height available to one insertion class on a page. pub fn insertion_class_limit(&self, class: u8) -> i64 { let fraction = self.insertion_fraction_limit(class); self.insertion_classes .iter() .find(|entry| entry.number == class) .and_then(|entry| entry.max_height) .map_or(fraction, |absolute| fraction.min(absolute)) } /// Percentage share of the page that insertion class `class` may occupy. pub fn insertion_fraction_limit(&self, class: u8) -> i64 { self.insertion_classes .iter() .find(|entry| entry.number == class) .map_or(self.page_goal, |entry| { self.page_goal * i64::from(entry.fraction_percent) / 100 }) } pub fn with_top_skip(mut self, top_skip: i64) -> Self { self.top_skip = top_skip; self } /// 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`]. /// /// Units made of box/glue/penalty/mark material can be expressed as /// page-builder nodes today (a unit may contribute several nodes and be /// split across pages); insertion classes become [`VerticalNode::Insertion`] /// reservations and floats become top, bottom or in-text nodes. A paragraph /// expands to one node per line with a zero-width interline glue between /// lines, which is the legal breakpoint that lets a page break inside it. /// `None` means the document holds material the paged builder cannot express /// yet. fn document_nodes( document: &Document, ) -> Option<(Vec, Vec, Vec)> { let mut nodes = Vec::new(); let mut owners = Vec::new(); let mut items = Vec::new(); let mut previous_paragraph = false; for (index, unit) in document.units.iter().enumerate() { if document.page_breaks.binary_search(&index).is_ok() { nodes.push(VerticalNode::Penalty(-10_000)); owners.push(index); items.push(VerticalItem::Penalty(-10_000)); } if unit.space_before > 0 { nodes.push(VerticalNode::Glue(VerticalGlue::new( unit.space_before, unit.space_stretch, unit.space_shrink, ))); owners.push(index); items.push(VerticalItem::Glue(unit.space_before)); } for (position, item) in unit.items.iter().enumerate() { if position == 0 && previous_paragraph && matches!(item, VerticalItem::Paragraph(_)) { nodes.push(VerticalNode::Glue(VerticalGlue::new( document.par_skip, document.par_skip_stretch, document.par_skip_shrink, ))); owners.push(index); items.push(VerticalItem::StretchGlue(VerticalGlue::new( document.par_skip, document.par_skip_stretch, document.par_skip_shrink, ))); } if let VerticalItem::Paragraph(paragraph) = item { if paragraph.lines.len() > 1 { // TeX breaks pages between lines. Expand a paragraph into // one node per line so the page builder is free to break // inside it; each slice renders as its own single-line // paragraph and keeps the baselines of its own line. let mut remaining = paragraph.clone(); loop { let tail = if remaining.lines.len() > 1 { Some(remaining.split_at(1)) } else { None }; let remaining_depth = if remaining.height > remaining.depth { remaining.depth } else { 0 }; // The line grid already budgets the descent; keep the // grid height and report the descent separately for // `\pagedepth`/`\maxdepth`. nodes.push(VerticalNode::Box { height: remaining.height, depth: remaining_depth, }); owners.push(index); items.push(VerticalItem::Paragraph(remaining.clone())); match tail { Some(tail) => { // TeX puts interline glue between lines; a // zero-width glue node is the legal breakpoint // the page builder needs to split here. nodes.push(VerticalNode::Glue(VerticalGlue::new(0, 0, 0))); owners.push(index); items.push(VerticalItem::Glue(0)); remaining = tail; } None => break, } } continue; } } if let VerticalItem::Halign(halign) = item { let capacity = (document.page_goal - document.top_skip) .max(halign.line_height) .max(1); let chunks = halign.split_for_height(capacity); if chunks.len() > 1 { // TeX breaks a long alignment at row boundaries; each // chunk becomes its own vertical node with a zero glue // between them so the page builder can break there. let last = chunks.len() - 1; for (chunk_index, chunk) in chunks.into_iter().enumerate() { nodes.push(VerticalNode::Box { height: chunk.height, depth: 0, }); owners.push(index); items.push(VerticalItem::Halign(chunk)); if chunk_index < last { nodes.push(VerticalNode::Glue(VerticalGlue::new(0, 0, 0))); owners.push(index); items.push(VerticalItem::Glue(0)); } } previous_paragraph = false; continue; } } let node = 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: if paragraph.height > paragraph.depth { paragraph.depth } else { 0 }, }, VerticalItem::Halign(halign) => VerticalNode::Box { height: halign.height, depth: 0, }, VerticalItem::Glue(height) => VerticalNode::Glue(VerticalGlue::new(*height, 0, 0)), VerticalItem::StretchGlue(glue) => VerticalNode::Glue(*glue), VerticalItem::Penalty(value) => VerticalNode::Penalty(*value), VerticalItem::Mark(mark) => VerticalNode::Mark(mark.clone()), VerticalItem::Insertion(insertion) => VerticalNode::Insertion { class: insertion.class, height: document.insertion_reserve(insertion.class, insertion.height), }, VerticalItem::Float(float) => match float.placement { FloatPlacement::Top => VerticalNode::Float { height: float.height, }, FloatPlacement::Bottom => VerticalNode::BottomFloat { height: float.height, }, // In-text floats are body material: reserve the float plus // its `\intextsep` gaps, then paint it inline when the page // is assembled. FloatPlacement::Here => VerticalNode::Box { height: float.height + float.gap_before.max(0) + float.gap_after.max(0), depth: 0, }, }, }; nodes.push(node); owners.push(index); items.push(item.clone()); } previous_paragraph = unit .items .last() .is_some_and(|item| matches!(item, VerticalItem::Paragraph(_))); } Some((nodes, owners, items)) } 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::StretchGlue(glue) => glue.width.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, } } /// TeX depth contributed by a vertical item. Only paragraph and math items /// currently carry depth; boxes have no depth field. fn item_depth(item: &VerticalItem) -> i64 { match item { VerticalItem::Paragraph(paragraph) => paragraph.depth, VerticalItem::Math { depth, .. } => *depth, _ => 0, } } /// TeX `\splitmaxdepth`: clamp the depth of the first box in held-over /// insertion material, moving the excess depth into its height so the page /// accounts for it exactly once. fn clamp_split_depth(document: &Document, material: &mut [VerticalItem]) { let limit = document.split_max_depth.max(0); for item in material.iter_mut() { let depth = item_depth(item); if depth <= limit { continue; } let excess = depth - limit; match item { VerticalItem::Paragraph(paragraph) => { paragraph.height += excess; paragraph.depth = limit; } VerticalItem::Math { height, depth, .. } => { *height += excess; *depth = limit; } _ => {} } return; } } /// TeX `\prevgraf` for a finished page: the line count of the last paragraph /// broken on it. fn page_prev_graf(page: &Page) -> i64 { page.items .iter() .rev() .find_map(|item| match item { VerticalItem::Paragraph(paragraph) => Some(paragraph.lines.len() as i64), _ => None, }) .unwrap_or(0) } /// Take the longest prefix of `items` whose reserved height fits `capacity`. /// /// Returns `(accepted, remainder, reserved_height)`. A single item larger than /// the capacity is still accepted alone: TeX only splits insertion material at /// item boundaries. /// TeX starts a split insertion's continuation with `\splittopskip`. Only add /// the glue when the class capacity can also hold the first content item; /// otherwise a class with no remaining capacity would accept the glue forever /// and never make progress. fn held_insertion_material( document: &Document, capacity: i64, mut material: Vec, ) -> Vec { let split = document.split_top_skip.max(0); let first = material .iter() .map(item_height) .find(|height| *height > 0) .unwrap_or(0); if !material.is_empty() && split > 0 && capacity >= split.saturating_add(first) { material.insert(0, VerticalItem::Glue(split)); } clamp_split_depth(document, &mut material); material } fn take_insertion_prefix( _class: u8, items: Vec, capacity: i64, multiplier: i64, ) -> (Vec, Vec, i64) { let mut accepted = Vec::new(); let mut reserved = 0_i64; let mut rest = items.into_iter(); let mut remainder = Vec::new(); while let Some(item) = rest.next() { let reserve = item_height(&item).saturating_mul(multiplier) / 1000; if reserved + reserve <= capacity { accepted.push(item); reserved += reserve; continue; } if accepted.is_empty() { reserved += reserve; accepted.push(item); } else { remainder.push(item); } remainder.extend(rest); break; } (accepted, remainder, reserved) } fn attach_insertion( insertions: &mut BTreeMap, used: &mut BTreeMap, class: u8, accepted: Vec, reserved: i64, ) { if accepted.is_empty() && reserved == 0 { return; } *used.entry(class).or_insert(0) += reserved; let entry = insertions.entry(class).or_insert_with(|| Insertion { class, height: 0, items: Vec::new(), }); entry.height += reserved; entry.items.extend(accepted); } 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. /// Place a paragraph into the vertical flow, splitting it at line boundaries /// when it cannot fit on the current page. TeX breaks between lines; the /// scrolled page builder used to move whole paragraphs and silently overflow. #[allow(clippy::too_many_arguments)] fn place_paragraph_flow( pages: &mut Vec, current: &mut Page, used: &mut i64, insertion_height: &mut i64, paragraph: &Paragraph, page_goal: i64, top_skip: i64, par_skip: i64, par_skip_stretch: i64, par_skip_shrink: i64, bottom: i64, ) { let mut pending = paragraph.clone(); loop { let at_top = current.items.is_empty() && !page_has_top_float_material(current); let skip = if current.items.is_empty() { 0 } else { par_skip }; let skip_stretch = if current.items.is_empty() { 0 } else { par_skip_stretch }; let skip_shrink = if current.items.is_empty() { 0 } else { par_skip_shrink }; let base = if at_top { top_skip } else { *used + skip }; let available = page_goal - *insertion_height - bottom - base; let lines = pending.lines.len(); if pending.height <= available.max(0) { if at_top { *used = top_skip.max(pending.height); } else { if skip != 0 || skip_stretch != 0 || skip_shrink != 0 { current .items .push(VerticalItem::StretchGlue(VerticalGlue::new( skip, skip_stretch, skip_shrink, ))); } *used = base + pending.height; } current.items.push(VerticalItem::Paragraph(pending)); return; } let line_height = (pending.height / lines as i64).max(1); let fit = (available.max(0) / line_height) as usize; if fit == 0 { if at_top { // A single line cannot be split; keep TeX's overfull page. *used = top_skip.max(pending.height); current.items.push(VerticalItem::Paragraph(pending)); return; } pages.push(std::mem::replace(current, Page::empty())); *used = top_skip; *insertion_height = 0; continue; } let mut head = pending.clone(); let tail = head.split_at(fit); if at_top { *used = top_skip.max(head.height); } else { if skip != 0 || skip_stretch != 0 || skip_shrink != 0 { current .items .push(VerticalItem::StretchGlue(VerticalGlue::new( skip, skip_stretch, skip_shrink, ))); } *used = base + head.height; } current.items.push(VerticalItem::Paragraph(head)); pages.push(std::mem::replace(current, Page::empty())); *used = top_skip; *insertion_height = 0; pending = tail; } } /// TeX insertion placement shared by the initial and incremental builders. /// /// Insertion material stays on the page where its anchor text ends. When the /// page cannot hold all of it, the part that fits at an item boundary stays /// and the remainder is held over to the next page (TeX's split insertions). fn place_insertion( document: &Document, pages: &mut Vec, current: &mut Page, used: &mut i64, insertion_height: &mut i64, insertion: &Insertion, ) { let mut pending = insertion.clone(); loop { let class = pending.class; let gap = if current.insertions.is_empty() { document.insertion_skip_for(class).max(0) } else { 0 }; let capacity = document .page_goal .saturating_sub(document.top_skip) .saturating_sub(gap) .max(1); let class_limit = document.insertion_class_limit(class).min(capacity).max(1); let class_height: i64 = current .insertions .iter() .filter(|entry| entry.class == class) .map(|entry| document.insertion_reserve(entry.class, entry.height)) .sum(); let reserved = document.insertion_reserve(class, pending.height); let room = document .page_goal .saturating_sub(*used) .saturating_sub(gap) .saturating_sub(*insertion_height) .max(0); if class_height + reserved <= class_limit && reserved <= room { *insertion_height += gap + reserved; current.insertions.push(pending); return; } let page_has_content = !current.items.is_empty() || !current.insertions.is_empty(); if page_has_content { let available = room.min(class_limit.saturating_sub(class_height)); if available > 0 && let Some((head, tail)) = split_insertion(document, &pending, available) { *insertion_height += gap + document.insertion_reserve(class, head.height); current.insertions.push(head); pages.push(std::mem::replace(current, Page::empty())); *used = document.top_skip; *insertion_height = 0; pending = tail; continue; } pages.push(std::mem::replace(current, Page::empty())); *used = document.top_skip; *insertion_height = 0; continue; } if let Some((head, tail)) = split_insertion(document, &pending, class_limit) { *insertion_height = gap + document.insertion_reserve(class, head.height); current.insertions.push(head); pages.push(std::mem::replace(current, Page::empty())); *used = document.top_skip; *insertion_height = 0; pending = tail; continue; } *insertion_height = gap + reserved; current.insertions.push(pending); return; } } /// Split an insertion at an item boundary, returning the part that fits in /// `available` reserved space and the held-over remainder. fn split_insertion( document: &Document, insertion: &Insertion, available: i64, ) -> Option<(Insertion, Insertion)> { let class = insertion.class; let mut head = Vec::new(); let mut head_height = 0i64; for (index, item) in insertion.items.iter().enumerate() { let height = item_height(item); if head.is_empty() && document.insertion_reserve(class, height) > available { return None; } if !head.is_empty() && document.insertion_reserve(class, head_height + height) > available { let tail_items = insertion.items[index..].to_vec(); let tail_height: i64 = tail_items.iter().map(item_height).sum(); return Some(( Insertion { class, height: head_height, items: head, }, Insertion { class, height: tail_height, items: tail_items, }, )); } head.push(item.clone()); head_height += height; } None } 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, /// Node index that starts each page of a paged layout. Empty when the /// layout came from the scrolling builder or cannot be replayed partially. #[serde(default)] pub paged_page_nodes: 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) {} } /// State carried between interpreted output-routine runs in a paged layout. /// /// TeX's output registers are global: an assignment made while shipping one /// page changes what later pages see. Keeping the state next to the page loop /// lets a `\dimen` assignment shrink the capacity of the next page's /// insertion class, as it does inside TeX's output routine. struct PagedOutput { program: output::OutputProgram, goal: i64, pageno: i64, deadcycles: i64, counts: [i64; 256], dimens: [i64; 256], skips: [i64; 256], initial_dimens: Vec<(u8, i64)>, initial_skips: Vec<(u8, i64)>, pending_marks: Vec<(u8, String)>, } impl PagedOutput { fn new(document: &Document, program: output::OutputProgram) -> Self { let mut counts = [1000_i64; 256]; let mut dimens = [0_i64; 256]; let mut skips = [0_i64; 256]; let mut initial_dimens = Vec::new(); let mut initial_skips = Vec::new(); for class in &document.insertion_classes { let slot = class.number as usize; counts[slot] = i64::from(class.multiplier); dimens[slot] = class.max_height.unwrap_or(0); skips[slot] = class.skip.unwrap_or(document.insertion_skip); initial_dimens.push((class.number, dimens[slot])); initial_skips.push((class.number, skips[slot])); } Self { program, goal: document.page_goal, pageno: 1, deadcycles: 0, counts, dimens, skips, initial_dimens, initial_skips, pending_marks: Vec::new(), } } #[allow(clippy::too_many_arguments)] fn ship( &mut self, document: &Document, page: &Page, page_goal: i64, penalty: i64, depth: i64, stretch: i64, stretches: [i64; 4], shrink: i64, badness: i64, insert_penalties: i64, ) -> Option { let page_total: i64 = page.items.iter().map(item_height).sum(); let mut context = output::OutputContext { page_goal, page_total, page_depth: depth, page_stretch: stretch, page_fil_stretch: stretches[1], page_fill_stretch: stretches[2], page_filll_stretch: stretches[3], page_shrink: shrink, vbadness: badness, hsize: document.text_width, vsize: self.goal, top_skip: document.top_skip, max_depth: document.max_depth, output_penalty: penalty, max_deadcycles: document.max_deadcycles, insertion_counts: self.counts, insertion_dimens: self.dimens, insertion_skips: self.skips, output_marks: Vec::new(), pageno: self.pageno, deadcycles: self.deadcycles, prev_graf: page_prev_graf(page), insert_penalties, }; let forced = self.deadcycles >= document.max_deadcycles.max(0); if forced { context.deadcycles = 0; } let shipped_now = if forced { 1 } else { self.program.shipout_count(&mut context).ok()? }; self.counts = context.insertion_counts; self.dimens = context.insertion_dimens; self.skips = context.insertion_skips; self.pending_marks = std::mem::take(&mut context.output_marks); self.goal = context.vsize.max(1); self.pageno = context.pageno.wrapping_add(1); self.deadcycles = context.deadcycles; if shipped_now > 0 { self.deadcycles = 0; Some(true) } else { self.deadcycles += 1; Some(false) } } } /// Insertion capacity in force before the next page is assembled. /// TeX's `\count` multiplier in force before the next page. fn output_insertion_multiplier( document: &Document, class: u8, routine: Option<&PagedOutput>, ) -> i64 { let initial = document .insertion_classes .iter() .find(|entry| entry.number == class) .map_or(1000, |entry| i64::from(entry.multiplier)); match routine { Some(routine) if routine.counts[class as usize] != initial => { routine.counts[class as usize].max(0) } _ => initial, } } fn output_insertion_limit(document: &Document, class: u8, routine: Option<&PagedOutput>) -> i64 { let fraction = document.insertion_fraction_limit(class); let absolute = match routine { Some(routine) => { let slot = class as usize; let initial = routine .initial_dimens .iter() .find(|(number, _)| *number == class) .map_or(0, |(_, value)| *value); if routine.dimens[slot] == initial { class_backstop(document, class, fraction) } else { routine.dimens[slot] } } None => class_backstop(document, class, fraction), }; fraction.min(absolute.max(0)) } fn output_insertion_skip(document: &Document, class: u8, routine: Option<&PagedOutput>) -> i64 { let initial = document .insertion_classes .iter() .find(|entry| entry.number == class) .and_then(|entry| entry.skip) .unwrap_or(document.insertion_skip); match routine { Some(routine) => { let slot = class as usize; let known = routine .initial_skips .iter() .find(|(number, _)| *number == class) .map_or(initial, |(_, value)| *value); if routine.skips[slot] == known { initial } else { routine.skips[slot].max(0) } } None => initial, } } fn class_backstop(document: &Document, class: u8, fraction: i64) -> i64 { document .insertion_classes .iter() .find(|entry| entry.number == class) .and_then(|entry| entry.max_height) .unwrap_or(fraction) } 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; } if document.page_breaks.binary_search(&unit_index).is_ok() && !current.items.is_empty() { 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(), }); if unit.space_before > 0 && !current.items.is_empty() { let lead = unit.space_before; let bottom = bottom_float_area(¤t, document.text_float_sep); if used + lead > document.page_goal - insertion_height - bottom { pages.push(std::mem::replace(&mut current, Page::empty())); used = document.top_skip; insertion_height = 0; } else { used += lead; current.items.push(VerticalItem::Glue(lead)); } } 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 bottom = bottom_float_area(¤t, document.text_float_sep); place_paragraph_flow( &mut pages, &mut current, &mut used, &mut insertion_height, paragraph, document.page_goal, document.top_skip, document.par_skip.max(0), document.par_skip_stretch.max(0), document.par_skip_shrink.max(0), bottom, ); } 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::StretchGlue(glue) => { if !current.items.is_empty() { used += glue.width.max(0); 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) => { place_insertion( document, &mut pages, &mut current, &mut used, &mut insertion_height, insertion, ); } 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(), paged_page_nodes: Vec::new(), }, } } pub fn pages(&self) -> &[Page] { &self.layout.pages } /// TeX `\topmark` when shipping out `page`: the last mark left by an /// earlier page, carried forward until a page defines its own. pub fn top_mark(&self, page: usize, class: u8) -> Option<&Mark> { (0..page).rev().find_map(|index| { self.layout.pages.get(index).and_then(|candidate| { candidate .marks .iter() .rev() .find(|mark| mark.class == class) }) }) } /// TeX `\firstmark` when shipping out `page`. pub fn first_mark(&self, page: usize, class: u8) -> Option<&Mark> { self.layout .pages .get(page) .and_then(|candidate| candidate.marks.iter().find(|mark| mark.class == class)) .or_else(|| self.top_mark(page, class)) } /// TeX `\botmark` when shipping out `page`. pub fn bot_mark(&self, page: usize, class: u8) -> Option<&Mark> { self.layout .pages .get(page) .and_then(|candidate| { candidate .marks .iter() .rev() .find(|mark| mark.class == class) }) .or_else(|| self.top_mark(page, class)) } 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 /// vertical items (boxes, rules, paragraphs, math, haligns, glue, penalties /// and marks). Insertion classes are laid out here too, including material /// held over past the class limit. Floats still make it return `None`, /// because their placement belongs to the incremental builder for now. pub fn layout_paged(document: &Document) -> Option { let (nodes, owners, node_items) = document_nodes(document)?; if let Some(source) = &document.output_routine { let program = output::OutputProgram::parse(source).ok()?; let plain = document.insertion_classes.is_empty() && nodes.iter().all(|node| { !matches!( node, VerticalNode::Insertion { .. } | VerticalNode::Float { .. } | VerticalNode::BottomFloat { .. } ) }); if plain && program.assigns_vsize() { return Self::layout_paged_variable_goal( document, &nodes, &owners, &node_items, &program, ); } } let mut builder = Self::paged_builder(document); let mut routine = match &document.output_routine { Some(source) => Some(PagedOutput::new( document, output::OutputProgram::parse(source).ok()?, )), None => None, }; let mut pages = Vec::new(); let mut held: BTreeMap> = BTreeMap::new(); let mut fragments = builder.build_with_deferred_bottom_floats(&nodes); let mut carried_marks: Vec<(u8, String)> = Vec::new(); let mut page_index = 0; while page_index < fragments.len() { let fragment = fragments[page_index].clone(); let fragment = &fragment; let mut items = Vec::new(); let mut marks = Vec::new(); let mut floats: Vec = fragment .bottom_floats .iter() .map(|height| Float { placement: FloatPlacement::Bottom, width: 0, height: *height, gap_before: 0, gap_after: 0, content: Vec::new(), }) .collect(); let mut sources = Vec::new(); let mut insert_penalties = 0_i64; let mut insertions: BTreeMap = BTreeMap::new(); let mut used: BTreeMap = BTreeMap::new(); // Material held over from the previous page fills its class first. let held_classes: Vec = held.keys().copied().collect(); for class in held_classes { let material = held.remove(&class).unwrap_or_default(); let limit = output_insertion_limit(document, class, routine.as_ref()); let capacity = (limit - used.get(&class).copied().unwrap_or(0)).max(0); let material = held_insertion_material(document, capacity, material); let multiplier = output_insertion_multiplier(document, class, routine.as_ref()); let (accepted, remainder, reserved) = take_insertion_prefix(class, material, capacity, multiplier); attach_insertion(&mut insertions, &mut used, class, accepted, reserved); if !remainder.is_empty() { held.insert(class, remainder); } } for index in fragment.start..fragment.end { let item = &node_items[index]; let unit = &document.units[owners[index]]; if sources.last().map(|(id, _)| *id) != Some(unit.id) { sources.push((unit.id, source_hash(&unit.source))); } match item { VerticalItem::Mark(mark) => marks.push(mark.clone()), VerticalItem::Insertion(insertion) => { let class = insertion.class; let limit = output_insertion_limit(document, class, routine.as_ref()); let capacity = (limit - used.get(&class).copied().unwrap_or(0)).max(0); let multiplier = output_insertion_multiplier(document, class, routine.as_ref()); let (accepted, remainder, reserved) = take_insertion_prefix( class, insertion.items.clone(), capacity, multiplier, ); attach_insertion(&mut insertions, &mut used, class, accepted, reserved); if !remainder.is_empty() { insert_penalties += remainder.len() as i64; held.entry(class).or_default().extend(remainder); } } item @ VerticalItem::Float(float) => match float.placement { FloatPlacement::Here => items.push(item.clone()), FloatPlacement::Top => floats.push(float.clone()), // Bottom floats, including deferred ones carried from // the previous page, arrive through the fragment. FloatPlacement::Bottom => {} }, other => items.push(other.clone()), } } Self::set_page_glue(&mut items, fragment); let mut page = Page::empty(); page.items = items; if !carried_marks.is_empty() { let mut marks_with_carry: Vec = std::mem::take(&mut carried_marks) .into_iter() .map(|(class, text)| Mark { class, text }) .collect(); marks_with_carry.append(&mut marks); marks = marks_with_carry; } page.marks = marks; page.floats = floats; let reserved: i64 = insertions.values().map(|insertion| insertion.height).sum(); page.insertions = insertions.into_values().collect(); let insertion_skip: i64 = page .insertions .iter() .map(|insertion| output_insertion_skip(document, insertion.class, routine.as_ref())) .sum(); page.sources = sources; page.seal_in_place(); let shipped = match routine.as_mut() { Some(routine) => routine.ship( document, &page, (builder.page_goal - reserved - insertion_skip).max(0), fragment.penalty, fragment.depth, fragment.stretch, fragment.stretches, fragment.shrink, fragment.badness, insert_penalties, )?, None => true, }; if shipped { pages.push(page); } carried_marks = routine .as_ref() .map(|active| active.pending_marks.clone()) .unwrap_or_default(); if let Some(active) = routine.as_ref() { let goal = active.goal; let has_bottom_float = nodes .iter() .any(|node| matches!(node, VerticalNode::BottomFloat { .. })); let mut skips = builder.insertion_skips.clone(); let mut skip_changed = false; for (class, skip) in &mut skips { let assigned = output_insertion_skip(document, *class, routine.as_ref()); if assigned != *skip { *skip = assigned; skip_changed = true; } } if (goal != builder.page_goal || skip_changed) && !has_bottom_float { let next_start = fragments .get(page_index + 1) .map_or(nodes.len(), |next| next.start); builder.set_page_goal(goal); builder.insertion_skips = skips; fragments.truncate(page_index + 1); fragments.extend(builder.build_from(&nodes, next_start)); } } page_index += 1; } // Insertion material that did not fit its class limit on the page where // it was raised is carried to dedicated pages, as TeX holds it over. while !held.is_empty() { let classes: Vec = held.keys().copied().collect(); let mut insertions: BTreeMap = BTreeMap::new(); let mut used: BTreeMap = BTreeMap::new(); for class in classes { let material = held.remove(&class).unwrap_or_default(); let limit = document.insertion_class_limit(class); let material = held_insertion_material(document, limit, material); let multiplier = document .insertion_classes .iter() .find(|entry| entry.number == class) .map_or(1000, |entry| i64::from(entry.multiplier)); let (accepted, remainder, reserved) = take_insertion_prefix(class, material, limit, multiplier); attach_insertion(&mut insertions, &mut used, class, accepted, reserved); if !remainder.is_empty() { held.insert(class, remainder); } } let mut page = Page::empty(); let reserved: i64 = insertions.values().map(|insertion| insertion.height).sum(); page.insertions = insertions.into_values().collect(); let insertion_skip: i64 = page .insertions .iter() .map(|insertion| output_insertion_skip(document, insertion.class, routine.as_ref())) .sum(); page.seal_in_place(); let shipped = match routine.as_mut() { Some(routine) => routine.ship( document, &page, (builder.page_goal - reserved - insertion_skip).max(0), 10_000, 0, 0, [0; 4], 0, 10_000, 0, )?, None => true, }; if shipped { pages.push(page); } } let paged_page_nodes = if document.output_routine.is_none() && pages.len() == fragments.len() { fragments.iter().map(|fragment| fragment.start).collect() } else { Vec::new() }; let count = pages.len(); Some(Self { layout: Layout { pages, checkpoints: Vec::new(), recomputed_pages: 0, changed_pages: (0..count).collect(), paged_page_nodes, }, }) } /// 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; } fn paged_builder(document: &Document) -> PageBuilder { PageBuilder { page_goal: document.page_goal, top_skip: document.top_skip, max_depth: document.max_depth, insertion_limits: document .insertion_classes .iter() .map(|class| InsertionLimit { class: class.number, height: document.insertion_class_limit(class.number), }) .collect(), insertion_skips: document .insertion_classes .iter() .map(|class| { ( class.number, class.skip.unwrap_or(document.insertion_skip).max(0), ) }) .collect(), text_float_sep: document.text_float_sep.max(0), float_sep: document.float_sep.max(0), bottom_fraction_percent: document.bottom_fraction_percent, top_number: usize::from(document.top_number), bottom_number: usize::from(document.bottom_number), total_number: usize::from(document.total_number), float_page_fraction_percent: document.float_page_fraction_percent, ragged_bottom: document.ragged_bottom, } } /// Distribute the page's glue-setting amount over its vertical glue. fn set_page_glue(items: &mut [VerticalItem], fragment: &PageFragment) { if fragment.set == 0 { return; } // `\vfil` and higher orders absorb the whole setting themselves; // ordinary glue only shares when no fill order is present. let order = if fragment.set > 0 { fragment.stretch_order } else { 0 }; let mut remaining = fragment.set; let mut total = if remaining > 0 { fragment.stretch } else { fragment.shrink }; for item in items.iter_mut() { let VerticalItem::StretchGlue(glue) = item else { continue; }; if glue.order != order { continue; } let share = if remaining > 0 { glue.stretch.max(0) } else { glue.shrink.max(0) }; if share <= 0 || total <= 0 { continue; } let delta = remaining * share / total; glue.width += delta; remaining -= delta; total -= share; } } /// Materialize page fragments without insertion hold-over. /// Build pages one at a time so an output routine that assigns `\vsize` /// changes the goal of the pages it has not seen yet. fn layout_paged_variable_goal( document: &Document, nodes: &[VerticalNode], owners: &[usize], node_items: &[VerticalItem], program: &output::OutputProgram, ) -> Option { let mut builder = Self::paged_builder(document); let mut goal = document.page_goal.max(1); let mut start = 0usize; let mut pages = Vec::new(); let mut pageno = 1_i64; let mut deadcycles = 0_i64; // Output registers are global in TeX; keep assignments between pages. let mut insertion_counts = [1000_i64; 256]; let mut insertion_dimens = [0_i64; 256]; let mut insertion_skips = [0_i64; 256]; for class in &document.insertion_classes { let slot = class.number as usize; insertion_counts[slot] = i64::from(class.multiplier); insertion_dimens[slot] = class.max_height.unwrap_or(0); insertion_skips[slot] = class.skip.unwrap_or(document.insertion_skip); } while start < nodes.len() { builder.set_page_goal(goal); let fragment = builder.build_from(nodes, start).into_iter().next()?; let mut items = Vec::new(); let mut marks = Vec::new(); let mut sources = Vec::new(); for index in fragment.start..fragment.end { let item = &node_items[index]; let unit = &document.units[owners[index]]; if sources.last().map(|(id, _)| *id) != Some(unit.id) { sources.push((unit.id, source_hash(&unit.source))); } match item { VerticalItem::Mark(mark) => marks.push(mark.clone()), other => items.push(other.clone()), } } Self::set_page_glue(&mut items, &fragment); let mut page = Page::empty(); page.items = items; page.marks = marks; page.sources = sources; page.seal_in_place(); let page_total: i64 = page.items.iter().map(item_height).sum(); let mut context = output::OutputContext { page_goal: goal, page_total, page_depth: fragment.depth, page_stretch: fragment.stretch, page_fil_stretch: fragment.stretches[1], page_fill_stretch: fragment.stretches[2], page_filll_stretch: fragment.stretches[3], page_shrink: fragment.shrink, vbadness: fragment.badness, hsize: document.text_width, vsize: goal, top_skip: document.top_skip, max_depth: document.max_depth, output_penalty: fragment.penalty, max_deadcycles: document.max_deadcycles, insertion_counts, insertion_dimens, insertion_skips, output_marks: Vec::new(), prev_graf: page_prev_graf(&page), insert_penalties: 0, pageno, deadcycles, }; let forced = deadcycles >= document.max_deadcycles.max(0); if forced { context.deadcycles = 0; } let shipped = if forced { 1 } else { program.shipout_count(&mut context).ok()? }; insertion_counts = context.insertion_counts; insertion_dimens = context.insertion_dimens; insertion_skips = context.insertion_skips; pageno = context.pageno.wrapping_add(1); deadcycles = context.deadcycles; if shipped > 0 { pages.push(page); deadcycles = 0; } else { deadcycles += 1; } if context.vsize != goal { goal = context.vsize.max(1); } start = fragment.end.max(start + 1); } let count = pages.len(); Some(Self { layout: Layout { pages, checkpoints: Vec::new(), recomputed_pages: 0, changed_pages: (0..count).collect(), paged_page_nodes: Vec::new(), }, }) } fn paged_pages( document: &Document, owners: &[usize], node_items: &[VerticalItem], fragments: &[PageFragment], ) -> Vec { fragments .iter() .map(|fragment| { let mut page = Page::empty(); for index in fragment.start..fragment.end { match &node_items[index] { VerticalItem::Mark(mark) => page.marks.push(mark.clone()), item @ VerticalItem::Float(float) => { if float.placement == FloatPlacement::Here { page.items.push(item.clone()); } else { page.floats.push(float.clone()); } } item => page.items.push(item.clone()), } let unit = &document.units[owners[index]]; if page.sources.last().map(|(id, _)| *id) != Some(unit.id) { page.sources.push((unit.id, source_hash(&unit.source))); } } Self::set_page_glue(&mut page.items, fragment); page.seal_in_place(); page }) .collect() } /// Replay a paged layout from the page that contains `unit_index`. /// /// Earlier pages keep their sealed content. Documents with insertions or /// an interpreted output routine fall back to a full rebuild: held-over /// material can add pages that have no node start to replay from. fn relayout_paged_incremental(&mut self, document: &Document, unit_index: usize) -> bool { let starts = self.layout.paged_page_nodes.clone(); if starts.is_empty() || document.output_routine.is_some() { return false; } let Some((nodes, owners, node_items)) = document_nodes(document) else { return false; }; if nodes .iter() .any(|node| matches!(node, VerticalNode::BottomFloat { .. })) { // A bottom float that did not fit is carried on the fragment, and a // suffix rebuild starting from a page boundary cannot recover that // queue. Rebuild the whole paged document instead of misplacing it. return false; } let Some(mut first_node) = owners.iter().position(|owner| *owner >= unit_index) else { return false; }; // The parser owns the synthetic par-skip glue by the paragraph that // follows it, so that glue sits at the end of the previous page. Start // replaying at the unit's first real item instead. while first_node < nodes.len() && owners[first_node] == unit_index && matches!( node_items[first_node], VerticalItem::Glue(_) | VerticalItem::StretchGlue(_) ) && !matches!( document.units[unit_index].items.first(), Some(VerticalItem::Glue(_)) ) { first_node += 1; } let page_index = starts .iter() .rposition(|start| *start <= first_node) .unwrap_or(0); let start_node = starts[page_index]; if nodes[..start_node] .iter() .any(|node| matches!(node, VerticalNode::Insertion { .. })) { // Insertion material raised before the replay start may still be // held over; without its state a suffix rebuild would drop it. return false; } let fragments = Self::paged_builder(document).build_from(&nodes, start_node); let rebuilt = Self::paged_pages(document, &owners, &node_items, &fragments); let previous = std::mem::take(&mut self.layout.pages); let prefix = page_index.min(previous.len()); let mut pages: Vec = previous[..prefix].to_vec(); pages.extend(rebuilt); let changed_pages = (prefix..pages.len()) .filter(|index| { previous .get(*index) .is_none_or(|old| old.hash != pages[*index].hash) }) .collect(); let recomputed_pages = pages.len() - prefix; let mut paged_page_nodes: Vec = starts[..page_index.min(starts.len())].to_vec(); paged_page_nodes.extend(fragments.iter().map(|fragment| fragment.start)); self.layout = Layout { pages, checkpoints: Vec::new(), recomputed_pages, changed_pages, paged_page_nodes, }; true } 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); let replacement = Unit::paragraph_with_style_and_face(unit_id, source, style, font); self.replace_unit_and_replay(next, unit_index, replacement); } /// Replace a paragraph that carries inline styled runs, then replay the /// pages from its checkpoint. /// /// [`Self::edit`] cannot preserve runs: a plain source string has already /// lost where each face begins and ends. pub fn edit_runs( &mut self, document: &Document, unit_id: UnitId, source: impl Into, runs: Vec<(ParagraphFont, String)>, ) { 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 Some(style) = next.units[unit_index].paragraph_style.clone() else { next.units[unit_index].source = source.into(); return; }; let replacement = Unit::paragraph_with_style_and_runs(unit_id, source, style, runs); self.replace_unit_and_replay(next, unit_index, replacement); } fn replace_unit_and_replay(&mut self, mut next: Document, unit_index: usize, mut unit: Unit) { unit.space_before = next.units[unit_index].space_before; unit.space_stretch = next.units[unit_index].space_stretch; unit.space_shrink = next.units[unit_index].space_shrink; next.units[unit_index] = unit; if self.layout.checkpoints.is_empty() { if !self.relayout_paged_incremental(&next, unit_index) { 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() { if !self.relayout_paged_incremental(document, start_index) { 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::StretchGlue(glue) => glue.width.max(0), 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(); // A paragraph is rebuilt line by line, so it may fill the remaining // space of the checkpoint page instead of being pushed to a new one. let splits = next.page_breaks.binary_search(&start_index).is_ok() || matches!( next.units[start_index].items.first(), Some(VerticalItem::Paragraph(_)) ); if !splits && 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) { if next.page_breaks.binary_search(&index).is_ok() && !current.items.is_empty() { pages.push(std::mem::replace(&mut current, Page::empty())); used = next.top_skip; insertion_height = 0; } 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(), }); if unit.space_before > 0 && !current.items.is_empty() { let lead = unit.space_before; let bottom = bottom_float_area(¤t, next.text_float_sep); if used + lead > next.page_goal - insertion_height - bottom { pages.push(std::mem::replace(&mut current, Page::empty())); used = next.top_skip; insertion_height = 0; } else { used += lead; current.items.push(VerticalItem::Glue(lead)); } } 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 bottom = bottom_float_area(¤t, next.text_float_sep); place_paragraph_flow( &mut pages, &mut current, &mut used, &mut insertion_height, paragraph, next.page_goal, next.top_skip, next.par_skip.max(0), next.par_skip_stretch.max(0), next.par_skip_shrink.max(0), bottom, ); } 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::StretchGlue(glue) => { if !current.items.is_empty() { used += glue.width.max(0); 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) => { place_insertion( next, &mut pages, &mut current, &mut used, &mut insertion_height, insertion, ); } 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, paged_page_nodes: Vec::new(), }; } } #[cfg(test)] mod tests { use super::*; #[test] fn documents_default_to_letter_paper() { let document = Document::new(100, Vec::new()); assert_eq!(document.paper_width, 612 * 65_536); assert_eq!(document.paper_height, 792 * 65_536); } 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 math_symbol_paints_with_the_cmsy_face() { use crate::render::{DisplayItem, FontFace}; let document = Document::new( 1_000_000, vec![Unit::math( 1, crate::math::parse_math("\\times"), &Cmr10Metrics::Math, )], ); let engine = Engine::layout(&document); let list = engine.pages()[0].display_list(); let symbols: Vec<(String, FontFace)> = list .items .iter() .filter_map(|item| match item { DisplayItem::Text { text, font, .. } if text == "\u{00D7}" => { Some((text.clone(), *font)) } _ => None, }) .collect(); assert_eq!(symbols, vec![("\u{00D7}".to_owned(), FontFace::MathSymbol)]); } #[test] fn math_alphabet_paints_with_its_type1_face() { use crate::render::{DisplayItem, FontFace}; let document = Document::new( 1_000_000, vec![Unit::math( 1, crate::math::parse_math("\\mathbf{x}"), &Cmr10Metrics::Math, )], ); let engine = Engine::layout(&document); let list = engine.pages()[0].display_list(); let faces: Vec = list .items .iter() .filter_map(|item| match item { DisplayItem::Text { text, font, .. } if text == "x" => Some(*font), _ => None, }) .collect(); assert_eq!(faces, vec![FontFace::Bold]); } #[test] fn mathcal_paints_with_the_cmsy_face() { use crate::render::{DisplayItem, FontFace}; let document = Document::new( 1_000_000, vec![Unit::math( 1, crate::math::parse_math("\\mathcal{A}"), &Cmr10Metrics::Math, )], ); let engine = Engine::layout(&document); let list = engine.pages()[0].display_list(); assert!(list.items.iter().any(|item| matches!( item, DisplayItem::Text { text, font: FontFace::MathSymbol, .. } if text == "A" ))); } #[test] fn mathbb_paints_with_the_msbm_face() { use crate::render::{DisplayItem, FontFace}; let document = Document::new( 1_000_000, vec![Unit::math( 1, crate::math::parse_math("\\mathbb{A}"), &Cmr10Metrics::Math, )], ); let engine = Engine::layout(&document); let list = engine.pages()[0].display_list(); assert!(list.items.iter().any(|item| matches!( item, DisplayItem::Text { text, font: FontFace::MathBlackboard, .. } if text == "A" ))); } #[test] fn mathfrak_paints_with_the_eufm_face() { use crate::render::{DisplayItem, FontFace}; let document = Document::new( 1_000_000, vec![Unit::math( 1, crate::math::parse_math("\\mathfrak{A}"), &Cmr10Metrics::Math, )], ); let engine = Engine::layout(&document); let list = engine.pages()[0].display_list(); assert!(list.items.iter().any(|item| matches!( item, DisplayItem::Text { text, font: FontFace::MathFraktur, .. } if text == "A" ))); } #[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, paragraph_runs: None, space_before: 0, space_stretch: 0, space_shrink: 0, 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_retarget_pages_with_insertions() { const PT: i64 = 65_536; let build = |routine: Option<&str>| { let insertion = Unit::insertion( 2, 0, 50 * PT, vec![VerticalItem::Rule { width: 100 * PT, height: 50 * PT, }], ); let mut document = Document::new( 250 * PT, vec![ Unit::rule(1, 100 * PT, 100 * PT), insertion, Unit::rule(3, 100 * PT, 100 * PT), Unit::vskip(6, 0), Unit::rule(4, 100 * PT, 100 * PT), Unit::vskip(7, 0), Unit::rule(5, 100 * PT, 100 * PT), ], ); document.insertion_classes = vec![InsertionClass { number: 0, fraction_percent: 100, max_height: Some(250 * PT), multiplier: 1000, skip: None, }]; document.output_routine = routine.map(str::to_owned); Engine::layout_paged(&document).expect("paged layout") }; let base = build(None); assert_eq!(base.layout.pages.len(), 2); assert_eq!(base.layout.pages[0].insertions.len(), 1); // \vsize assigned by the routine retargets the pages it has not seen // yet, even though the document raises insertion material. let retargeted = build(Some(r#"\ifnum\pageno=1\vsize=150\fi\shipout\box255"#)); assert_eq!(retargeted.layout.pages.len(), 3); assert_eq!(retargeted.layout.pages[0].insertions.len(), 1); } #[test] fn output_routine_can_assign_insertion_skip_for_later_pages() { const PT: i64 = 65_536; let build = |routine: Option<&str>| { let mut units = Vec::new(); for step in 0..4_u64 { units.push(Unit::rule(step * 3, 100 * PT, 100 * PT)); units.push(Unit::insertion( step * 3 + 1, 0, 50 * PT, vec![VerticalItem::Rule { width: 100 * PT, height: 50 * PT, }], )); units.push(Unit::vskip(step * 3 + 2, 0)); } let mut document = Document::new(300 * PT, units); document.insertion_classes = vec![InsertionClass { number: 0, fraction_percent: 100, max_height: Some(300 * PT), multiplier: 1000, skip: None, }]; document.output_routine = routine.map(str::to_owned); Engine::layout_paged(&document).expect("paged layout") }; let base = build(None); assert_eq!(base.layout.pages.len(), 2); // The routine assigns \skip0 after the first page; the remaining // fragments are rebuilt with the larger reservation, so the second // pair of units no longer fits on the second page. let retargeted = build(Some(r#"\ifnum\pageno=1\skip0=40pt\fi\shipout\box255"#)); assert_eq!(retargeted.layout.pages.len(), 3); } #[test] fn output_routine_can_change_vsize_for_later_pages() { let mut units = Vec::new(); for n in 0..7 { units.push(Unit::rule(n * 2, 300, 300)); if n < 6 { units.push(Unit::penalty(n * 2 + 1, 0)); } } let mut document = Document::new(1000, units); document.top_skip = 0; document.output_routine = Some(r"\ifnum\pageno=1\vsize=600\fi\shipout\box255".to_owned()); let engine = Engine::layout_paged(&document).expect("paged"); let counts = engine .pages() .iter() .map(|page| { page.items .iter() .filter(|item| matches!(item, VerticalItem::Rule { .. })) .count() }) .collect::>(); assert_eq!(counts, vec![3, 2, 2], "pages: {counts:?}"); } #[test] fn output_marks_reach_the_following_page() { let mut units = Vec::new(); for step in 0..3_u64 { units.push(Unit::rule(step * 2, 300, 600)); if step < 2 { units.push(Unit::vskip(step * 2 + 1, 0)); } } let mut document = Document::new(1000, units); document.top_skip = 0; document.output_routine = Some(r"\mark{carried}\shipout\box255".to_owned()); let engine = Engine::layout_paged(&document).expect("paged"); assert_eq!(engine.layout.pages.len(), 3); assert!(engine.layout.pages[0].marks.is_empty()); assert_eq!(engine.layout.pages[1].marks[0].text, "carried"); assert_eq!(engine.layout.pages[1].marks[0].class, 0); } #[test] fn output_marks_carry_their_class() { let mut units = Vec::new(); for step in 0..3_u64 { units.push(Unit::rule(step * 2, 300, 600)); if step < 2 { units.push(Unit::vskip(step * 2 + 1, 0)); } } let mut document = Document::new(1000, units); document.top_skip = 0; document.output_routine = Some(r"\marks3{carried}\shipout\box255".to_owned()); let engine = Engine::layout_paged(&document).expect("paged"); assert_eq!(engine.layout.pages.len(), 3); assert_eq!(engine.layout.pages[1].marks[0].class, 3); assert_eq!(engine.layout.pages[1].marks[0].text, "carried"); } #[test] fn output_routine_can_advance_vsize_for_later_pages() { let mut units = Vec::new(); for n in 0..7 { units.push(Unit::rule(n * 2, 300, 300)); if n < 6 { units.push(Unit::penalty(n * 2 + 1, 0)); } } let mut document = Document::new(1000, units); document.top_skip = 0; document.output_routine = Some(r"\advance\vsize by -300 \shipout\box255".to_owned()); let engine = Engine::layout_paged(&document).expect("paged"); let counts = engine .pages() .iter() .map(|page| { page.items .iter() .filter(|item| matches!(item, VerticalItem::Rule { .. })) .count() }) .collect::>(); assert_eq!(counts, vec![3, 2, 1, 1], "pages: {counts:?}"); } #[test] fn output_routine_sees_page_goal_after_insertion_reservation() { let scale = 65_536; let mut document = Document::new( 200 * scale, vec![ Unit::rule(1, 0, 40 * scale), Unit::insertion( 2, 0, 40 * scale, vec![VerticalItem::Rule { width: 0, height: 40 * scale, }], ), Unit::rule(3, 0, 40 * scale), ], ); document.insertion_classes = vec![InsertionClass { number: 0, fraction_percent: 100, max_height: None, skip: None, multiplier: 1000, }]; document.output_routine = Some(r"\ifdim\pagegoal<195pt\ifdim\pagetotal>79pt\shipout\box255\fi\fi".to_owned()); let engine = Engine::layout_paged(&document).expect("paged"); assert_eq!(engine.pages().len(), 1); document.units.remove(1); document.output_routine = Some(r"\ifdim\pagegoal<195pt\shipout\box255\fi".to_owned()); let engine = Engine::layout_paged(&document).expect("paged"); assert!(engine.pages().is_empty()); } #[test] fn output_routine_can_rewrite_the_page_number() { let mut document = Document::new( 100, vec![ Unit::rule(1, 10, 10), Unit::penalty(2, -10_000), Unit::rule(3, 10, 10), Unit::penalty(4, -10_000), Unit::rule(5, 10, 10), ], ); document.output_routine = Some(r"\ifnum\pageno=1\pageno=10\fi\ifnum\pageno=11\shipout\box255\fi".to_owned()); let engine = Engine::layout_paged(&document).expect("paged"); assert_eq!(engine.pages().len(), 1); } #[test] fn output_routine_sees_page_break_badness() { // The first page overfills the 50pt goal, so its break is maximally // bad; the second page fits exactly. Only the overfull page ships. let mut document = Document::new( 50, vec![ Unit::rule(1, 0, 60), Unit::penalty(2, 0), Unit::rule(3, 0, 50), ], ); document.output_routine = Some(r"\ifnum\vbadness=10000\shipout\box255\fi".to_owned()); let engine = Engine::layout_paged(&document).expect("paged"); assert_eq!(engine.pages().len(), 1); } #[test] fn output_routine_sees_insertion_penalties() { // The class limit fits one 20pt item, so the second is held over and // reported through \insertpenalties. let mut document = Document::new( 200, vec![ Unit::rule(1, 0, 20), Unit::insertion( 2, 0, 40, vec![ VerticalItem::Rule { width: 0, height: 20, }, VerticalItem::Rule { width: 0, height: 20, }, ], ), ], ); document.insertion_classes = vec![InsertionClass { number: 0, fraction_percent: 100, max_height: Some(20), skip: None, multiplier: 1000, }]; document.output_routine = Some(r"\ifnum\insertpenalties=1\shipout\box255\fi".to_owned()); let engine = Engine::layout_paged(&document).expect("paged"); assert_eq!(engine.pages().len(), 1); } #[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, paragraph_runs: None, space_before: 0, space_stretch: 0, space_shrink: 0, 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, paragraph_runs: None, space_before: 0, space_stretch: 0, space_shrink: 0, 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, paragraph_runs: None, space_before: 0, space_stretch: 0, space_shrink: 0, 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_carry_to_following_pages() { let document = Document::new( 100, vec![ Unit::mark(0, 1, "first"), Unit::mark(1, 1, "second"), Unit::rule(2, 10, 80), Unit::rule(3, 10, 80), ], ); let engine = Engine::layout(&document); assert_eq!(engine.pages().len(), 2); assert!(engine.top_mark(0, 1).is_none()); assert_eq!( engine.first_mark(0, 1).map(|mark| mark.text.as_str()), Some("first") ); assert_eq!( engine.bot_mark(0, 1).map(|mark| mark.text.as_str()), Some("second") ); assert_eq!( engine.top_mark(1, 1).map(|mark| mark.text.as_str()), Some("second") ); assert_eq!( engine.first_mark(1, 1).map(|mark| mark.text.as_str()), Some("second") ); assert_eq!( engine.bot_mark(1, 1).map(|mark| mark.text.as_str()), Some("second") ); } #[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, paragraph_runs: None, space_before: 0, space_stretch: 0, space_shrink: 0, 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, paragraph_runs: None, space_before: 0, space_stretch: 0, space_shrink: 0, 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, paragraph_runs: None, space_before: 0, space_stretch: 0, space_shrink: 0, 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 output_routine_dimen_limits_later_insertions() { let items = || { (0..8) .map(|_| VerticalItem::Rule { width: 65_536, height: 10, }) .collect::>() }; let mut document = Document::new( 100, vec![ Unit::insertion(1, 1, 80, items()), Unit::vskip(2, 65_536), Unit::insertion(3, 1, 80, items()), ], ); document.insertion_classes = vec![InsertionClass { number: 1, fraction_percent: 100, max_height: None, skip: None, multiplier: 1000, }]; let without = Engine::layout_paged(&document).expect("paged layout"); assert_eq!( without.layout.pages.len(), 2, "both insertions should fit before any assignment" ); assert_eq!(without.layout.pages[0].insertions[0].height, 80); document.output_routine = Some(r"\ifnum\pageno=1 \dimen1=30 \fi \shipout\box255".to_string()); let with = Engine::layout_paged(&document).expect("paged layout"); assert_eq!(with.layout.pages.len(), 3); assert_eq!(with.layout.pages[0].insertions[0].height, 80); assert_eq!(with.layout.pages[1].insertions[0].height, 30); assert_eq!(with.layout.pages[2].insertions[0].height, 50); } #[test] fn output_routine_count_changes_later_insertion_reservations() { let items = || { (0..4) .map(|_| VerticalItem::Rule { width: 65_536, height: 10, }) .collect::>() }; let mut document = Document::new( 100, vec![ Unit::insertion(1, 1, 40, items()), Unit::vskip(2, 65_536), Unit::insertion(3, 1, 40, items()), ], ); document.insertion_classes = vec![InsertionClass { number: 1, fraction_percent: 100, max_height: None, skip: None, multiplier: 1000, }]; let without = Engine::layout_paged(&document).expect("paged layout"); assert_eq!(without.layout.pages[0].insertions[0].height, 40); assert_eq!(without.layout.pages[1].insertions[0].height, 40); document.output_routine = Some(r"\ifnum\pageno=1 \count1=2000 \fi \shipout\box255".to_string()); let with = Engine::layout_paged(&document).expect("paged layout"); assert_eq!(with.layout.pages[1].insertions[0].height, 80); } #[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, multiplier: 1000, }]; 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, multiplier: 1000, }, InsertionClass { number: 2, fraction_percent: 60, max_height: None, skip: None, multiplier: 1000, }, ]; 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, multiplier: 1000, }]; 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 insertion_splits_at_the_page_break_and_holds_over_the_tail() { let rule = |height| VerticalItem::Rule { width: 65_536, height, }; let mut document = Document::new( 100, vec![ Unit::vertical(1, vec![rule(40)]), Unit::insertion(2, 1, 80, vec![rule(40), rule(40)]), Unit::vertical(3, vec![rule(20)]), ], ); document.insertion_skip = 0; let layout = Engine::layout(&document); assert_eq!(layout.pages().len(), 2); assert_eq!(layout.pages()[0].items.len(), 1); assert_eq!(layout.pages()[0].insertions.len(), 1); assert_eq!(layout.pages()[0].insertions[0].height, 40); assert_eq!(layout.pages()[1].insertions.len(), 1); assert_eq!(layout.pages()[1].insertions[0].height, 40); // The held-over tail sits above the text that follows the insertion. assert_eq!(layout.pages()[1].items.len(), 1); } #[test] fn incremental_layout_holds_over_the_insertion_tail() { let rule = |height| VerticalItem::Rule { width: 65_536, height, }; let mut document = Document::new( 100, vec![ Unit::paragraph(1, "body"), Unit::insertion(2, 1, 80, vec![rule(40), rule(40)]), ], ); document.insertion_skip = 0; document.insertion_classes = vec![InsertionClass { number: 1, fraction_percent: 60, max_height: None, skip: None, multiplier: 1000, }]; let mut engine = Engine::layout(&document); assert_eq!(engine.pages().len(), 2); assert_eq!(engine.pages()[0].insertions[0].height, 40); assert_eq!(engine.pages()[1].insertions[0].height, 40); engine.edit(&document, 1, "changed body"); assert_eq!(engine.pages().len(), 2); assert_eq!(engine.pages()[0].insertions[0].height, 40); assert_eq!(engine.pages()[1].insertions[0].height, 40); } #[test] fn incremental_layout_respects_insertion_count() { let rule = VerticalItem::Rule { width: 65_536, height: 200, }; let mut document = Document::new( 500, 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: 100, max_height: None, skip: None, multiplier: 2000, }]; let mut engine = Engine::layout(&document); assert_eq!(engine.pages().len(), 2, "2x reserve splits the insertions"); engine.edit(&document, 1, "changed body"); assert_eq!(engine.pages().len(), 2); assert_eq!(engine.pages()[1].insertions.len(), 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, multiplier: 1000, }]; 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), multiplier: 1000, }]; 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), multiplier: 1000, }]; 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 held_over_insertions_start_with_split_top_skip() { let scale = 65_536; let mut document = Document::new( 200 * scale, vec![Unit::insertion( 1, 0, 120 * scale, vec![ VerticalItem::Rule { width: 0, height: 60 * scale, }, VerticalItem::Rule { width: 0, height: 60 * scale, }, ], )], ); document.split_top_skip = 20 * scale; document.insertion_classes = vec![InsertionClass { number: 0, fraction_percent: 50, max_height: None, skip: None, multiplier: 1000, }]; let engine = Engine::layout_paged(&document).expect("paged"); assert_eq!(engine.pages().len(), 2); let second = &engine.pages()[1].insertions[0]; assert_eq!(second.items.first(), Some(&VerticalItem::Glue(20 * scale))); assert_eq!(second.height, 80 * scale); } #[test] fn split_max_depth_clamps_the_first_held_item() { let scale = 65_536; let mut document = Document::new(1000 * scale, vec![]); document.split_top_skip = 0; document.split_max_depth = 3 * scale; let material = held_insertion_material( &document, 1000 * scale, vec![VerticalItem::Math { atom: crate::math::MathAtom::Symbol('x'), width: scale, height: 20 * scale, depth: 10 * scale, }], ); match &material[0] { VerticalItem::Math { height, depth, .. } => { assert_eq!(*depth, 3 * scale); assert_eq!(*height, 27 * scale); } other => panic!("unexpected material {other:?}"), } } #[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, multiplier: 1000, }]; 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, multiplier: 1000, }]; 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, paragraph_runs: None, space_before: 0, space_stretch: 0, space_shrink: 0, 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, paragraph_runs: None, space_before: 0, space_stretch: 0, space_shrink: 0, 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, paragraph_runs: None, space_before: 0, space_stretch: 0, space_shrink: 0, 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 sans_bold_paragraph_paints_with_the_sans_bold_face() { let unit = Unit::paragraph_with_face(1, "sans bold", ParagraphFont::SansBold); 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 { font: crate::render::FontFace::SansBold, .. } ))); let svg = list.to_svg(); assert!(svg.contains("font-family=\"sans-serif\"")); assert!(svg.contains("font-weight=\"bold\"")); } #[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 big_delimiters_paint_at_their_selected_size() { let atom = crate::math::parse_math("\\big("); 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 size = list .items .iter() .find_map(|item| match item { DisplayItem::Text { text, size, .. } if text == "(" => Some(*size), _ => None, }) .expect("big paren should be painted"); assert!(size > 655_360, "expected a larger glyph, got {size}"); } #[test] fn aligned_displays_share_their_alignment_points() { let rows = vec![ crate::math::AlignedRow::new( vec![ crate::math::MathAtom::Text("a".to_string()), crate::math::MathAtom::Text("= b".to_string()), ], Some("(1)".to_string()), ), crate::math::AlignedRow::new( vec![ crate::math::MathAtom::Text("cc".to_string()), crate::math::MathAtom::Text("= d".to_string()), ], Some("(2)".to_string()), ), ]; let atom = crate::math::MathAtom::Aligned { rows, centered: false, }; 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 mut equals = Vec::new(); let mut parens = Vec::new(); for item in &list.items { if let DisplayItem::Text { text, x, y, .. } = item { if text == "=" { equals.push((*x, *y)); } else if text == "(" { parens.push(*x); } } } assert_eq!(equals.len(), 2); assert_eq!(equals[0].0, equals[1].0, "columns must share an x"); assert!(equals[1].1 > equals[0].1, "rows must stack downward"); assert_eq!(parens.len(), 2); assert_eq!(parens[0], parens[1], "tags must share a right edge"); } #[test] fn middle_delimiters_paint_larger_than_the_base_glyph() { let atom = crate::math::parse_math( "\\left( \\frac{\\frac{a}{b}}{\\frac{c}{d}} \\middle\\{ c \\right)", ); 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 size = list .items .iter() .find_map(|item| match item { DisplayItem::Text { text, size, .. } if text == "{" => Some(*size), _ => None, }) .expect("middle brace should be painted"); assert!(size > 655_360, "expected a larger glyph, got {size}"); } #[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 fractions_paint_a_rule_without_parentheses() { let atom = crate::math::parse_math("\\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(); assert!( !list.items.iter().any(|item| matches!( item, DisplayItem::Text { text, .. } if text == "(" || text == ")" )), "fractions must not paint parentheses: {:?}", list.items ); assert!( list.items .iter() .any(|item| matches!(item, DisplayItem::Rule { .. })) ); } #[test] fn atop_paints_without_a_fraction_rule() { let atom = crate::math::parse_math("a \\atop 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(); assert!( !list .items .iter() .any(|item| matches!(item, DisplayItem::Rule { .. })) ); } #[test] fn big_operators_paint_with_the_cmex_face() { let atom = crate::math::parse_math("\\sum_{i=1}^{n}"); 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 item = list .items .iter() .find(|item| { matches!( item, DisplayItem::Text { font: crate::render::FontFace::MathExtension, .. } ) }) .expect("sum should use the CMEX face"); if let DisplayItem::Text { text, .. } = item { assert_eq!(text, "\u{2211}"); } assert!(list.to_svg().contains('\u{2211}')); } #[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("> = (0..10).map(|_| Vec::new()).collect(); let paragraph = Paragraph { lines, height: 100, width: 50, depth: 0, font: ParagraphFont::Roman, left_skip: 0, line_indents: vec![0; 10], line_baselines: (0..10).map(|line| 8 + line * 10).collect(), centered: false, right_aligned: false, }; let mut document = Document::new( 45, vec![Unit::vertical(1, vec![VerticalItem::Paragraph(paragraph)])], ); document.top_skip = 5; let engine = Engine::layout(&document); let counts: Vec = engine .pages() .iter() .map(|page| { page.items .iter() .filter_map(|item| match item { VerticalItem::Paragraph(paragraph) => Some(paragraph.lines.len()), _ => None, }) .sum() }) .collect(); assert_eq!(counts, vec![4, 4, 2]); // A split paragraph does not collect a parskip: continuation pages // start with the next line fragment, not a glue item. for page in engine.pages().iter().skip(1) { assert!(matches!( page.items.first(), Some(VerticalItem::Paragraph(_)) )); } let baselines: Vec = engine .pages() .iter() .flat_map(|page| { page.items.iter().filter_map(|item| match item { VerticalItem::Paragraph(paragraph) => paragraph.line_baselines.first().copied(), _ => None, }) }) .collect(); assert_eq!(baselines, vec![8, 8, 8]); } #[test] fn floatsep_separates_stacked_top_floats() { let mut document = Document::new( 1000, vec![ Unit::float(1, FloatPlacement::Top, 100, 100), Unit::float(2, FloatPlacement::Top, 100, 100), Unit::paragraph(3, "body"), ], ); document.top_skip = 0; document.float_sep = 50; let mut engine = Engine::layout(&document); let page = &engine.pages()[0]; assert_eq!(page.floats.len(), 2); assert_eq!(page.floats[0].gap_before, 0); assert_eq!(page.floats[1].gap_before, 50); let ys: Vec = 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 paged_layout_splits_a_tall_halign_across_pages() { let mut rows = Vec::new(); for n in 0..30_u64 { rows.push(HalignRow { cells: vec![ HalignCell { text: format!("r{n}"), span: 1, alignment: CellAlignment::Left, }, HalignCell { text: "value".to_owned(), span: 1, alignment: CellAlignment::Left, }, ], rule: false, }); } let document = Document::new(300 * 65_536, vec![Unit::halign(0, rows, 2, 0)]); let engine = Engine::layout_paged(&document).expect("paged"); assert!(engine.pages().len() > 1, "pages: {}", engine.pages().len()); let mut rows_seen = 0; let mut widths = Vec::new(); for page in engine.pages() { for item in &page.items { if let VerticalItem::Halign(halign) = item { rows_seen += halign.rows.len(); widths.push(halign.column_widths.clone()); } } } assert_eq!(rows_seen, 30); assert!(!widths.is_empty()); assert!(widths.windows(2).all(|pair| pair[0] == pair[1])); } #[test] fn paragraph_columns_wrap_cell_text() { let unit = Unit::halign_from_source_with_template( 1, "p{25mm}l", "alpha beta gamma delta & short \\\\ second row & right\n", 0, ); let VerticalItem::Halign(halign) = &unit.items[0] else { panic!("expected halign"); }; let wrap = halign.column_wrap[0].expect("p column"); let expected = (25.0_f64 * 72.27 / 25.4 * 65_536.0).round() as i64; assert!( (wrap - expected).abs() <= 2, "wrap {wrap} expected {expected}" ); assert_eq!(halign.column_widths[0], wrap); let lines = halign.cell_lines(0, 0); assert!(lines.len() >= 3, "lines: {lines:?}"); assert!(lines.iter().all(|line| crate::text_width(line) <= wrap)); assert_eq!( halign.row_height(0), halign.line_height * lines.len() as i64 ); assert_eq!( halign.cell_lines(1, 0), vec!["second".to_owned(), "row".to_owned()] ); } #[test] fn paragraph_columns_paint_wrapped_lines_and_split_rows() { let unit = Unit::halign_from_source_with_template( 1, "p{20mm}l", "alpha beta gamma delta & x \\\\ second row text & y\n", 0, ); let VerticalItem::Halign(halign) = &unit.items[0] else { panic!("expected halign"); }; let lines = halign.cell_lines(0, 0); assert!(lines.len() >= 4, "lines: {lines:?}"); let list = halign.display_list(); let texts: Vec<&str> = list .items .iter() .filter_map(|item| match item { DisplayItem::Text { text, .. } => Some(text.as_str()), _ => None, }) .collect(); assert!(texts.contains(&"alpha"), "texts: {texts:?}"); assert!(texts.contains(&"beta"), "texts: {texts:?}"); let alpha_y = list .items .iter() .find_map(|item| match item { DisplayItem::Text { text, y, .. } if text == "alpha" => Some(*y), _ => None, }) .unwrap(); let beta_y = list .items .iter() .find_map(|item| match item { DisplayItem::Text { text, y, .. } if text == "beta" => Some(*y), _ => None, }) .unwrap(); assert!(beta_y > alpha_y, "alpha {alpha_y} beta {beta_y}"); let chunks = halign.split_for_height(halign.line_height * 2); assert!(chunks.len() >= 2); assert_eq!( chunks.iter().map(|chunk| chunk.rows.len()).sum::(), 2 ); assert_eq!(chunks[0].column_widths, chunks[1].column_widths); } #[test] fn explicit_tabskips_set_the_column_gaps() { let unit = Unit::halign_from_source_with_template_and_tabskips( 1, "ll", "a & b \\\\ cc & d\n", 0, vec![30 * 65_536], ); let VerticalItem::Halign(halign) = &unit.items[0] else { panic!("expected halign"); }; assert_eq!(halign.column_skips, vec![30 * 65_536]); let first_width = halign.column_widths[0]; assert_eq!( halign.cell_span(0, 1), Some((first_width + 30 * 65_536, halign.column_widths[1])) ); assert_eq!( halign.width, halign.column_widths.iter().sum::() + 30 * 65_536 ); let list = halign.display_list(); let second_x = list .items .iter() .find_map(|item| match item { DisplayItem::Text { text, x, .. } if text == "b" => Some(*x), _ => None, }) .unwrap(); assert_eq!(second_x, first_width + 30 * 65_536); } #[test] fn tabskips_survive_page_splitting() { let mut source = String::new(); for index in 0..20 { source.push_str(&format!( "row{index} & value{index} \\\\ " )); } let unit = Unit::halign_from_source_with_template_and_tabskips( 1, "ll", &source, 0, vec![15 * 65_536], ); let VerticalItem::Halign(halign) = &unit.items[0] else { panic!("expected halign"); }; let chunks = halign.split_for_height(halign.line_height * 3); assert!(chunks.len() >= 2); for chunk in &chunks { assert_eq!(chunk.column_skips, vec![15 * 65_536]); assert_eq!(chunk.column_widths, halign.column_widths); } assert_eq!( chunks.iter().map(|chunk| chunk.rows.len()).sum::(), 20 ); } #[test] fn booktabs_rules_carry_widths_and_partial_spans() { let source = r"\toprule Name & Value \\ \midrule a & 1 \\ \cmidrule(lr){1-1} b & 2 \\ \bottomrule "; let unit = Unit::halign_from_source_with_template(1, "ll", source, 0); let VerticalItem::Halign(halign) = &unit.items[0] else { panic!("expected halign"); }; assert_eq!(halign.rows.len(), 3); assert_eq!(halign.rules.len(), 4); assert_eq!( halign.rules[0], HalignRule { row: 0, start: 0, end: 1, width: 52_429, trim_left: 0, trim_right: 0, } ); assert_eq!(halign.rules[1].row, 1); assert_eq!(halign.rules[1].width, 32_768); assert_eq!(halign.rules[2].row, 2); assert_eq!(halign.rules[2].start, 0); assert_eq!(halign.rules[2].end, 0); assert_eq!(halign.rules[2].trim_left, 4 * 65_536); assert_eq!(halign.rules[2].trim_right, 4 * 65_536); assert_eq!(halign.rules[3].row, 3); assert_eq!(halign.rules[3].width, 52_429); let (x, width) = halign.rule_rect(&halign.rules[2]); assert_eq!(x, 4 * 65_536); assert_eq!(width, halign.column_widths[0] - 8 * 65_536); let list = halign.display_list(); let painted: Vec<(i64, i64, i64)> = list .items .iter() .filter_map(|item| match item { DisplayItem::Rule { x, y, width, .. } => Some((*x, *y, *width)), _ => None, }) .collect(); assert_eq!(painted.len(), 4); assert!( painted .iter() .any(|(_, _, width)| *width < halign.width / 2) ); assert!(painted.iter().any(|(_, y, _)| *y == halign.height)); } #[test] fn booktabs_rules_follow_page_chunks() { let mut source = String::from( r"\toprule ", ); for index in 0..20 { source.push_str(&format!("row{index} & value{index} \\\\\n")); } source.push_str( r"\bottomrule ", ); let unit = Unit::halign_from_source_with_template(1, "ll", &source, 0); let VerticalItem::Halign(halign) = &unit.items[0] else { panic!("expected halign"); }; assert_eq!(halign.rules.len(), 2); let chunks = halign.split_for_height(halign.line_height * 3); assert!(chunks.len() >= 2); assert!( chunks[0] .rules .iter() .any(|rule| rule.row == 0 && rule.width == 52_429) ); let last = chunks.last().unwrap(); assert!( last.rules .iter() .any(|rule| rule.row == last.rows.len() && rule.width == 52_429) ); assert_eq!( chunks.iter().map(|chunk| chunk.rows.len()).sum::(), 20 ); } #[test] fn at_expressions_override_column_gaps() { let unit = Unit::halign_from_source_with_template(1, "l@{}c", "aa & bb \\\\", 20); let VerticalItem::Halign(halign) = &unit.items[0] else { panic!("expected halign"); }; assert_eq!(halign.column_skips, vec![0]); assert_eq!(halign.width, halign.column_widths.iter().sum::()); assert_eq!(halign.column_offset(1), halign.column_widths[0]); let unit = Unit::halign_from_source_with_template(1, r"l@{\hspace{5pt}}c", "aa & bb \\\\", 20); let VerticalItem::Halign(halign) = &unit.items[0] else { panic!("expected halign"); }; assert_eq!(halign.column_skips, vec![5 * 65_536]); assert_eq!( halign.column_offset(1), halign.column_widths[0] + 5 * 65_536 ); } #[test] fn plain_templates_keep_uniform_gaps() { let unit = Unit::halign_from_source_with_template(1, "lc", "aa & bb \\\\", 20); let VerticalItem::Halign(halign) = &unit.items[0] else { panic!("expected halign"); }; assert!(halign.column_skips.is_empty()); assert_eq!( halign.column_offset(1), halign.column_widths[0] + 20 * 65_536 ); } #[test] fn noalign_vertical_glue_spaces_rows() { let source = "a & b \\\\\n\\noalign{\\vskip 6pt}\nc & d \\\\\n"; let unit = Unit::halign_from_source_with_template(1, "ll", source, 0); let VerticalItem::Halign(halign) = &unit.items[0] else { panic!("expected halign"); }; assert_eq!(halign.rows.len(), 2); assert_eq!(halign.row_gaps, vec![6 * 65_536]); assert_eq!( halign.height, halign.row_height(0) + halign.row_height(1) + 6 * 65_536 ); let list = halign.display_list(); let mut a_y = None; let mut c_y = None; for item in &list.items { if let DisplayItem::Text { y, text, .. } = item { if text == "a" { a_y = Some(*y); } if text == "c" { c_y = Some(*y); } } } let (a_y, c_y) = (a_y.unwrap(), c_y.unwrap()); assert_eq!(c_y - a_y, halign.row_height(0) + 6 * 65_536); } #[test] fn noalign_glue_stays_with_its_row_chunk() { let source = "a & b \\\\\n\\noalign{\\vskip 6pt}\nc & d \\\\\n"; let unit = Unit::halign_from_source_with_template(1, "ll", source, 0); let VerticalItem::Halign(halign) = &unit.items[0] else { panic!("expected halign"); }; let chunks = halign.split_for_height(halign.row_height(0) + halign.row_gap(0)); assert_eq!(chunks.len(), 2); assert_eq!(chunks[0].height, halign.row_height(0) + 6 * 65_536); assert_eq!(chunks[0].row_gaps, vec![6 * 65_536]); assert_eq!(chunks[1].rows.len(), 1); assert_eq!(chunks[1].height, halign.row_height(1)); } #[test] fn longtable_heads_repeat_on_continuation_chunks() { let source = "H1 & H2 \\\\\n\\endfirsthead\nH3 & H4 \\\\\n\\endhead\nF1 & F2 \\\\\n\\endfoot\nL1 & L2 \\\\\n\\endlastfoot\nb1 & x \\\\\nb2 & y \\\\\nb3 & z \\\\\nb4 & w \\\\\n"; let unit = Unit::halign_from_source_with_template(1, "ll", source, 0); let VerticalItem::Halign(halign) = &unit.items[0] else { panic!("expected halign"); }; assert_eq!(halign.rows.len(), 8); assert_eq!(halign.first_head_len, 1); assert_eq!(halign.head_len, 1); assert_eq!(halign.foot_len, 2); let texts = |chunk: &Halign| -> Vec { chunk .rows .iter() .flat_map(|row| row.cells.iter().map(|cell| cell.text.clone())) .collect() }; let all = texts(halign); assert_eq!(&all[..4], ["H1", "H2", "H3", "H4"]); assert_eq!(&all[12..16], ["F1", "F2", "L1", "L2"]); let chunks = halign.split_for_height(halign.line_height * 2); assert_eq!(chunks.len(), 4); assert_eq!(chunks[0].rows[0].cells[0].text, "H1"); for chunk in &chunks[1..] { assert_eq!(chunk.rows[0].cells[0].text, "H3"); } let chunk_text: Vec> = chunks.iter().map(texts).collect(); for body in ["b1", "b2", "b3", "b4"] { assert_eq!( chunk_text .iter() .filter(|texts| texts.iter().any(|text| text == body)) .count(), 1 ); } assert_eq!( chunk_text .iter() .filter(|texts| texts.iter().any(|text| text == "H1")) .count(), 1 ); assert_eq!( chunk_text .iter() .filter(|texts| texts.iter().any(|text| text == "H3")) .count(), 3 ); assert!(chunk_text[3].iter().any(|text| text == "L1")); assert!(!chunk_text[0].iter().any(|text| text == "F1")); } #[test] fn display_math_splits_at_operators() { let atom = crate::math::parse_math("a + b + c + d + e + f + g + h + i + j"); let font = Cmr10Metrics::default(); let lines = crate::math::split_math_lines(&atom, &font, 60 * 65_536); assert!(lines.len() > 1, "lines={}", lines.len()); let atoms = |atom: &crate::math::MathAtom| match atom { crate::math::MathAtom::Row(items) => items.len(), _ => 1, }; let total: usize = lines.iter().map(atoms).sum(); assert_eq!(total, atoms(&atom)); for line in &lines { let width = crate::math::layout_math(line, &font).width; let single = match line { crate::math::MathAtom::Row(items) => items.len() <= 1, _ => true, }; assert!(single || width <= 60 * 65_536, "width={width}"); } } #[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, paragraph_runs: None, space_before: 0, space_stretch: 0, space_shrink: 0, 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_glue_setting_fills_or_ragged_bottoms() { let units = vec![ Unit::rule(1, 100, 40), Unit::vertical( 2, vec![VerticalItem::StretchGlue(VerticalGlue::new(0, 10, 0))], ), Unit::rule(3, 100, 40), ]; let mut document = Document::new(120, units); let ragged = Engine::layout_paged(&document).expect("paged"); let rule_ys = |engine: &Engine| { engine.pages()[0] .display_list() .items .iter() .filter_map(|item| match item { DisplayItem::Rule { y, .. } => Some(*y), _ => None, }) .collect::>() }; assert_eq!(rule_ys(&ragged), vec![0, 40]); document.ragged_bottom = false; let flush = Engine::layout_paged(&document).expect("paged"); assert_eq!(rule_ys(&flush), vec![0, 80]); } #[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_breaks_inside_a_paragraph() { let text = "word ".repeat(60); let unit = Unit::paragraph_with_style_and_face( 1, text, ParagraphStyle::default(), ParagraphFont::Roman, ); let VerticalItem::Paragraph(paragraph) = &unit.items[0] else { panic!("paragraph unit") }; let line_count = paragraph.lines.len(); assert!(line_count >= 4, "fixture should wrap: {line_count}"); let mut document = Document::new(paragraph.height / 2, vec![unit]); document.top_skip = 0; let engine = Engine::layout_paged(&document).expect("paragraphs are page-buildable"); assert!(engine.pages().len() >= 2, "half a paragraph per page"); let lines: usize = engine .pages() .iter() .flat_map(|page| page.items.iter()) .map(|item| match item { VerticalItem::Paragraph(slice) => slice.lines.len(), _ => 0, }) .sum(); assert_eq!(lines, line_count, "line slices keep every line"); assert!(engine.pages().iter().all(|page| { page.items .iter() .any(|item| matches!(item, VerticalItem::Paragraph(_))) })); } #[test] fn fill_glue_absorbs_the_page_set() { let mut document = Document::new( 200, vec![ Unit::rule(1, 100, 100), Unit::vertical( 2, vec![VerticalItem::StretchGlue(VerticalGlue::new(20, 10, 0))], ), Unit::vertical( 3, vec![VerticalItem::StretchGlue(VerticalGlue::with_order( 20, 1, 0, 1, ))], ), Unit::penalty(4, -10_000), ], ); document.ragged_bottom = false; let engine = Engine::layout_paged(&document).expect("paged"); let page = &engine.pages()[0]; let widths: Vec = page .items .iter() .filter_map(|item| match item { VerticalItem::StretchGlue(glue) => Some(glue.width), _ => None, }) .collect(); assert_eq!(widths, vec![20, 80], "only the fil glue stretches"); } #[test] fn output_routine_sees_fill_stretch_orders() { let mut document = Document::new(200, Vec::new()); document.units = vec![ Unit::rule(0, 10, 40), Unit::vertical( 1, vec![VerticalItem::StretchGlue(VerticalGlue::with_order( 20, 4 * 65_536, 0, 2, ))], ), Unit::penalty(2, -10_000), Unit::rule(3, 10, 40), ]; document.output_routine = Some(r"\ifdim\pagefillstretch>3pt\shipout\box255\fi".to_owned()); let engine = Engine::layout_paged(&document).expect("paged"); assert_eq!(engine.pages().len(), 1); assert!( engine.pages()[0] .items .iter() .any(|item| matches!(item, VerticalItem::Rule { .. })) ); } #[test] fn interpreted_output_sees_the_break_penalty() { let mut document = Document::new(100, Vec::new()); document.output_routine = Some(r"\ifnum\outputpenalty<-9999\shipout\box255\fi".to_owned()); document.units = vec![ Unit::rule(0, 10, 40), Unit::penalty(1, -10_000), Unit::rule(2, 10, 40), ]; let engine = Engine::layout_paged(&document).expect("paged layout"); assert_eq!(engine.pages().len(), 1); } #[test] fn interpreted_output_reads_the_page_number() { let mut document = Document::new(100, Vec::new()); document.output_routine = Some(r"\ifnum\pageno>1\shipout\box255\fi".to_owned()); document.units = vec![ Unit::rule(0, 10, 40), Unit::penalty(1, -10_000), Unit::rule(2, 10, 40), ]; let engine = Engine::layout_paged(&document).expect("paged layout"); assert_eq!(engine.pages().len(), 1); } #[test] fn dead_cycles_accumulate_until_the_next_shipout() { let mut document = Document::new(100, Vec::new()); document.output_routine = Some(r"\ifnum\deadcycles=1\shipout\box255\fi".to_owned()); document.units = vec![ Unit::rule(0, 10, 40), Unit::penalty(1, -10_000), Unit::rule(2, 10, 50), Unit::penalty(3, -10_000), Unit::rule(4, 10, 60), ]; let engine = Engine::layout_paged(&document).expect("paged layout"); assert_eq!(engine.pages().len(), 1); assert_eq!( engine.pages()[0].items[0], VerticalItem::Rule { width: 10, height: 50 } ); } #[test] fn output_routine_reads_insertion_registers() { let mut document = Document::new(100, vec![Unit::rule(0, 10, 40)]); document.insertion_classes = vec![InsertionClass { number: 1, fraction_percent: 100, max_height: Some(7 * 65_536), skip: Some(3 * 65_536), multiplier: 2000, }]; document.output_routine = Some(r"\ifnum\count1=2000\shipout\box255\else\relax\fi".to_owned()); let engine = Engine::layout_paged(&document).expect("paged"); assert_eq!(engine.pages().len(), 1); document.output_routine = Some(r"\ifdim\dimen1>6pt\shipout\box255\else\relax\fi".to_owned()); let engine = Engine::layout_paged(&document).expect("paged"); assert_eq!(engine.pages().len(), 1); document.output_routine = Some(r"\ifnum\count1=1000\shipout\box255\else\relax\fi".to_owned()); let engine = Engine::layout_paged(&document).expect("paged"); assert_eq!(engine.pages().len(), 0); } #[test] fn interpreted_output_can_ship_only_odd_pages() { let mut document = Document::new(100, Vec::new()); document.output_routine = Some(r"\ifodd\pageno\shipout\box255\fi".to_owned()); document.units = vec![ Unit::rule(0, 10, 40), Unit::penalty(1, -10_000), Unit::rule(2, 10, 40), ]; let engine = Engine::layout_paged(&document).expect("paged layout"); assert_eq!(engine.pages().len(), 1); } #[test] fn in_text_floats_flow_with_the_paged_builder() { let mut document = Document::new(100, Vec::new()); document.top_skip = 0; let mut float_unit = Unit::vertical( 2, vec![VerticalItem::Float(Float { placement: FloatPlacement::Here, width: 50, height: 30, gap_before: 5, gap_after: 5, content: Vec::new(), })], ); float_unit.source = "here".to_owned(); document.units = vec![Unit::rule(1, 50, 20), float_unit, Unit::rule(3, 50, 20)]; let engine = Engine::layout_paged(&document).expect("paged layout"); assert_eq!(engine.layout.pages.len(), 1, "20 + 40 + 20 fits 100"); assert!(engine.layout.pages[0] .items .iter() .any(|item| matches!(item, VerticalItem::Float(float) if float.placement == FloatPlacement::Here))); assert!(engine.layout.pages[0].floats.is_empty()); } #[test] fn in_text_float_gaps_count_towards_the_page_goal() { let mut document = Document::new(100, Vec::new()); document.top_skip = 0; let mut float_unit = Unit::vertical( 2, vec![VerticalItem::Float(Float { placement: FloatPlacement::Here, width: 50, height: 70, gap_before: 5, gap_after: 5, content: Vec::new(), })], ); float_unit.source = "here".to_owned(); document.units = vec![ Unit::rule(1, 50, 20), float_unit, Unit::vskip(3, 0), Unit::rule(4, 50, 5), ]; let engine = Engine::layout_paged(&document).expect("paged layout"); assert_eq!(engine.layout.pages.len(), 2, "20 + 80 + 5 exceeds 100"); assert!( engine.layout.pages[0] .items .iter() .any(|item| matches!(item, VerticalItem::Float(_))) ); assert!( engine.layout.pages[1] .items .iter() .all(|item| !matches!(item, VerticalItem::Float(_))) ); } #[test] fn paged_layout_expands_vertical_units() { let document = Document::new( 100, vec![Unit::vertical( 1, vec![ VerticalItem::Rule { width: 100, height: 60, }, VerticalItem::Glue(10), VerticalItem::Rule { width: 100, height: 60, }, ], )], ); let engine = Engine::layout_paged(&document).expect("vertical materials are page-buildable"); assert_eq!(engine.pages().len(), 2); assert_eq!(engine.pages()[0].sources, vec![(1, source_hash(""))]); } #[test] fn paragraph_skip_carries_its_stretch_into_pages() { let first = Unit::paragraph(1, "alpha beta gamma delta epsilon zeta"); let second = Unit::paragraph(2, "eta theta iota kappa lambda mu nu"); let mut document = Document::new(550 * 65_536, vec![first, second]); document.top_skip = 12 * 65_536; document.par_skip_stretch = 6 * 65_536; document.par_skip_shrink = 2 * 65_536; let engine = Engine::layout_paged(&document).expect("paged layout"); let page = &engine.pages()[0]; assert!( page.items.iter().any(|item| matches!( item, VerticalItem::StretchGlue(glue) if glue.width == 0 && glue.stretch == 6 * 65_536 && glue.shrink == 2 * 65_536 )), "parskip stretch missing from page items: {:?}", page.items ); } #[test] fn paged_layout_inserts_par_skip_between_paragraphs() { let mut style = ParagraphStyle::default(); style.line_height = 30; let mut document = Document::new( 60, vec![ Unit::paragraph_with_style(1, "one", style.clone()), Unit::paragraph_with_style(2, "two", style), ], ); assert_eq!( Engine::layout_paged(&document) .expect("paragraphs are page-buildable") .pages() .len(), 1 ); document.par_skip = 10; let engine = Engine::layout_paged(&document).expect("paragraphs are page-buildable"); assert_eq!(engine.pages().len(), 2); assert!(matches!( engine.pages()[1].items.first(), Some(VerticalItem::Paragraph(_)) )); } #[test] fn paged_layout_can_split_one_unit_across_pages() { let document = Document::new( 70, vec![Unit::vertical( 1, vec![ VerticalItem::Rule { width: 100, height: 60, }, VerticalItem::Penalty(0), VerticalItem::Rule { width: 100, height: 60, }, ], )], ); let engine = Engine::layout_paged(&document).expect("vertical materials are page-buildable"); assert_eq!(engine.pages().len(), 2); let rules = |page: &Page| { page.items .iter() .filter(|item| matches!(item, VerticalItem::Rule { .. })) .count() }; assert_eq!(rules(&engine.pages()[0]), 1); assert_eq!(rules(&engine.pages()[1]), 1); assert_eq!(engine.pages()[1].sources, vec![(1, source_hash(""))]); } #[test] fn insertion_count_scales_reserved_page_space() { let insertions = |document: &mut Document| { document.units = vec![ Unit::insertion( 1, 0, 30, vec![VerticalItem::Rule { width: 10, height: 30, }], ), Unit::insertion( 2, 0, 30, vec![VerticalItem::Rule { width: 10, height: 30, }], ), ]; }; let mut document = Document::new(100, Vec::new()); insertions(&mut document); assert_eq!(Engine::layout(&document).pages().len(), 1); document.insertion_classes = vec![InsertionClass { number: 0, fraction_percent: 100, max_height: None, skip: None, multiplier: 2000, }]; assert_eq!( Engine::layout(&document).pages().len(), 2, "a 2000 multiplier reserves 120pt for 60pt of insertions" ); } #[test] fn paged_layout_limits_page_depth() { let math = Unit { id: 1, source: String::new(), items: vec![VerticalItem::Math { atom: crate::math::MathAtom::Symbol('x'), width: 10, height: 70, depth: 30, }], paragraph_style: None, paragraph_runs: None, space_before: 0, space_stretch: 0, space_shrink: 0, }; let mut document = Document::new(100, vec![math, Unit::vskip(2, 0), Unit::rule(3, 100, 20)]); let deep = Engine::layout_paged(&document).expect("math is page-buildable"); assert_eq!( deep.pages().len(), 2, "depth beyond maxdepth pushes the rule onto its own page" ); document.max_depth = 30; let capped = Engine::layout_paged(&document).expect("math is page-buildable"); assert_eq!( capped.pages().len(), 1, "allowed depth keeps the rule on the first page" ); } #[test] fn output_routine_sees_paragraph_depth() { let paragraph = Paragraph { lines: vec![Vec::new()], height: 8 * 65_536, width: 5 * 65_536, depth: 2 * 65_536, font: ParagraphFont::Roman, left_skip: 0, line_indents: vec![0], line_baselines: vec![8 * 65_536], centered: false, right_aligned: false, }; let mut document = Document::new( 300 * 65_536, vec![Unit::vertical(1, vec![VerticalItem::Paragraph(paragraph)])], ); document.max_depth = 5 * 65_536; document.output_routine = Some("\\ifdim\\pagedepth>0pt\\shipout\\box255\\fi".to_string()); let deep = Engine::layout_paged(&document).expect("paragraph page"); assert_eq!(deep.pages().len(), 1, "maxdepth keeps the paragraph depth"); document.max_depth = 0; let capped = Engine::layout_paged(&document).expect("paragraph page"); assert_eq!(capped.pages().len(), 0, "maxdepth zero drops the depth"); document.output_routine = Some("\\ifdim\\pagedepth=0pt\\shipout\\box255\\fi".to_string()); let zero = Engine::layout_paged(&document).expect("paragraph page"); assert_eq!(zero.pages().len(), 1); } #[test] fn page_prev_graf_counts_the_last_paragraph_lines() { let style = ParagraphStyle { line_width: 60 * 65_536, par_indent: 0, ..ParagraphStyle::default() }; let paragraph = layout_paragraph_with_font( "alpha beta gamma delta epsilon zeta eta theta", &style, &Cmr10Metrics::Roman, ); let lines = paragraph.lines.len() as i64; assert!(lines > 1, "fixture should wrap, got {lines} lines"); let mut page = Page::empty(); page.items.push(VerticalItem::Paragraph(paragraph)); assert_eq!(page_prev_graf(&page), lines); let empty = Page::empty(); assert_eq!(page_prev_graf(&empty), 0); } #[test] fn output_routine_reads_the_page_box_height() { let pt = 65_536; let mut document = Document::new( 100 * pt, vec![ Unit::rule(1, 10 * pt, 40 * pt), Unit::penalty(2, -10_000), Unit::rule(3, 10 * pt, 70 * pt), ], ); document.output_routine = Some(r"\ifdim\ht255>50pt\shipout\box255\else\relax\fi".into()); let engine = Engine::layout_paged(&document).expect("paged layout"); assert_eq!(engine.pages().len(), 1); assert_eq!(item_height(&engine.pages()[0].items[0]), 70 * pt); } #[test] fn max_deadcycles_forces_a_page_out() { let document_with = |limit: i64| { let mut document = Document::new( 100, vec![ Unit::rule(1, 10, 90), Unit::penalty(2, -10_000), Unit::rule(3, 10, 90), Unit::penalty(4, -10_000), Unit::rule(5, 10, 90), Unit::penalty(6, -10_000), Unit::rule(7, 10, 90), ], ); document.output_routine = Some(r"\relax".into()); document.max_deadcycles = limit; document }; // With the default limit no page is ever shipped. let idle = Engine::layout_paged(&document_with(25)).expect("paged layout"); assert_eq!(idle.pages().len(), 0); // After two dead cycles TeX ships the third page itself, then the // fourth page starts a fresh dead cycle and is dropped too. let forced = Engine::layout_paged(&document_with(2)).expect("paged layout"); assert_eq!(forced.pages().len(), 1); assert_eq!(item_height(&forced.pages()[0].items[0]), 90); } #[test] fn output_register_assignments_persist_across_pages() { let mut document = Document::new( 100, vec![ Unit::rule(1, 10, 40), Unit::penalty(2, -10_000), Unit::rule(3, 10, 40), ], ); document.output_routine = Some( r"\ifnum\pageno=1\count2=1500\shipout\box255\else\ifnum\count2=1500\shipout\box255\fi\fi" .into(), ); let engine = Engine::layout(&document); assert_eq!(engine.pages().len(), 2); } #[test] fn output_routine_sees_the_page_depth() { let math = Unit { id: 1, source: String::new(), items: vec![VerticalItem::Math { atom: crate::math::MathAtom::Symbol('x'), width: 10, height: 500_000, depth: 300_000, }], paragraph_style: None, paragraph_runs: None, space_before: 0, space_stretch: 0, space_shrink: 0, }; let mut document = Document::new(800_000, vec![math]); document.max_depth = 400_000; document.output_routine = Some(r"\ifdim\pagedepth>4pt\shipout\box255\fi".to_owned()); let kept = Engine::layout_paged(&document).expect("math is page-buildable"); assert_eq!(kept.pages().len(), 1); document.max_depth = 0; let dropped = Engine::layout_paged(&document).expect("math is page-buildable"); assert_eq!(dropped.pages().len(), 0); } #[test] fn output_routine_sees_the_text_width() { let rule = Unit::rule(1, 100 * 65_536, 10 * 65_536); let mut document = Document::new(100 * 65_536, vec![rule]); document.text_width = 320 * 65_536; document.output_routine = Some(r"\ifdim\hsize=320pt\shipout\box255\fi".to_owned()); let kept = Engine::layout_paged(&document).expect("rule is page-buildable"); assert_eq!(kept.pages().len(), 1); document.output_routine = Some(r"\ifdim\wd255=319pt\shipout\box255\fi".to_owned()); let dropped = Engine::layout_paged(&document).expect("rule is page-buildable"); assert_eq!(dropped.pages().len(), 0); } #[test] fn paged_layout_expands_multi_item_units_and_places_insertions() { let stacked = Document::new( 100, vec![Unit::vertical( 1, vec![ VerticalItem::Rule { width: 80, height: 20, }, VerticalItem::Rule { width: 80, height: 20, }, ], )], ); let layout = Engine::layout_paged(&stacked).expect("multi-item units expand"); assert_eq!(layout.pages().len(), 1); assert_eq!(layout.pages()[0].items.len(), 2); let insertion = Document::new( 100, vec![ Unit::rule(1, 80, 20), Unit::insertion( 2, 0, 40, vec![VerticalItem::Rule { width: 80, height: 40, }], ), ], ); let layout = Engine::layout_paged(&insertion).expect("insertions are page-buildable"); assert_eq!(layout.pages().len(), 1); assert_eq!(layout.pages()[0].insertions.len(), 1); assert_eq!(layout.pages()[0].insertions[0].height, 40); assert_eq!(layout.pages()[0].insertions[0].items.len(), 1); } #[test] fn paged_layout_places_bottom_floats_at_the_page_end() { let mut document = Document::new( 100, vec![ Unit::rule(1, 100, 60), Unit::float(2, FloatPlacement::Bottom, 100, 30), ], ); document.text_float_sep = 0; let layout = Engine::layout_paged(&document).expect("bottom floats are page-buildable"); assert_eq!(layout.pages().len(), 1); assert_eq!(layout.pages()[0].floats.len(), 1); assert_eq!( layout.pages()[0].floats[0].placement, FloatPlacement::Bottom ); } #[test] fn paged_layout_defers_a_bottom_float_that_cannot_fit() { let mut document = Document::new( 100, vec![ Unit::rule(1, 100, 80), Unit::float(2, FloatPlacement::Bottom, 100, 30), Unit::rule(3, 100, 10), ], ); document.text_float_sep = 0; let layout = Engine::layout_paged(&document).expect("bottom floats are page-buildable"); assert_eq!(layout.pages().len(), 2); assert_eq!(layout.pages()[0].floats.len(), 0); // TeX keeps filling the page instead of breaking at the float. assert_eq!(layout.pages()[0].items.len(), 2); assert_eq!(layout.pages()[1].items.len(), 0); assert_eq!(layout.pages()[1].floats.len(), 1); assert_eq!( layout.pages()[1].floats[0].placement, FloatPlacement::Bottom ); } #[test] fn paged_edit_with_bottom_floats_rebuilds_with_the_float_queue() { let style = ParagraphStyle { line_width: 100 * 65_536, line_height: 12 * 65_536, ..ParagraphStyle::default() }; let paragraph = |id, text: &str| { Unit::paragraph_with_style_and_face(id, text, style.clone(), ParagraphFont::Roman) }; let mut document = Document::new( 40 * 65_536, vec![ paragraph(1, "alpha"), paragraph(2, "beta"), Unit::float(3, FloatPlacement::Bottom, 100, 20 * 65_536), paragraph(4, "gamma"), ], ); document.text_float_sep = 0; let mut engine = Engine::layout_paged(&document).expect("bottom floats are page-buildable"); let total = engine.pages().len(); assert_eq!(total, 2, "the float should be deferred to the second page"); let mut edited = document.clone(); edited.units[3] = paragraph(4, "delta"); engine.edit(&edited, 4, "delta"); assert_eq!( engine.recomputed_pages(), total, "the queue must force a full rebuild" ); let fresh = Engine::layout_paged(&edited).expect("paged"); let hashes: Vec<_> = engine.pages().iter().map(|page| page.hash).collect(); let fresh_hashes: Vec<_> = fresh.pages().iter().map(|page| page.hash).collect(); assert_eq!(hashes, fresh_hashes); } #[test] fn paged_layout_places_top_floats() { let document = Document::new( 100, vec![ Unit::float(1, FloatPlacement::Top, 100, 20), Unit::rule(2, 100, 60), ], ); let layout = Engine::layout_paged(&document).expect("top floats are page-buildable"); assert_eq!(layout.pages().len(), 1); assert_eq!(layout.pages()[0].floats.len(), 1); assert_eq!(layout.pages()[0].items.len(), 1); assert_eq!( layout.pages()[0].items[0], VerticalItem::Rule { width: 100, height: 60 } ); } #[test] fn paged_layout_honours_float_page_fraction() { let mut document = Document::new( 100, vec![ Unit::float(1, FloatPlacement::Top, 100, 60), Unit::rule(2, 100, 10), ], ); document.text_fraction_percent = 0; document.float_page_fraction_percent = 50; let layout = Engine::layout_paged(&document).expect("float page builds"); assert_eq!(layout.pages().len(), 2); assert!(layout.pages()[0].items.is_empty()); assert_eq!(layout.pages()[0].floats.len(), 1); document.float_page_fraction_percent = 90; let layout = Engine::layout_paged(&document).expect("shared page builds"); assert_eq!(layout.pages().len(), 1); assert_eq!(layout.pages()[0].items.len(), 1); } #[test] fn paged_float_reserves_text_float_sep_in_the_display_list() { let mut document = Document::new( 100, vec![ Unit::float(1, FloatPlacement::Top, 100, 20), Unit::rule(2, 100, 10), ], ); document.text_float_sep = 10; let engine = Engine::layout_paged(&document).expect("paged floats build"); let list = engine.pages()[0].display_list_with_layout(document.page_goal, document.text_float_sep); let body = list.items.iter().find_map(|item| match item { crate::render::DisplayItem::Rule { y, height, .. } if *height == 10 => Some(*y), _ => None, }); assert_eq!(body, Some(30)); } #[test] fn paged_layout_limits_floats_per_page() { let mut document = Document::new( 100, vec![ Unit::float(1, FloatPlacement::Top, 100, 20), Unit::float(2, FloatPlacement::Top, 100, 20), Unit::float(3, FloatPlacement::Top, 100, 20), ], ); document.text_float_sep = 0; document.top_number = 1; let layout = Engine::layout_paged(&document).expect("floats"); assert_eq!(layout.pages().len(), 3); assert!(layout.pages().iter().all(|page| page.floats.len() == 1)); document.top_number = 3; let layout = Engine::layout_paged(&document).expect("floats"); assert_eq!(layout.pages().len(), 1); } #[test] fn paged_layout_puts_a_late_top_float_on_its_own_page() { let mut document = Document::new( 100, vec![ Unit::rule(1, 100, 60), Unit::float(2, FloatPlacement::Top, 100, 20), Unit::rule(3, 100, 20), ], ); document.text_float_sep = 0; let layout = Engine::layout_paged(&document).expect("a late float still builds"); // TeX installs the float at the top of the page it is seen on, so the // float and both rules share one page. assert_eq!(layout.pages().len(), 1); assert_eq!(layout.pages()[0].floats.len(), 1); assert_eq!(layout.pages()[0].items.len(), 2); } #[test] fn text_float_sep_reserves_space_after_floats() { let units = || { vec![ Unit::float(1, FloatPlacement::Top, 100, 20), Unit::rule(2, 100, 40), Unit::vskip(3, 0), Unit::rule(4, 100, 40), ] }; let mut packed = Document::new(100, units()); packed.text_float_sep = 0; assert_eq!( Engine::layout_paged(&packed) .expect("packed floats build") .pages() .len(), 1 ); let mut spaced = Document::new(100, units()); spaced.text_float_sep = 20; let layout = Engine::layout_paged(&spaced).expect("spaced floats build"); assert_eq!(layout.pages().len(), 2); assert_eq!(layout.pages()[0].floats.len(), 1); assert_eq!(layout.pages()[0].items.len(), 1); } #[test] fn paged_layout_holds_over_insertion_material() { let mut document = Document::new( 100, vec![ Unit::rule(1, 80, 20), Unit::insertion( 2, 0, 80, vec![ VerticalItem::Rule { width: 80, height: 40, }, VerticalItem::Rule { width: 80, height: 40, }, ], ), Unit::rule(3, 80, 10), ], ); document.insertion_classes = vec![InsertionClass { number: 0, fraction_percent: 50, max_height: None, skip: None, multiplier: 1000, }]; let layout = Engine::layout_paged(&document).expect("insertions are page-buildable"); assert_eq!(layout.pages().len(), 2); assert_eq!(layout.pages()[0].insertions[0].items.len(), 1); assert_eq!(layout.pages()[1].insertions[0].items.len(), 1); // Body text keeps filling the page after a split insertion; the held // over material gets a page of its own. assert_eq!(layout.pages()[0].items.len(), 2); assert!(layout.pages()[1].items.is_empty()); } #[test] fn interpreted_output_can_drop_pages() { let mut document = Document::new( 100, vec![ Unit::rule(1, 80, 40), Unit::penalty(2, -10_000), Unit::rule(3, 80, 80), ], ); document.output_routine = Some(r"\ifdim\pagetotal>50\shipout\box255\fi".to_owned()); let layout = Engine::layout_paged(&document).expect("output routine is page-buildable"); assert_eq!(layout.pages().len(), 1); assert_eq!(layout.pages()[0].items.len(), 1); match &layout.pages()[0].items[0] { VerticalItem::Rule { height, .. } => assert_eq!(*height, 80), other => panic!("unexpected item {other:?}"), } } #[test] fn interpreted_output_ships_every_page_when_asked_to() { let mut document = Document::new( 100, vec![ Unit::rule(1, 80, 40), Unit::penalty(2, -10_000), Unit::rule(3, 80, 80), ], ); document.output_routine = Some(r"\shipout\box255".to_owned()); let layout = Engine::layout_paged(&document).expect("output routine is page-buildable"); assert_eq!(layout.pages().len(), 2); } #[test] fn invalid_output_routines_fall_back_to_the_scrolling_builder() { let mut document = Document::new(100, vec![Unit::rule(1, 80, 40)]); document.output_routine = Some(r"\vbox{}".to_owned()); assert!(Engine::layout_paged(&document).is_none()); } #[test] fn paragraphs_break_pages_without_par_skip() { let style = ParagraphStyle { line_width: 100 * 65_536, line_height: 12 * 65_536, ..ParagraphStyle::default() }; let units = [1_u64, 2, 3] .into_iter() .map(|id| { Unit::paragraph_with_style_and_face( id, "alpha", style.clone(), ParagraphFont::Roman, ) }) .collect(); let document = Document::new(20 * 65_536, units); let engine = Engine::layout_paged(&document).expect("paged"); assert_eq!(engine.pages().len(), 3); } #[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_eq!(engine.changed_pages(), &[1]); assert_eq!(engine.recomputed_pages(), 1); } #[test] fn paged_edit_replays_when_insertions_start_later() { let style = ParagraphStyle { line_width: 100 * 65_536, line_height: 12 * 65_536, ..ParagraphStyle::default() }; let paragraph = |id, text: &str| { Unit::paragraph_with_style_and_face(id, text, style.clone(), ParagraphFont::Roman) }; let mut document = Document::new( 20 * 65_536, vec![ paragraph(1, "alpha"), paragraph(2, "beta"), paragraph(3, "gamma"), paragraph(4, "delta"), Unit::insertion( 5, 0, 5 * 65_536, vec![VerticalItem::Rule { width: 0, height: 5 * 65_536, }], ), ], ); document.par_skip = 2 * 65_536; let mut engine = Engine::layout_paged(&document).expect("paged"); assert_eq!(engine.pages().len(), 4); let first = engine.pages()[0].hash; engine.edit(&document, 3, "epsilon"); assert_eq!(engine.pages()[0].hash, first); assert!(engine.recomputed_pages() < 4); } #[test] fn paged_edit_rebuilds_when_insertions_precede_the_edit() { let style = ParagraphStyle { line_width: 100 * 65_536, line_height: 12 * 65_536, ..ParagraphStyle::default() }; let paragraph = |id, text: &str| { Unit::paragraph_with_style_and_face(id, text, style.clone(), ParagraphFont::Roman) }; let mut document = Document::new( 20 * 65_536, vec![ Unit::insertion( 1, 0, 5 * 65_536, vec![VerticalItem::Rule { width: 0, height: 5 * 65_536, }], ), paragraph(2, "alpha"), paragraph(3, "beta"), paragraph(4, "gamma"), ], ); document.par_skip = 2 * 65_536; let mut engine = Engine::layout_paged(&document).expect("paged"); let total = engine.pages().len(); engine.edit(&document, 4, "delta"); assert_eq!(engine.recomputed_pages(), total); } #[test] fn paged_edit_keeps_untouched_pages() { let style = ParagraphStyle { line_width: 200 * 65_536, line_height: 12 * 65_536, ..ParagraphStyle::default() }; let paragraph = |id, text: &str| { Unit::paragraph_with_style_and_face(id, text, style.clone(), ParagraphFont::Roman) }; let mut document = Document::new( 16 * 65_536, vec![ paragraph(1, "alpha beta"), paragraph(2, "gamma delta"), paragraph(3, "epsilon zeta"), ], ); document.par_skip = 65_536; let mut engine = Engine::layout_paged(&document).expect("paragraphs are page-buildable"); assert_eq!(engine.pages().len(), 3); let first = engine.pages()[0].hash; let second = engine.pages()[1].hash; engine.edit(&document, 3, "eta theta iota"); assert_eq!(engine.pages()[0].hash, first); assert_eq!(engine.pages()[1].hash, second); assert_eq!(engine.changed_pages(), &[2]); assert_eq!(engine.recomputed_pages(), 1); } #[test] fn paged_edit_falls_back_when_insertions_are_present() { let style = ParagraphStyle { line_width: 200 * 65_536, line_height: 12 * 65_536, ..ParagraphStyle::default() }; let document = Document::new( 16 * 65_536, vec![ Unit::paragraph_with_style_and_face( 1, "alpha beta", style.clone(), ParagraphFont::Roman, ), Unit::insertion( 2, 0, 65_536, vec![VerticalItem::Rule { width: 10, height: 65_536, }], ), Unit::paragraph_with_style_and_face(3, "gamma delta", style, ParagraphFont::Roman), ], ); let mut engine = Engine::layout_paged(&document).expect("insertions are page-buildable"); let pages = engine.pages().len(); engine.edit(&document, 3, "epsilon zeta"); assert_eq!(engine.recomputed_pages(), pages); } #[test] fn space_before_inserts_vertical_glue_between_units() { let mut second = Unit::paragraph(2, "bbb"); second.space_before = 20; let document = Document::new(100, vec![Unit::paragraph(1, "aaa"), second]); let engine = Engine::layout(&document); assert_eq!(engine.pages().len(), 1); let items = &engine.pages()[0].items; assert_eq!(items.len(), 3); assert!(matches!(items[1], VerticalItem::Glue(20))); } #[test] fn space_before_can_force_a_paged_break() { let mut second = Unit::paragraph(2, "bbb"); second.space_before = 20; let document = Document::new(30, vec![Unit::paragraph(1, "aaa"), second]); let engine = Engine::layout_paged(&document).expect("paged layout"); assert_eq!(engine.pages().len(), 2); } #[test] fn incremental_layout_keeps_space_before() { let mut second = Unit::paragraph(2, "bbb"); second.space_before = 20; let document = Document::new(100, vec![Unit::paragraph(1, "aaa"), second]); let mut engine = Engine::layout(&document); engine.edit(&document, 2, "bbb edited"); let page = &engine.pages()[0]; assert!( page.items .iter() .any(|item| matches!(item, VerticalItem::Glue(20))) ); } } #[cfg(test)] mod runs_edit_tests { use super::*; fn bold_glyphs(engine: &Engine) -> usize { engine .pages() .iter() .flat_map(|page| page.display_list().items) .filter(|item| { matches!( item, crate::render::DisplayItem::Text { font: crate::render::FontFace::Bold, .. } ) }) .count() } #[test] fn editing_runs_preserves_mixed_faces() { let style = ParagraphStyle::default(); let unit = Unit::paragraph_with_style_and_runs( 1, "a \\textbf{b}", style, vec![ (ParagraphFont::Roman, "a ".to_string()), (ParagraphFont::Bold, "b".to_string()), ], ); let document = Document::new(2_000, vec![unit]); let mut engine = Engine::layout(&document); assert!(bold_glyphs(&engine) > 0); engine.edit_runs( &document, 1, "a \\textbf{cc}", vec![ (ParagraphFont::Roman, "a ".to_string()), (ParagraphFont::Bold, "cc".to_string()), ], ); assert!(bold_glyphs(&engine) > 0); } }