6802 lines
248 KiB
Rust
6802 lines
248 KiB
Rust
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 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<HalignCell>,
|
|
pub rule: bool,
|
|
}
|
|
|
|
/// A laid-out `\halign` table: natural column widths plus row rules.
|
|
#[derive(Clone, Debug, PartialEq, Eq, Hash, serde::Serialize, serde::Deserialize)]
|
|
pub struct Halign {
|
|
pub rows: Vec<HalignRow>,
|
|
pub column_widths: Vec<i64>,
|
|
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.
|
|
pub fn split_for_height(&self, max_height: i64) -> Vec<Halign> {
|
|
if self.rows.is_empty() {
|
|
return vec![self.clone()];
|
|
}
|
|
let max_height = max_height.max(self.line_height);
|
|
let mut chunks = Vec::new();
|
|
let mut start = 0_usize;
|
|
let mut height = 0_i64;
|
|
for (index, row) in self.rows.iter().enumerate() {
|
|
let row_height = if row.rule { 26_214 } else { self.line_height };
|
|
if index > start && height + row_height > max_height {
|
|
chunks.push(Self {
|
|
rows: self.rows[start..index].to_vec(),
|
|
column_widths: self.column_widths.clone(),
|
|
width: self.width,
|
|
height,
|
|
line_height: self.line_height,
|
|
});
|
|
start = index;
|
|
height = 0;
|
|
}
|
|
height += row_height;
|
|
}
|
|
chunks.push(Self {
|
|
rows: self.rows[start..].to_vec(),
|
|
column_widths: self.column_widths.clone(),
|
|
width: self.width,
|
|
height,
|
|
line_height: self.line_height,
|
|
});
|
|
chunks
|
|
}
|
|
|
|
/// The horizontal rectangle occupied by a cell's text: `(x, width)`.
|
|
///
|
|
/// Spanned cells include the intercolumn gaps they cover. The x offset is
|
|
/// the aligned start inside that rectangle.
|
|
pub fn cell_box(&self, row_index: usize, cell_index: usize) -> Option<(i64, i64)> {
|
|
let row = self.rows.get(row_index)?;
|
|
let cell = row.cells.get(cell_index)?;
|
|
let mut column = 0_usize;
|
|
for previous in &row.cells[..cell_index] {
|
|
column += previous.span.max(1);
|
|
}
|
|
let span = cell
|
|
.span
|
|
.max(1)
|
|
.min(self.column_widths.len().saturating_sub(column));
|
|
if span == 0 {
|
|
return None;
|
|
}
|
|
let intercolumn = if self.column_widths.len() > 1 {
|
|
(self.width - self.column_widths.iter().copied().sum::<i64>())
|
|
/ (self.column_widths.len() as i64 - 1)
|
|
} else {
|
|
0
|
|
};
|
|
let gaps = intercolumn * (span.saturating_sub(1) as i64);
|
|
let width = self.column_widths[column..column + span]
|
|
.iter()
|
|
.sum::<i64>()
|
|
+ gaps;
|
|
let x: i64 = self.column_widths[..column].iter().sum::<i64>() + intercolumn * column as i64;
|
|
let text_width = cell
|
|
.text
|
|
.chars()
|
|
.map(|character| {
|
|
if character.is_whitespace() {
|
|
4 * 65_536
|
|
} else {
|
|
10 * 65_536
|
|
}
|
|
})
|
|
.sum::<i64>();
|
|
let offset = match cell.alignment {
|
|
CellAlignment::Left => 0,
|
|
CellAlignment::Center => (width - text_width).max(0) / 2,
|
|
CellAlignment::Right => (width - text_width).max(0),
|
|
};
|
|
Some((x + offset, width))
|
|
}
|
|
}
|
|
|
|
/// Vertical material reserved at the bottom of a page (footnotes etc.).
|
|
#[derive(Clone, Debug, PartialEq, Eq, Hash, serde::Serialize, serde::Deserialize)]
|
|
pub struct Insertion {
|
|
pub class: u8,
|
|
pub height: i64,
|
|
pub items: Vec<VerticalItem>,
|
|
}
|
|
|
|
/// 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<VerticalItem>,
|
|
}
|
|
|
|
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<VerticalItem>,
|
|
/// 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<ParagraphStyle>,
|
|
/// 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<HalignRow>, column_count: usize, intercolumn: i64) -> Self {
|
|
let intercolumn = intercolumn.saturating_mul(65_536);
|
|
let mut column_widths = vec![0_i64; column_count];
|
|
for row in &rows {
|
|
let mut column = 0_usize;
|
|
for cell in &row.cells {
|
|
let span = cell.span.max(1).min(column_count.saturating_sub(column));
|
|
if span == 1 {
|
|
let width: i64 = cell
|
|
.text
|
|
.chars()
|
|
.map(|character| {
|
|
if character.is_whitespace() {
|
|
4 * 65_536
|
|
} else {
|
|
10 * 65_536
|
|
}
|
|
})
|
|
.sum();
|
|
if let Some(slot) = column_widths.get_mut(column) {
|
|
*slot = (*slot).max(width);
|
|
}
|
|
}
|
|
column += span;
|
|
}
|
|
}
|
|
for row in &rows {
|
|
let mut column = 0_usize;
|
|
for cell in &row.cells {
|
|
let span = cell.span.max(1).min(column_count.saturating_sub(column));
|
|
if span > 1 {
|
|
let gaps = intercolumn * (span.saturating_sub(1) as i64);
|
|
let available: i64 = column_widths[column..column + span]
|
|
.iter()
|
|
.copied()
|
|
.sum::<i64>()
|
|
+ gaps;
|
|
let needed: i64 = cell.text.chars().count() as i64 * 10 * 65_536;
|
|
let extra = (needed - available).max(0);
|
|
for offset in 0..span {
|
|
column_widths[column + offset] += extra / span as i64;
|
|
}
|
|
}
|
|
column += span;
|
|
}
|
|
}
|
|
let gaps = intercolumn * column_count.saturating_sub(1) as i64;
|
|
let width = column_widths.iter().sum::<i64>() + gaps;
|
|
let line_height = 12 * 65_536;
|
|
let rule_height = 26_214; // 0.4pt
|
|
let height = rows
|
|
.iter()
|
|
.map(|row| if row.rule { rule_height } else { line_height })
|
|
.sum();
|
|
Self {
|
|
id,
|
|
source: "halign".to_owned(),
|
|
paragraph_style: None,
|
|
space_before: 0,
|
|
space_stretch: 0,
|
|
space_shrink: 0,
|
|
items: vec![VerticalItem::Halign(Halign {
|
|
rows,
|
|
column_widths,
|
|
width,
|
|
height,
|
|
line_height,
|
|
})],
|
|
}
|
|
}
|
|
|
|
/// Parse a small TeX-like halign body with an `l`/`c`/`r` column template.
|
|
pub fn halign_from_source(
|
|
id: UnitId,
|
|
source: &str,
|
|
column_count: usize,
|
|
intercolumn: i64,
|
|
) -> Self {
|
|
let template = "l".repeat(column_count.max(1));
|
|
Self::halign_from_source_with_template(id, &template, source, intercolumn)
|
|
}
|
|
|
|
/// Parse an `l`/`c`/`r` column template plus a halign body.
|
|
pub fn halign_from_source_with_template(
|
|
id: UnitId,
|
|
template: &str,
|
|
source: &str,
|
|
intercolumn: i64,
|
|
) -> Self {
|
|
let alignments: Vec<CellAlignment> = template
|
|
.chars()
|
|
.map(|character| match character {
|
|
'c' => CellAlignment::Center,
|
|
'r' => CellAlignment::Right,
|
|
_ => CellAlignment::Left,
|
|
})
|
|
.collect();
|
|
let column_count = alignments.len().max(1);
|
|
let mut rows = Vec::new();
|
|
for raw_row in source.split(r"\\") {
|
|
if raw_row.trim().is_empty() {
|
|
continue;
|
|
}
|
|
let mut raw_row = raw_row.trim();
|
|
if let Some(rest) = raw_row.strip_prefix(r"\noalign") {
|
|
let rest = rest.trim_start();
|
|
if let Some(body) = rest.strip_prefix('{') {
|
|
if let Some((_, tail)) = body.split_once('}') {
|
|
raw_row = tail.trim();
|
|
}
|
|
}
|
|
}
|
|
let mut rule = false;
|
|
if let Some(rest) = raw_row.strip_prefix(r"\hline") {
|
|
rule = true;
|
|
raw_row = rest.trim();
|
|
}
|
|
if rule {
|
|
rows.push(HalignRow {
|
|
cells: Vec::new(),
|
|
rule: true,
|
|
});
|
|
}
|
|
if raw_row.is_empty() {
|
|
continue;
|
|
}
|
|
let mut cells = Vec::new();
|
|
for raw_cell in raw_row.split('&') {
|
|
let mut text = raw_cell.trim().to_owned();
|
|
let mut span = 1;
|
|
if let Some(rest) = text.strip_prefix(r"\span") {
|
|
span = 2;
|
|
text = rest.trim().to_owned();
|
|
}
|
|
if let Some(rest) = text.strip_prefix(r"\multispan") {
|
|
let rest = rest.trim_start();
|
|
if let Some(body) = rest.strip_prefix('{') {
|
|
if let Some((count, tail)) = body.split_once('}') {
|
|
span = count.trim().parse().unwrap_or(1).max(1);
|
|
text = tail.trim().to_owned();
|
|
}
|
|
}
|
|
}
|
|
if let Some(rest) = text.strip_prefix(r"\omit") {
|
|
text = rest.trim().to_owned();
|
|
}
|
|
let column: usize = cells.iter().map(|cell: &HalignCell| cell.span.max(1)).sum();
|
|
cells.push(HalignCell {
|
|
text,
|
|
span,
|
|
alignment: alignments
|
|
.get(column)
|
|
.copied()
|
|
.unwrap_or(CellAlignment::Left),
|
|
});
|
|
}
|
|
rows.push(HalignRow { cells, rule: false });
|
|
}
|
|
Self::halign(id, rows, column_count, intercolumn)
|
|
}
|
|
|
|
/// A running mark item, recorded on the page where it is shipped out.
|
|
pub fn mark(id: UnitId, class: u8, text: &str) -> Self {
|
|
Self::vertical(
|
|
id,
|
|
vec![VerticalItem::Mark(Mark {
|
|
class,
|
|
text: text.to_owned(),
|
|
})],
|
|
)
|
|
}
|
|
|
|
/// A top/bottom float item.
|
|
pub fn float(id: UnitId, placement: FloatPlacement, width: i64, height: i64) -> Self {
|
|
Self::vertical(
|
|
id,
|
|
vec![VerticalItem::Float(Float {
|
|
placement,
|
|
width,
|
|
height,
|
|
gap_before: 0,
|
|
gap_after: 0,
|
|
content: Vec::new(),
|
|
})],
|
|
)
|
|
}
|
|
|
|
/// Build a float that carries vertical material.
|
|
pub fn float_with_content(
|
|
id: UnitId,
|
|
placement: FloatPlacement,
|
|
width: i64,
|
|
height: i64,
|
|
content: Vec<VerticalItem>,
|
|
) -> 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<String>) -> 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<String>, font: ParagraphFont) -> Self {
|
|
Self::paragraph_with_style_and_face(id, source, ParagraphStyle::default(), font)
|
|
}
|
|
|
|
pub fn paragraph_with_style(
|
|
id: UnitId,
|
|
source: impl Into<String>,
|
|
style: ParagraphStyle,
|
|
) -> Self {
|
|
Self::paragraph_with_style_and_face(id, source, style, ParagraphFont::Roman)
|
|
}
|
|
|
|
/// Build a paragraph unit with both an explicit style and font face.
|
|
pub fn paragraph_with_style_and_face(
|
|
id: UnitId,
|
|
source: impl Into<String>,
|
|
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),
|
|
space_before: 0,
|
|
space_stretch: 0,
|
|
space_shrink: 0,
|
|
}
|
|
}
|
|
|
|
/// Build a unit from a math atom using CMR10 metrics.
|
|
pub fn math(
|
|
id: UnitId,
|
|
atom: crate::math::MathAtom,
|
|
font: &crate::cmr10::Cmr10Metrics,
|
|
) -> Self {
|
|
let math_box = math::layout_math(&atom, font);
|
|
Self::vertical(
|
|
id,
|
|
vec![VerticalItem::Math {
|
|
atom,
|
|
width: math_box.width,
|
|
height: math_box.height,
|
|
depth: math_box.depth,
|
|
}],
|
|
)
|
|
}
|
|
|
|
/// Build a unit from arbitrary vertical material.
|
|
pub fn vertical(id: UnitId, items: Vec<VerticalItem>) -> Self {
|
|
Self {
|
|
id,
|
|
source: String::new(),
|
|
items,
|
|
paragraph_style: 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<VerticalItem>) -> 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<number>`: an absolute cap on this class's height on one
|
|
/// page. `None` uses only the percentage share.
|
|
#[serde(default)]
|
|
pub max_height: Option<i64>,
|
|
/// TeX's `\skip<number>`: space inserted before this class on a page.
|
|
/// `None` falls back to `Document::insertion_skip`.
|
|
#[serde(default)]
|
|
pub skip: Option<i64>,
|
|
/// TeX's `\count<number>` 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<Unit>,
|
|
pub page_goal: i64,
|
|
/// Unit indices that start on a fresh page (TeX `\newpage` forced breaks).
|
|
#[serde(default)]
|
|
pub page_breaks: Vec<usize>,
|
|
/// 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-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<InsertionClass>,
|
|
/// 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 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<String>,
|
|
}
|
|
|
|
fn default_paper_width() -> i64 {
|
|
612 * 65_536
|
|
}
|
|
|
|
fn default_paper_height() -> i64 {
|
|
792 * 65_536
|
|
}
|
|
|
|
fn default_text_fraction() -> u8 {
|
|
50
|
|
}
|
|
|
|
fn default_float_sep() -> i64 {
|
|
12 * 65_536
|
|
}
|
|
|
|
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<Unit>) -> Self {
|
|
Self {
|
|
units,
|
|
page_goal,
|
|
page_breaks: Vec::new(),
|
|
paper_width: default_paper_width(),
|
|
paper_height: default_paper_height(),
|
|
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(),
|
|
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<number>` 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 {
|
|
self.insertion_classes
|
|
.iter()
|
|
.find(|entry| entry.number == class)
|
|
.map_or(self.page_goal, |entry| {
|
|
let fraction = self.page_goal * i64::from(entry.fraction_percent) / 100;
|
|
entry
|
|
.max_height
|
|
.map_or(fraction, |absolute| fraction.min(absolute))
|
|
})
|
|
}
|
|
pub fn with_top_skip(mut self, top_skip: i64) -> Self {
|
|
self.top_skip = top_skip;
|
|
self
|
|
}
|
|
|
|
/// TeX's `\skip<insert class>`, 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<VerticalItem>,
|
|
#[serde(default)]
|
|
pub insertions: Vec<Insertion>,
|
|
#[serde(default)]
|
|
pub marks: Vec<Mark>,
|
|
#[serde(default)]
|
|
pub floats: Vec<Float>,
|
|
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<VerticalNode>, Vec<usize>, Vec<VerticalItem>)> {
|
|
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
|
|
};
|
|
nodes.push(VerticalNode::Box {
|
|
height: remaining.height,
|
|
depth: 0,
|
|
});
|
|
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;
|
|
}
|
|
}
|
|
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: 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 `\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<VerticalItem>,
|
|
) -> Vec<VerticalItem> {
|
|
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));
|
|
}
|
|
material
|
|
}
|
|
|
|
fn take_insertion_prefix(
|
|
document: &Document,
|
|
class: u8,
|
|
items: Vec<VerticalItem>,
|
|
capacity: i64,
|
|
) -> (Vec<VerticalItem>, Vec<VerticalItem>, 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 = document.insertion_reserve(class, item_height(&item));
|
|
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<u8, Insertion>,
|
|
used: &mut BTreeMap<u8, i64>,
|
|
class: u8,
|
|
accepted: Vec<VerticalItem>,
|
|
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<Page>,
|
|
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<Page>,
|
|
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<VerticalItem>,
|
|
/// Insertions already attached to the current page.
|
|
#[serde(default)]
|
|
pub page_insertions: Vec<Insertion>,
|
|
/// 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<Mark>,
|
|
/// Floats already attached to the current page.
|
|
#[serde(default)]
|
|
pub page_floats: Vec<Float>,
|
|
}
|
|
|
|
#[derive(Clone, Debug, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
|
|
pub struct Layout {
|
|
pub pages: Vec<Page>,
|
|
/// `checkpoints[i]` is the state before executing unit `i`.
|
|
pub checkpoints: Vec<Checkpoint>,
|
|
/// 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<usize>,
|
|
/// 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<usize>,
|
|
}
|
|
|
|
impl Layout {
|
|
pub fn page_index_for(&self, unit_index: usize) -> Option<usize> {
|
|
self.checkpoints.get(unit_index).map(|c| c.page_index)
|
|
}
|
|
}
|
|
|
|
/// Shipout hook corresponding to TeX's `\output` stage.
|
|
///
|
|
/// This is deliberately small: the routine can inspect and mutate each
|
|
/// assembled page (and later change page styles) but it is Rust code rather
|
|
/// than an interpreted token list.
|
|
pub trait OutputRoutine {
|
|
fn shipout(&mut self, page: &mut Page, page_number: usize);
|
|
|
|
/// TeX's output routine may decide to ship a page before it is full.
|
|
/// This hook is consulted between units, so a return of `true` seals the
|
|
/// current non-empty page and starts the next one.
|
|
fn wants_break(&mut self, _page: &Page, _used: i64, _page_goal: i64) -> bool {
|
|
false
|
|
}
|
|
}
|
|
|
|
pub struct NoOutput;
|
|
|
|
impl OutputRoutine for NoOutput {
|
|
fn shipout(&mut self, _page: &mut Page, _page_number: usize) {}
|
|
}
|
|
|
|
pub struct Engine {
|
|
layout: Layout,
|
|
}
|
|
|
|
impl Engine {
|
|
pub fn layout(document: &Document) -> Self {
|
|
Self::layout_with_output(document, &mut NoOutput)
|
|
}
|
|
|
|
pub fn layout_with_output(document: &Document, output: &mut impl OutputRoutine) -> Self {
|
|
let mut pages = Vec::new();
|
|
let mut checkpoints = Vec::with_capacity(document.units.len());
|
|
let mut current = Page::empty();
|
|
let mut used = 0_i64;
|
|
let mut insertion_height = 0_i64;
|
|
for (unit_index, unit) in document.units.iter().enumerate() {
|
|
if !current.items.is_empty() && output.wants_break(¤t, used, document.page_goal) {
|
|
output.shipout(&mut current, pages.len() + 1);
|
|
pages.push(std::mem::replace(&mut current, Page::empty()));
|
|
used = document.top_skip;
|
|
insertion_height = 0;
|
|
}
|
|
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<Self> {
|
|
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 builder = Self::paged_builder(document);
|
|
let mut pages = Vec::new();
|
|
let mut page_penalties = Vec::new();
|
|
let mut page_depths = Vec::new();
|
|
let mut page_stretches = Vec::new();
|
|
let mut page_fil_stretches = Vec::new();
|
|
let mut page_fill_stretches = Vec::new();
|
|
let mut page_filll_stretches = Vec::new();
|
|
let mut page_shrinks = Vec::new();
|
|
let mut page_goals: Vec<i64> = Vec::new();
|
|
let mut held: BTreeMap<u8, Vec<VerticalItem>> = BTreeMap::new();
|
|
let fragments = builder.build(&nodes);
|
|
for fragment in &fragments {
|
|
let mut items = Vec::new();
|
|
let mut marks = Vec::new();
|
|
let mut floats = Vec::new();
|
|
let mut sources = Vec::new();
|
|
let mut insertions: BTreeMap<u8, Insertion> = BTreeMap::new();
|
|
let mut used: BTreeMap<u8, i64> = BTreeMap::new();
|
|
|
|
// Material held over from the previous page fills its class first.
|
|
let held_classes: Vec<u8> = held.keys().copied().collect();
|
|
for class in held_classes {
|
|
let material = held.remove(&class).unwrap_or_default();
|
|
let limit = document.insertion_class_limit(class);
|
|
let capacity = (limit - used.get(&class).copied().unwrap_or(0)).max(0);
|
|
let material = held_insertion_material(document, capacity, material);
|
|
let (accepted, remainder, reserved) =
|
|
take_insertion_prefix(document, class, material, capacity);
|
|
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 = document.insertion_class_limit(class);
|
|
let capacity = (limit - used.get(&class).copied().unwrap_or(0)).max(0);
|
|
let (accepted, remainder, reserved) = take_insertion_prefix(
|
|
document,
|
|
class,
|
|
insertion.items.clone(),
|
|
capacity,
|
|
);
|
|
attach_insertion(&mut insertions, &mut used, class, accepted, reserved);
|
|
if !remainder.is_empty() {
|
|
held.entry(class).or_default().extend(remainder);
|
|
}
|
|
}
|
|
item @ VerticalItem::Float(float) => {
|
|
if float.placement == FloatPlacement::Here {
|
|
items.push(item.clone());
|
|
} else {
|
|
floats.push(float.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.floats = floats;
|
|
let reserved: i64 = insertions.values().map(|insertion| insertion.height).sum();
|
|
page_goals.push((document.page_goal - reserved).max(0));
|
|
page.insertions = insertions.into_values().collect();
|
|
page.sources = sources;
|
|
page.seal_in_place();
|
|
pages.push(page);
|
|
page_penalties.push(fragment.penalty);
|
|
page_depths.push(fragment.depth);
|
|
page_stretches.push(fragment.stretch);
|
|
page_fil_stretches.push(fragment.stretches[1]);
|
|
page_fill_stretches.push(fragment.stretches[2]);
|
|
page_filll_stretches.push(fragment.stretches[3]);
|
|
page_shrinks.push(fragment.shrink);
|
|
}
|
|
|
|
// 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<u8> = held.keys().copied().collect();
|
|
let mut insertions: BTreeMap<u8, Insertion> = BTreeMap::new();
|
|
let mut used: BTreeMap<u8, i64> = 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 (accepted, remainder, reserved) =
|
|
take_insertion_prefix(document, class, material, limit);
|
|
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_goals.push((document.page_goal - reserved).max(0));
|
|
page.insertions = insertions.into_values().collect();
|
|
page.seal_in_place();
|
|
pages.push(page);
|
|
page_penalties.push(10_000);
|
|
page_depths.push(0);
|
|
page_stretches.push(0);
|
|
page_fil_stretches.push(0);
|
|
page_fill_stretches.push(0);
|
|
page_filll_stretches.push(0);
|
|
page_shrinks.push(0);
|
|
}
|
|
if let Some(source) = &document.output_routine {
|
|
let program = output::OutputProgram::parse(source).ok()?;
|
|
let mut shipped = Vec::new();
|
|
let mut deadcycles = 0_i64;
|
|
let mut pageno = 1_i64;
|
|
// TeX's output registers are global: assignments made by the
|
|
// routine on one page stay visible on later 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);
|
|
}
|
|
for (index, page) in pages.into_iter().enumerate() {
|
|
let page_total: i64 = page.items.iter().map(item_height).sum();
|
|
let mut context = output::OutputContext {
|
|
page_goal: page_goals.get(index).copied().unwrap_or(document.page_goal),
|
|
page_total,
|
|
page_depth: page_depths.get(index).copied().unwrap_or(0),
|
|
page_stretch: page_stretches.get(index).copied().unwrap_or(0),
|
|
page_fil_stretch: page_fil_stretches.get(index).copied().unwrap_or(0),
|
|
page_fill_stretch: page_fill_stretches.get(index).copied().unwrap_or(0),
|
|
page_filll_stretch: page_filll_stretches.get(index).copied().unwrap_or(0),
|
|
page_shrink: page_shrinks.get(index).copied().unwrap_or(0),
|
|
vsize: document.page_goal,
|
|
top_skip: document.top_skip,
|
|
max_depth: document.max_depth,
|
|
output_penalty: page_penalties.get(index).copied().unwrap_or(10_000),
|
|
max_deadcycles: document.max_deadcycles,
|
|
insertion_counts,
|
|
insertion_dimens,
|
|
insertion_skips,
|
|
pageno,
|
|
deadcycles,
|
|
prev_graf: page_prev_graf(&page),
|
|
};
|
|
let forced = deadcycles >= document.max_deadcycles.max(0);
|
|
if forced {
|
|
context.deadcycles = 0;
|
|
}
|
|
let shipped_now = 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_now > 0 {
|
|
shipped.push(page);
|
|
deadcycles = 0;
|
|
} else {
|
|
// TeX counts a page the output routine does not ship as a
|
|
// dead cycle; the count resets on the next shipout.
|
|
deadcycles += 1;
|
|
}
|
|
}
|
|
pages = shipped;
|
|
}
|
|
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(),
|
|
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<Self> {
|
|
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,
|
|
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,
|
|
prev_graf: page_prev_graf(&page),
|
|
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<Page> {
|
|
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;
|
|
};
|
|
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<Page> = 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<usize> = 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<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 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 space_before = next.units[unit_index].space_before;
|
|
let space_stretch = next.units[unit_index].space_stretch;
|
|
let space_shrink = next.units[unit_index].space_shrink;
|
|
next.units[unit_index] = Unit::paragraph_with_style_and_face(unit_id, source, style, font);
|
|
next.units[unit_index].space_before = space_before;
|
|
next.units[unit_index].space_stretch = space_stretch;
|
|
next.units[unit_index].space_shrink = space_shrink;
|
|
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 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,
|
|
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_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::<Vec<_>>();
|
|
assert_eq!(counts, vec![3, 2, 2], "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_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,
|
|
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,
|
|
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,
|
|
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,
|
|
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<usize>,
|
|
}
|
|
|
|
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,
|
|
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,
|
|
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 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 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,
|
|
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,
|
|
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,
|
|
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<i64> = 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::<usize>().ok())
|
|
.expect("FontFile2 /Length1");
|
|
assert!(
|
|
length1 < crate::pdf::full_face_size(crate::render::FontFace::Roman),
|
|
"subset {length1} should be smaller than the full face {}",
|
|
crate::pdf::full_face_size(crate::render::FontFace::Roman)
|
|
);
|
|
assert!(text.contains("/Filter /FlateDecode"));
|
|
}
|
|
|
|
#[test]
|
|
fn pdf_embeds_only_the_used_faces() {
|
|
let document = Document::new(400, vec![Unit::paragraph(1, "roman only")]);
|
|
let engine = Engine::layout(&document);
|
|
let list = engine.pages()[0].display_list();
|
|
let pdf = crate::pdf::display_list_to_pdf(&list, 400 * 65_536);
|
|
let text = String::from_utf8_lossy(&pdf);
|
|
assert_eq!(text.matches("/Subtype /Type0").count(), 1);
|
|
assert!(pdf.len() < 60_000, "{}", pdf.len());
|
|
assert!(!text.contains("/BaseFont /LiberationSerif-Bold"));
|
|
assert!(!text.contains("/BaseFont /LiberationMono"));
|
|
}
|
|
|
|
#[test]
|
|
fn sans_paragraph_paints_with_the_sans_face() {
|
|
let unit = Unit::paragraph_with_face(1, "sans face", ParagraphFont::Sans);
|
|
let page = Page {
|
|
items: unit.items,
|
|
insertions: Vec::new(),
|
|
marks: Vec::new(),
|
|
floats: Vec::new(),
|
|
sources: Vec::new(),
|
|
hash: 0,
|
|
};
|
|
let svg = page.display_list().to_svg();
|
|
assert!(svg.contains("font-family=\"sans-serif\""));
|
|
}
|
|
|
|
#[test]
|
|
fn mono_paragraph_paints_with_a_mono_face() {
|
|
let unit = Unit::paragraph_with_face(1, "code 123", ParagraphFont::Mono);
|
|
let page = Page {
|
|
items: unit.items,
|
|
insertions: Vec::new(),
|
|
marks: Vec::new(),
|
|
floats: Vec::new(),
|
|
sources: Vec::new(),
|
|
hash: 0,
|
|
};
|
|
let svg = page.display_list().to_svg();
|
|
assert!(svg.contains("font-family=\"monospace\""));
|
|
}
|
|
|
|
#[test]
|
|
fn bold_paragraph_paints_with_a_bold_face() {
|
|
let document = Document::new(
|
|
2_000_000,
|
|
vec![Unit::paragraph_with_face(1, "bold", ParagraphFont::Bold)],
|
|
);
|
|
let layout = Engine::layout(&document);
|
|
let list = layout.pages()[0].display_list();
|
|
assert!(list.items.iter().any(|item| matches!(
|
|
item,
|
|
crate::render::DisplayItem::Text {
|
|
font: crate::render::FontFace::Bold,
|
|
..
|
|
}
|
|
)));
|
|
}
|
|
|
|
#[test]
|
|
fn italic_paragraph_paints_with_an_italic_face() {
|
|
let document = Document::new(
|
|
2_000_000,
|
|
vec![Unit::paragraph_with_face(
|
|
1,
|
|
"italic",
|
|
ParagraphFont::Italic,
|
|
)],
|
|
);
|
|
let layout = Engine::layout(&document);
|
|
let list = layout.pages()[0].display_list();
|
|
assert!(list.items.iter().any(|item| matches!(
|
|
item,
|
|
crate::render::DisplayItem::Text {
|
|
font: crate::render::FontFace::Italic,
|
|
..
|
|
}
|
|
)));
|
|
}
|
|
|
|
#[test]
|
|
fn italic_paragraph_pdf_uses_the_italic_resource() {
|
|
let document = Document::new(
|
|
2_000_000,
|
|
vec![Unit::paragraph_with_face(
|
|
1,
|
|
"italic",
|
|
ParagraphFont::Italic,
|
|
)],
|
|
);
|
|
let layout = Engine::layout(&document);
|
|
let list = layout.pages()[0].display_list();
|
|
let pdf = crate::pdf::display_list_to_pdf(&list, 400 * 65_536);
|
|
let text = String::from_utf8_lossy(&pdf);
|
|
assert!(text.contains("/BaseFont /LiberationSerif-Italic"));
|
|
assert!(text.contains("BT /F3"));
|
|
}
|
|
#[test]
|
|
fn pdf_writer_uses_a_bold_font_resource() {
|
|
let mut list = crate::render::DisplayList::default();
|
|
list.push(crate::render::DisplayItem::Text {
|
|
x: 10,
|
|
y: 20,
|
|
size: 10 * 65_536,
|
|
text: "bold".to_owned(),
|
|
font: crate::render::FontFace::Bold,
|
|
});
|
|
let pdf = crate::pdf::display_list_to_pdf(&list, 400 * 65_536);
|
|
let text = String::from_utf8_lossy(&pdf);
|
|
assert!(text.contains("/BaseFont /LiberationSerif-Bold"));
|
|
assert!(text.contains("/F2 "));
|
|
assert!(text.contains("/W ["));
|
|
assert!(text.contains("BT /F2"));
|
|
}
|
|
|
|
#[test]
|
|
fn svg_reflects_display_font_faces() {
|
|
let mut list = crate::render::DisplayList::default();
|
|
for (index, font) in [
|
|
crate::render::FontFace::Roman,
|
|
crate::render::FontFace::Bold,
|
|
crate::render::FontFace::Italic,
|
|
crate::render::FontFace::Mono,
|
|
]
|
|
.into_iter()
|
|
.enumerate()
|
|
{
|
|
list.push(crate::render::DisplayItem::Text {
|
|
x: 10,
|
|
y: 20 + index as i64 * 20,
|
|
size: 10 * 65_536,
|
|
text: format!("face{index}"),
|
|
font,
|
|
});
|
|
}
|
|
let svg = list.to_svg();
|
|
assert!(svg.contains("font-family=\"serif\">face0"));
|
|
assert!(svg.contains("font-weight=\"bold\">face1"));
|
|
assert!(svg.contains("font-style=\"italic\">face2"));
|
|
assert!(svg.contains("font-family=\"monospace\">face3"));
|
|
}
|
|
|
|
#[test]
|
|
fn binomial_is_painted_with_parentheses() {
|
|
let document = Document::new(
|
|
1000,
|
|
vec![Unit::math(
|
|
1,
|
|
crate::math::parse_math("\\binom{n}{k}"),
|
|
&Cmr10Metrics::default(),
|
|
)],
|
|
);
|
|
let engine = Engine::layout(&document);
|
|
let list = engine.pages()[0].display_list();
|
|
let texts: Vec<_> = list
|
|
.items
|
|
.iter()
|
|
.filter_map(|item| match item {
|
|
DisplayItem::Text { text, .. } => Some(text.as_str()),
|
|
_ => None,
|
|
})
|
|
.collect();
|
|
assert!(texts.contains(&"("));
|
|
assert!(texts.contains(&")"));
|
|
assert!(texts.contains(&"n"));
|
|
assert!(texts.contains(&"k"));
|
|
}
|
|
#[test]
|
|
fn sqrt_degree_is_painted_before_the_radical() {
|
|
let document = Document::new(
|
|
1000,
|
|
vec![Unit::math(
|
|
1,
|
|
crate::math::parse_math("\\sqrt[3]{x}"),
|
|
&Cmr10Metrics::default(),
|
|
)],
|
|
);
|
|
let engine = Engine::layout(&document);
|
|
let list = engine.pages()[0].display_list();
|
|
let texts: Vec<_> = list
|
|
.items
|
|
.iter()
|
|
.filter_map(|item| match item {
|
|
DisplayItem::Text { text, .. } => Some(text.as_str()),
|
|
_ => None,
|
|
})
|
|
.collect();
|
|
assert!(texts.contains(&"3"));
|
|
assert!(texts.contains(&"x"));
|
|
let degree_x = list
|
|
.items
|
|
.iter()
|
|
.find_map(|item| match item {
|
|
DisplayItem::Text { text, x, .. } if text == "3" => Some(*x),
|
|
_ => None,
|
|
})
|
|
.unwrap();
|
|
let radical_x = list
|
|
.items
|
|
.iter()
|
|
.find_map(|item| match item {
|
|
DisplayItem::Text { text, x, .. } if text == "√" => Some(*x),
|
|
_ => None,
|
|
})
|
|
.unwrap();
|
|
assert!(radical_x > degree_x);
|
|
}
|
|
#[test]
|
|
fn overbrace_paints_a_brace_bar() {
|
|
let document = Document::new(
|
|
1000,
|
|
vec![Unit::math(
|
|
1,
|
|
crate::math::parse_math("\\overbrace{x}"),
|
|
&Cmr10Metrics::default(),
|
|
)],
|
|
);
|
|
let engine = Engine::layout(&document);
|
|
let list = engine.pages()[0].display_list();
|
|
let rules = list
|
|
.items
|
|
.iter()
|
|
.filter(|item| matches!(item, DisplayItem::Rule { .. }))
|
|
.count();
|
|
assert!(
|
|
rules >= 3,
|
|
"expected a brace bar and two ticks, got {rules}"
|
|
);
|
|
}
|
|
#[test]
|
|
fn display_list_paints_limits_above_and_below() {
|
|
let document = Document::new(
|
|
1000,
|
|
vec![Unit::math(
|
|
1,
|
|
crate::math::parse_math("\\sum_{i=1}^{n}"),
|
|
&Cmr10Metrics::default(),
|
|
)],
|
|
);
|
|
let engine = Engine::layout(&document);
|
|
let list = engine.pages()[0].display_list();
|
|
let texts = list
|
|
.items
|
|
.iter()
|
|
.filter(|item| matches!(item, DisplayItem::Text { .. }))
|
|
.count();
|
|
assert!(texts >= 4, "expected sum plus both limits, got {texts}");
|
|
}
|
|
#[test]
|
|
fn math_display_list_paints_symbols_and_fraction_rule() {
|
|
let atom = crate::math::parse_math("x + \\frac{a}{b}");
|
|
let document = Document::new(
|
|
400,
|
|
vec![Unit::math(1, atom, &crate::cmr10::Cmr10Metrics::new())],
|
|
);
|
|
let engine = Engine::layout(&document);
|
|
let list = engine.pages()[0].display_list();
|
|
let text = list
|
|
.items
|
|
.iter()
|
|
.filter(|item| matches!(item, DisplayItem::Text { .. }))
|
|
.count();
|
|
let rules = list
|
|
.items
|
|
.iter()
|
|
.filter(|item| matches!(item, DisplayItem::Rule { .. }))
|
|
.count();
|
|
assert!(text >= 4, "expected math glyphs, got {text}");
|
|
assert!(rules >= 1, "expected a fraction rule");
|
|
let svg = list.to_svg();
|
|
assert!(svg.contains(">x</text>"));
|
|
}
|
|
|
|
#[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</text>"));
|
|
assert!(svg.contains(">w</text>"));
|
|
}
|
|
|
|
#[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</text>"));
|
|
assert!(svg.contains("<rect"));
|
|
}
|
|
|
|
#[test]
|
|
fn paragraph_skip_separates_paragraph_units() {
|
|
let mut document = Document::new(
|
|
1,
|
|
vec![Unit::paragraph(1, "alpha"), Unit::paragraph(2, "beta")],
|
|
);
|
|
let first = item_height(&document.units[0].items[0]);
|
|
let second = item_height(&document.units[1].items[0]);
|
|
document.par_skip = 10;
|
|
document.page_goal = first + second + 10;
|
|
assert_eq!(Engine::layout(&document).pages().len(), 1);
|
|
document.page_goal = first + second + 9;
|
|
assert_eq!(Engine::layout(&document).pages().len(), 2);
|
|
}
|
|
|
|
#[test]
|
|
fn paragraphs_split_at_line_boundaries_across_pages() {
|
|
let lines: Vec<Vec<crate::paragraph::HorizontalItem>> =
|
|
(0..10).map(|_| Vec::new()).collect();
|
|
let paragraph = Paragraph {
|
|
lines,
|
|
height: 100,
|
|
width: 50,
|
|
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<usize> = 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<i64> = 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<i64> = 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<i64> = 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<i64> = 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<i64> = page
|
|
.display_list_with_layout(1000, document.text_float_sep)
|
|
.items
|
|
.iter()
|
|
.filter_map(|item| match item {
|
|
DisplayItem::Rule { y, height: 10, .. } => Some(*y),
|
|
_ => None,
|
|
})
|
|
.collect();
|
|
assert_eq!(
|
|
ys,
|
|
vec![130, 140],
|
|
"the late float reserves one textfloatsep"
|
|
);
|
|
}
|
|
|
|
#[test]
|
|
fn incremental_layout_honours_text_float_sep() {
|
|
let mut document = Document::new(
|
|
1000,
|
|
vec![
|
|
Unit::float(1, FloatPlacement::Top, 100, 100),
|
|
Unit::paragraph(2, "body"),
|
|
],
|
|
);
|
|
document.top_skip = 0;
|
|
document.text_float_sep = 30;
|
|
let mut engine = Engine::layout(&document);
|
|
fn body_y(engine: &Engine) -> i64 {
|
|
engine.pages()[0]
|
|
.display_list_with_layout(1000, 30)
|
|
.items
|
|
.iter()
|
|
.filter_map(|item| match item {
|
|
DisplayItem::Text { y, text, .. } if text == "b" => Some(*y),
|
|
_ => None,
|
|
})
|
|
.min()
|
|
.expect("body glyph")
|
|
}
|
|
let initial = body_y(&engine);
|
|
assert!(initial >= 130, "body starts below the reserved separation");
|
|
engine.edit(&document, 2, "changed body");
|
|
assert!(body_y(&engine) >= 130);
|
|
}
|
|
|
|
#[test]
|
|
fn float_height_covers_its_content() {
|
|
let unit = Unit::float_with_content(
|
|
1,
|
|
FloatPlacement::Top,
|
|
100,
|
|
5,
|
|
vec![VerticalItem::Rule {
|
|
width: 100,
|
|
height: 30,
|
|
}],
|
|
);
|
|
let VerticalItem::Float(float) = &unit.items[0] else {
|
|
panic!("expected float");
|
|
};
|
|
assert_eq!(float.height, 30);
|
|
assert_eq!(float.content_height(), 30);
|
|
}
|
|
#[test]
|
|
fn float_carries_vertical_content() {
|
|
let unit = Unit::float_with_content(
|
|
1,
|
|
FloatPlacement::Top,
|
|
100,
|
|
20,
|
|
vec![VerticalItem::Rule {
|
|
width: 100,
|
|
height: 2,
|
|
}],
|
|
);
|
|
let VerticalItem::Float(float) = &unit.items[0] else {
|
|
panic!("expected float");
|
|
};
|
|
assert_eq!(float.content.len(), 1);
|
|
let encoded = serde_json::to_string(float).unwrap();
|
|
let decoded: Float = serde_json::from_str(&encoded).unwrap();
|
|
assert_eq!(decoded.content.len(), 1);
|
|
}
|
|
#[test]
|
|
fn mark_and_float_constructors_build_page_items() {
|
|
let mut document = Document::new(
|
|
100,
|
|
vec![
|
|
Unit::mark(1, 0, "Intro"),
|
|
Unit::float(2, FloatPlacement::Top, 50, 20),
|
|
Unit::vertical(
|
|
3,
|
|
vec![VerticalItem::Box(VerticalBox {
|
|
width: 100,
|
|
height: 50,
|
|
})],
|
|
),
|
|
],
|
|
);
|
|
document.text_float_sep = 0;
|
|
let engine = Engine::layout(&document);
|
|
assert_eq!(engine.pages().len(), 1);
|
|
assert_eq!(engine.pages()[0].marks[0].text, "Intro");
|
|
assert_eq!(engine.pages()[0].floats.len(), 1);
|
|
}
|
|
#[test]
|
|
fn forced_penalty_between_boxes_starts_a_page() {
|
|
let block = |id| {
|
|
Unit::vertical(
|
|
id,
|
|
vec![VerticalItem::Box(VerticalBox {
|
|
width: 100,
|
|
height: 30,
|
|
})],
|
|
)
|
|
};
|
|
let document = Document::new(100, vec![block(1), Unit::penalty(2, -10_000), block(3)]);
|
|
let engine = Engine::layout(&document);
|
|
assert_eq!(engine.pages().len(), 2);
|
|
}
|
|
#[test]
|
|
fn vskip_consumes_vertical_space() {
|
|
let block = |id| {
|
|
Unit::vertical(
|
|
id,
|
|
vec![VerticalItem::Box(VerticalBox {
|
|
width: 100,
|
|
height: 30,
|
|
})],
|
|
)
|
|
};
|
|
let document = Document::new(50, vec![block(1), Unit::vskip(2, 10), block(3)]);
|
|
let engine = Engine::layout(&document);
|
|
assert_eq!(engine.pages().len(), 2);
|
|
}
|
|
#[test]
|
|
fn vertical_rules_consume_page_height() {
|
|
let unit = Unit::rule(1, 100, 60);
|
|
let document = Document::new(100, vec![unit]);
|
|
let engine = Engine::layout(&document);
|
|
assert_eq!(engine.pages().len(), 1);
|
|
|
|
let unit = Unit::rule(2, 100, 60);
|
|
let document = Document::new(100, vec![unit.clone(), unit]);
|
|
let engine = Engine::layout(&document);
|
|
assert_eq!(engine.pages().len(), 2);
|
|
}
|
|
|
|
#[test]
|
|
fn halign_skips_noalign_material() {
|
|
let unit = Unit::halign_from_source(1, r"A & B \\ \noalign{\vskip 4pt} C & D", 2, 10);
|
|
let VerticalItem::Halign(table) = &unit.items[0] else {
|
|
panic!("expected halign")
|
|
};
|
|
assert_eq!(table.rows.len(), 2);
|
|
assert_eq!(table.rows[1].cells[0].text, "C");
|
|
}
|
|
|
|
#[test]
|
|
fn halign_template_centers_and_right_aligns_cells() {
|
|
let unit = Unit::halign_from_source_with_template(1, "lcr", r"A & B & C", 10);
|
|
let VerticalItem::Halign(halign) = &unit.items[0] else {
|
|
panic!("expected halign");
|
|
};
|
|
assert_eq!(halign.rows[0].cells[1].alignment, CellAlignment::Center);
|
|
assert_eq!(halign.rows[0].cells[2].alignment, CellAlignment::Right);
|
|
}
|
|
#[test]
|
|
fn halign_source_parses_hline_rules() {
|
|
let unit = Unit::halign_from_source(1, r"A & B \\ \hline C & D", 2, 10);
|
|
let VerticalItem::Halign(halign) = &unit.items[0] else {
|
|
panic!("expected halign");
|
|
};
|
|
assert!(halign.rows.iter().any(|row| row.rule));
|
|
assert_eq!(halign.rows.last().unwrap().cells.len(), 2);
|
|
}
|
|
#[test]
|
|
fn halign_source_parses_omit_span_and_multispan() {
|
|
let unit = Unit::halign_from_source(1, r"A & B \\ \omit C & \multispan{2} D", 3, 10);
|
|
let VerticalItem::Halign(halign) = &unit.items[0] else {
|
|
panic!("expected halign");
|
|
};
|
|
assert_eq!(halign.rows.len(), 2);
|
|
assert_eq!(halign.rows[1].cells[0].text, "C");
|
|
assert_eq!(halign.rows[1].cells[0].span, 1);
|
|
assert_eq!(halign.rows[1].cells[1].span, 2);
|
|
}
|
|
#[test]
|
|
fn halign_computes_natural_column_widths() {
|
|
let rows = vec![
|
|
HalignRow {
|
|
cells: vec![
|
|
HalignCell {
|
|
text: "A".to_owned(),
|
|
span: 1,
|
|
alignment: CellAlignment::Left,
|
|
},
|
|
HalignCell {
|
|
text: "B".to_owned(),
|
|
span: 1,
|
|
alignment: CellAlignment::Left,
|
|
},
|
|
],
|
|
rule: false,
|
|
},
|
|
HalignRow {
|
|
cells: vec![
|
|
HalignCell {
|
|
text: "longword".to_owned(),
|
|
span: 1,
|
|
alignment: CellAlignment::Left,
|
|
},
|
|
HalignCell {
|
|
text: "C".to_owned(),
|
|
span: 1,
|
|
alignment: CellAlignment::Right,
|
|
},
|
|
],
|
|
rule: true,
|
|
},
|
|
HalignRow {
|
|
cells: vec![HalignCell {
|
|
text: "TOTAL".to_owned(),
|
|
span: 2,
|
|
alignment: CellAlignment::Center,
|
|
}],
|
|
rule: false,
|
|
},
|
|
];
|
|
let unit = Unit::halign(0, rows, 2, 20);
|
|
let VerticalItem::Halign(halign) = &unit.items[0] else {
|
|
panic!("expected a halign item");
|
|
};
|
|
assert_eq!(halign.column_widths, vec![5242880, 655360]);
|
|
assert_eq!(halign.width, 7208960);
|
|
assert_eq!(halign.height, 1_599_078);
|
|
}
|
|
|
|
#[test]
|
|
fn halign_splits_at_row_boundaries() {
|
|
let rows = vec![
|
|
HalignRow {
|
|
cells: vec![HalignCell {
|
|
text: "A".to_owned(),
|
|
span: 1,
|
|
alignment: CellAlignment::Left,
|
|
}],
|
|
rule: false,
|
|
},
|
|
HalignRow {
|
|
cells: vec![HalignCell {
|
|
text: "B".to_owned(),
|
|
span: 1,
|
|
alignment: CellAlignment::Left,
|
|
}],
|
|
rule: false,
|
|
},
|
|
HalignRow {
|
|
cells: vec![HalignCell {
|
|
text: "C".to_owned(),
|
|
span: 1,
|
|
alignment: CellAlignment::Left,
|
|
}],
|
|
rule: false,
|
|
},
|
|
];
|
|
let unit = Unit::halign(0, rows, 1, 0);
|
|
let VerticalItem::Halign(halign) = &unit.items[0] else {
|
|
panic!("expected halign");
|
|
};
|
|
let chunks = halign.split_for_height(1_700_000);
|
|
assert_eq!(chunks.len(), 2);
|
|
assert_eq!(chunks[0].rows.len(), 2);
|
|
assert_eq!(chunks[1].rows.len(), 1);
|
|
assert_eq!(chunks[0].height, 2 * halign.line_height);
|
|
assert_eq!(chunks[1].height, halign.line_height);
|
|
}
|
|
|
|
#[test]
|
|
fn tall_halign_splits_across_pages() {
|
|
let rows = vec![
|
|
HalignRow {
|
|
cells: vec![HalignCell {
|
|
text: "A".to_owned(),
|
|
span: 1,
|
|
alignment: CellAlignment::Left,
|
|
}],
|
|
rule: false,
|
|
},
|
|
HalignRow {
|
|
cells: vec![HalignCell {
|
|
text: "B".to_owned(),
|
|
span: 1,
|
|
alignment: CellAlignment::Left,
|
|
}],
|
|
rule: false,
|
|
},
|
|
HalignRow {
|
|
cells: vec![HalignCell {
|
|
text: "C".to_owned(),
|
|
span: 1,
|
|
alignment: CellAlignment::Left,
|
|
}],
|
|
rule: false,
|
|
},
|
|
];
|
|
let document = Document::new(2_000_000, vec![Unit::halign(0, rows, 1, 0)]);
|
|
let layout = Engine::layout(&document);
|
|
assert_eq!(layout.pages().len(), 2);
|
|
assert_eq!(layout.pages()[0].items.len(), 1);
|
|
assert_eq!(layout.pages()[1].items.len(), 1);
|
|
}
|
|
#[test]
|
|
fn checkpoint_round_trips_through_serde() {
|
|
let engine = Engine::layout(&document());
|
|
let encoded = serde_json::to_string(engine.checkpoints()).unwrap();
|
|
let decoded: Vec<Checkpoint> = 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<i64> = 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,
|
|
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::<Vec<_>>()
|
|
};
|
|
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<i64> = 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,
|
|
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 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,
|
|
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 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);
|
|
assert_eq!(layout.pages()[0].items.len(), 1);
|
|
assert_eq!(layout.pages()[1].floats.len(), 1);
|
|
assert_eq!(
|
|
layout.pages()[1].floats[0].placement,
|
|
FloatPlacement::Bottom
|
|
);
|
|
}
|
|
|
|
#[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_defers_a_late_top_float() {
|
|
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");
|
|
assert_eq!(layout.pages().len(), 2);
|
|
assert!(layout.pages()[0].floats.is_empty());
|
|
assert_eq!(layout.pages()[1].floats.len(), 1);
|
|
assert_eq!(layout.pages()[1].items.len(), 1);
|
|
}
|
|
|
|
#[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)))
|
|
);
|
|
}
|
|
}
|