Feed simple documents through the TeX page builder

This commit is contained in:
gloamxun committed 2026-10-23 01:45:45 +08:00
1 parent d4a9c6b4fd
commit 9599982b91
4 files changed
+195 -17

No files matched your search

+173
View File
@@ -8,6 +8,7 @@ mod subset;
pub mod tfm;
pub use cmr10::Cmr10Metrics;
use page::{PageBuilder, VerticalGlue, VerticalNode};
pub use paragraph::{
HorizontalBox, HorizontalItem, Paragraph, ParagraphFont, ParagraphStyle, layout_items,
layout_paragraph, layout_paragraph_with_font, text_items, text_items_with_font,
@@ -730,6 +731,47 @@ fn source_hash(source: &str) -> u64 {
hasher.finish()
}
/// Convert a document into the vertical list consumed by [`PageBuilder`].
///
/// Only single-item units can be expressed as page-builder nodes today, so
/// floats and insertions make this return `None` and keep the incremental
/// builder in charge.
fn document_nodes(document: &Document) -> Option<Vec<VerticalNode>> {
let mut nodes = Vec::with_capacity(document.units.len());
for unit in &document.units {
let [item] = unit.items.as_slice() else {
return None;
};
nodes.push(match item {
VerticalItem::Box(vertical_box) => VerticalNode::Box {
height: vertical_box.height,
depth: 0,
},
VerticalItem::Rule { height, .. } => VerticalNode::Box {
height: *height,
depth: 0,
},
VerticalItem::Math { height, depth, .. } => VerticalNode::Box {
height: *height,
depth: *depth,
},
VerticalItem::Paragraph(paragraph) => VerticalNode::Box {
height: paragraph.height,
depth: 0,
},
VerticalItem::Halign(halign) => VerticalNode::Box {
height: halign.height,
depth: 0,
},
VerticalItem::Glue(height) => VerticalNode::Glue(VerticalGlue::new(*height, 0, 0)),
VerticalItem::Penalty(value) => VerticalNode::Penalty(*value),
VerticalItem::Mark(mark) => VerticalNode::Mark(mark.clone()),
VerticalItem::Insertion(_) | VerticalItem::Float(_) => return None,
});
}
Some(nodes)
}
fn item_height(item: &VerticalItem) -> i64 {
match item {
VerticalItem::Box(vertical_box) => vertical_box.height,
@@ -1335,6 +1377,74 @@ impl Engine {
&self.layout.changed_pages
}
/// Lay out a document with TeX's page builder instead of the greedy
/// scrolling builder.
///
/// This is the staged P2 integration: it accepts documents whose units are
/// single vertical items (boxes, rules, paragraphs, math, haligns, glue,
/// penalties and marks). Floats and insertions still make it return `None`,
/// because their page interaction belongs to the incremental builder for
/// now.
pub fn layout_paged(document: &Document) -> Option<Self> {
let nodes = document_nodes(document)?;
let builder = PageBuilder {
page_goal: document.page_goal,
top_skip: document.top_skip,
max_depth: 0,
};
let mut pages = Vec::new();
for fragment in builder.build(&nodes) {
let mut items = Vec::new();
let mut marks = Vec::new();
let mut sources = Vec::new();
for unit in &document.units[fragment.start..fragment.end] {
let item = unit.items.first()?.clone();
if let VerticalItem::Mark(mark) = &item {
marks.push(mark.clone());
} else {
items.push(item);
}
sources.push((unit.id, source_hash(&unit.source)));
}
let mut page = Page::empty();
page.items = items;
page.marks = marks;
page.sources = sources;
page.seal_in_place();
pages.push(page);
}
let count = pages.len();
Some(Self {
layout: Layout {
pages,
checkpoints: Vec::new(),
recomputed_pages: 0,
changed_pages: (0..count).collect(),
},
})
}
/// Rebuild a paged layout wholesale and report which page hashes changed.
fn replace_with_paged(&mut self, document: &Document) {
let previous = std::mem::take(&mut self.layout.pages);
let mut layout = Self::layout_paged(document)
.unwrap_or_else(|| Self::layout(document))
.layout;
layout.changed_pages = layout
.pages
.iter()
.enumerate()
.filter(|(index, page)| {
previous
.get(*index)
.map_or(true, |old| old.hash != page.hash)
})
.map(|(index, _)| index)
.collect();
layout.recomputed_pages = layout.pages.len();
self.layout = layout;
}
pub fn edit(&mut self, document: &Document, unit_id: UnitId, source: impl Into<String>) {
let Some(unit_index) = document.units.iter().position(|unit| unit.id == unit_id) else {
self.layout = Self::layout(document).layout;
@@ -1357,6 +1467,10 @@ impl Engine {
})
.unwrap_or(ParagraphFont::Roman);
next.units[unit_index] = Unit::paragraph_with_style_and_face(unit_id, source, style, font);
if self.layout.checkpoints.is_empty() {
self.replace_with_paged(&next);
return;
}
self.relayout_from(&next, unit_index);
}
@@ -1365,6 +1479,10 @@ impl Engine {
/// callers may add, remove or replace units at and after `start_index` as
/// long as the prefix is unchanged.
pub fn relayout_from(&mut self, document: &Document, start_index: usize) {
if self.layout.checkpoints.is_empty() {
self.replace_with_paged(document);
return;
}
if start_index == 0 || start_index >= self.layout.checkpoints.len() {
self.layout = Self::layout(document).layout;
self.layout.recomputed_pages = self.layout.pages.len();
@@ -4231,4 +4349,59 @@ mod tests {
.unwrap();
assert_eq!(float_y, 0, "the float starts at the top margin");
}
#[test]
fn paged_layout_breaks_simple_vertical_lists() {
let document = Document::new(
100,
vec![
Unit::rule(1, 100, 60),
Unit::vskip(2, 0),
Unit::rule(3, 100, 60),
Unit::vskip(4, 0),
Unit::rule(5, 100, 60),
],
);
let engine = Engine::layout_paged(&document).expect("simple documents are page-buildable");
assert_eq!(engine.pages().len(), 3);
assert_eq!(engine.pages()[0].sources, vec![(1, source_hash(""))]);
assert!(engine.pages().iter().all(|page| page.hash != 0));
}
#[test]
fn paged_layout_refuses_floats_and_insertions() {
let floated = Document::new(100, vec![Unit::float(1, FloatPlacement::Top, 100, 20)]);
assert!(Engine::layout_paged(&floated).is_none());
let insertion = Document::new(100, vec![Unit::insertion(1, 0, 10, Vec::new())]);
assert!(Engine::layout_paged(&insertion).is_none());
}
#[test]
fn paged_layout_edit_relayouts_and_reports_changes() {
let style = ParagraphStyle {
line_width: 100 * 65_536,
line_height: 12 * 65_536,
..ParagraphStyle::default()
};
let document = Document::new(
20 * 65_536,
vec![
Unit::paragraph_with_style_and_face(
1,
"alpha beta",
style.clone(),
ParagraphFont::Roman,
),
Unit::vskip(2, 0),
Unit::paragraph_with_style_and_face(3, "gamma delta", style, ParagraphFont::Roman),
],
);
let mut engine = Engine::layout_paged(&document).expect("paragraphs are page-buildable");
assert_eq!(engine.pages().len(), 2);
let first = engine.pages()[0].hash;
engine.edit(&document, 3, "epsilon zeta");
assert_eq!(engine.pages()[0].hash, first);
assert!(engine.changed_pages().contains(&1));
assert_eq!(engine.recomputed_pages(), engine.pages().len());
}
}