Route route-D page breaking through the paged builder

This commit is contained in:
gloamxun committed 2026-10-23 15:02:52 +08:00
1 parent 08a312be82
commit 6b3145fd09
6 files changed
+112 -25

No files matched your search

+1 -1
View File
@@ -589,7 +589,7 @@ execution, service and incrementality targets) is in
The first M7 service integration is available as `POST /api/route-d/preview`, with PDF export at `POST /api/route-d/pdf`. The first M7 service integration is available as `POST /api/route-d/preview`, with PDF export at `POST /api/route-d/pdf`.
It accepts blank-line-separated source with a small `\section`/`\textbf`/`\emph`/display-math/list subset, lays it out with the route-D page It accepts blank-line-separated source with a small `\section`/`\textbf`/`\emph`/display-math/list subset, lays it out with the route-D page
builder, and returns the v1-compatible preview shape plus per-page hashes and builder, and returns the v1-compatible preview shape plus per-page hashes and
SVG. Route-D paragraphs are laid out with CMR10 advances, kerns and ligatures; runs of two or three hyphens become en/em dashes, the breaker follows TeX's `\pretolerance`/`\tolerance`/`\emergencystretch` passes with demerits (falling back to TeX's overfull fill when no feasible break exists), and the PDF `/W` array reports the same advances, so extracted text keeps word boundaries. Non-final lines bake their justification into the glue widths, so the PDF and the SVG preview are flush to the measure instead of showing natural spaces; with `\raggedright` (`ParagraphStyle::ragged_right`) lines keep their natural widths and fill greedily, because `\rightskip` carries an infinite `fil`. Interline spacing follows TeX (`\baselineskip` unless `\lineskiplimit` forces `\lineskip`), and `Document::par_skip` adds `\parskip` between paragraph units. `page::PageBuilder` selects page breaks by TeX's badness-plus-penalty cost, including glue setting with TeX orders (normal/`\vfil`/`\vfill`/`\vfilll`), `\topskip` and `Document::max_depth` (`\maxdepth`), and breaks ties toward the page closest to the goal; `Engine::layout_paged` exposes it for documents whose units are single vertical items; insertion classes are placed through the same builder, with per-class limits, held-over material and `Document::split_top_skip` (`\splittopskip`, default 10pt) at the top of each continuation, while the scrolling builder remains the default until bottom/in-text floats gain a paged equivalent; paged layouts replay edits from the edited page, falling back to a full rebuild when insertions or an `\output` routine are present. `Document::output_routine` runs an interpreted `\output` program (`\shipout\box255`, `\relax`, `\message`, `\ifdim`, `\ifnum` and `\ifodd` over page registers; `\pageno`, `\outputpenalty` and `\deadcycles` are readable, and each page fragment records the penalty that broke it and how much stretch each glue order carries, so `\pagefilstretch`, `\pagefillstretch` and `\pagefilllstretch` are readable) over those paged fragments, so a routine can drop pages it does not ship, or ship only the pages it wants based on the break penalty or page number. Embedded text fonts are subset per document to the glyphs actually used (retaining glyph IDs and composite components), and each subset carries a ToUnicode CMap covering its used characters. `Document::h_offset` and `v_offset` (`\hoffset`/`\voffset`) shift the exported SVG. Route-D paragraphs are laid out with CMR10 advances, kerns and ligatures; runs of two or three hyphens become en/em dashes, the breaker follows TeX's `\pretolerance`/`\tolerance`/`\emergencystretch` passes with demerits (falling back to TeX's overfull fill when no feasible break exists), and the PDF `/W` array reports the same advances, so extracted text keeps word boundaries. Non-final lines bake their justification into the glue widths, so the PDF and the SVG preview are flush to the measure instead of showing natural spaces; with `\raggedright` (`ParagraphStyle::ragged_right`) lines keep their natural widths and fill greedily, because `\rightskip` carries an infinite `fil`. Interline spacing follows TeX (`\baselineskip` unless `\lineskiplimit` forces `\lineskip`), and `Document::par_skip` adds `\parskip` between paragraph units. `page::PageBuilder` selects page breaks by TeX's badness-plus-penalty cost, including glue setting with TeX orders (normal/`\vfil`/`\vfill`/`\vfilll`), `\topskip` and `Document::max_depth` (`\maxdepth`), and breaks ties toward the page closest to the goal; `Engine::layout_paged` exposes it for documents of box/glue/penalty/mark/float/insertion units, expanding each paragraph into one node per line with a zero-width interline breakpoint, and route-D previews and PDFs run through it; insertion classes are placed through the same builder, with per-class limits, held-over material and `Document::split_top_skip` (`\splittopskip`, default 10pt) at the top of each continuation, while `Engine::layout` keeps the scrolling builder as the non-paged fallback; paged layouts replay edits from the edited page, falling back to a full rebuild when insertions or an `\output` routine are present. `Document::output_routine` runs an interpreted `\output` program (`\shipout\box255`, `\relax`, `\message`, `\ifdim`, `\ifnum` and `\ifodd` over page registers; `\pageno`, `\outputpenalty` and `\deadcycles` are readable, and each page fragment records the penalty that broke it and how much stretch each glue order carries, so `\pagefilstretch`, `\pagefillstretch` and `\pagefilllstretch` are readable) over those paged fragments, so a routine can drop pages it does not ship, or ship only the pages it wants based on the break penalty or page number. Embedded text fonts are subset per document to the glyphs actually used (retaining glyph IDs and composite components), and each subset carries a ToUnicode CMap covering its used characters. `Document::h_offset` and `v_offset` (`\hoffset`/`\voffset`) shift the exported
page body through `pdf::PageOrigin`, leaving the sheet size unchanged, while page body through `pdf::PageOrigin`, leaving the sheet size unchanged, while
`Document::paper_width`/`paper_height` (`\paperwidth`/`\paperheight`, default US `Document::paper_width`/`paper_height` (`\paperwidth`/`\paperheight`, default US
Letter) set the MediaBox and the preview page box; the route-D endpoints read Letter) set the MediaBox and the preview page box; the route-D endpoints read
+77 -2
View File
@@ -867,8 +867,11 @@ fn source_hash(source: &str) -> u64 {
/// Units made of box/glue/penalty/mark material can be expressed as /// Units made of box/glue/penalty/mark material can be expressed as
/// page-builder nodes today (a unit may contribute several nodes and be /// page-builder nodes today (a unit may contribute several nodes and be
/// split across pages); insertion classes become [`VerticalNode::Insertion`] /// split across pages); insertion classes become [`VerticalNode::Insertion`]
/// reservations. Floats return `None`, leaving the scrolling builder in /// reservations and floats become top, bottom or in-text nodes. A paragraph
/// charge. /// 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( fn document_nodes(
document: &Document, document: &Document,
) -> Option<(Vec<VerticalNode>, Vec<usize>, Vec<VerticalItem>)> { ) -> Option<(Vec<VerticalNode>, Vec<usize>, Vec<VerticalItem>)> {
@@ -905,6 +908,41 @@ fn document_nodes(
document.par_skip_shrink, 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 { let node = match item {
VerticalItem::Box(vertical_box) => VerticalNode::Box { VerticalItem::Box(vertical_box) => VerticalNode::Box {
height: vertical_box.height, height: vertical_box.height,
@@ -2427,7 +2465,9 @@ impl Engine {
/// long as the prefix is unchanged. /// long as the prefix is unchanged.
pub fn relayout_from(&mut self, document: &Document, start_index: usize) { pub fn relayout_from(&mut self, document: &Document, start_index: usize) {
if self.layout.checkpoints.is_empty() { if self.layout.checkpoints.is_empty() {
if !self.relayout_paged_incremental(document, start_index) {
self.replace_with_paged(document); self.replace_with_paged(document);
}
return; return;
} }
if start_index == 0 || start_index >= self.layout.checkpoints.len() { if start_index == 0 || start_index >= self.layout.checkpoints.len() {
@@ -5692,6 +5732,41 @@ mod tests {
assert!(engine.pages().iter().all(|page| page.hash != 0)); 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] #[test]
fn fill_glue_absorbs_the_page_set() { fn fill_glue_absorbs_the_page_set() {
let mut document = Document::new( let mut document = Document::new(
+8 -6
View File
@@ -48,7 +48,7 @@ floats (`\floatsep`, `\textfloatsep`, `\intextsep`, `\topfraction`,
`\bottomnumber`, `\totalnumber`), insertion classes (`\skip`, fraction and `\bottomnumber`, `\totalnumber`), insertion classes (`\skip`, fraction and
absolute limits, splitting), marks, Rust output hook, multi-page PDF, and the absolute limits, splitting), marks, Rust output hook, multi-page PDF, and the
route-D service endpoints (`/api/route-d/preview|pdf|edit`, project preview and route-D service endpoints (`/api/route-d/preview|pdf|edit`, project preview and
PDF opt-in with `?engine=route-d`). 449 workspace tests are green and no oracle PDF opt-in with `?engine=route-d`). 450 workspace tests are green and no oracle
fixture is ignored. fixture is ignored.
Known gaps, in dependency order: Known gaps, in dependency order:
@@ -67,11 +67,13 @@ source-level `\hyphenation{...}` exceptions and `\parshape` measures,
`\raggedright` (infinite `\rightskip` fil), explicit `\raggedright` (infinite `\rightskip` fil), explicit
`\hfil`/`\hfill` glue orders, and `\prevgraf` visibility in the output `\hfil`/`\hfill` glue orders, and `\prevgraf` visibility in the output
routine; routine;
2. the default builder is still the scrolling builder with fraction 2. the scrolling builder remains the non-paged fallback with fraction float
policies, now with line-level paragraph splits; `page::PageBuilder` policies; `page::PageBuilder` implements the candidate-breakpoint cost
implements the candidate-breakpoint cost model (badness + penalty, glue model (badness + penalty, glue setting, `\topskip`, `\maxdepth`) and
setting, `\topskip`, `\maxdepth`) and `Engine::layout_paged` runs it for `Engine::layout_paged` runs it for documents made of
documents made of box/glue/penalty/mark units, insertion classes box/glue/penalty/mark/float/insertion units, with paragraphs expanded to
one node per line so pages break inside them; route-D previews and PDFs
use the paged builder when the document is expressible, insertion classes
(per-class limits with held-over material) and top and bottom floats (per-class limits with held-over material) and top and bottom floats
(`\textfloatsep` above the body, `\floatsep` between stacked bottom (`\textfloatsep` above the body, `\floatsep` between stacked bottom
floats, `\bottomfraction` cap); in-text floats flow inline, so every floats, `\bottomfraction` cap); in-text floats flow inline, so every
+11 -7
View File
@@ -156,10 +156,13 @@ and justification.
Interline glue follows TeX: each baseline advances by `\baselineskip` when Interline glue follows TeX: each baseline advances by `\baselineskip` when
the resulting gap clears `\lineskiplimit`, otherwise by `\lineskip`; the resulting gap clears `\lineskiplimit`, otherwise by `\lineskip`;
`\parskip` is appended between paragraph units in the vertical list. When a `\parskip` is appended between paragraph units in the vertical list. When a
paragraph does not fit on the page, the scrolling builder splits it at line paragraph does not fit on the page it is split at line boundaries
boundaries (`Paragraph::split_at`): the fragment keeps its baseline grid on (`Paragraph::split_at`): the fragment keeps its baseline grid on the next
the next page, `\parskip` is not charged inside the paragraph, and only a page, `\parskip` is not charged inside the paragraph, and only a single
single unsplittable line is allowed to overflow at the top of a page. unsplittable line is allowed to overflow at the top of a page. The scrolling
builder splits paragraphs directly; for the paged builder each paragraph
becomes one node per line joined by zero-width interline glue, so its page
breaks also land between lines with the same overflowing-line rule.
Remaining gaps are generic `fil`/`fill` glue orders outside Remaining gaps are generic `fil`/`fill` glue orders outside
`\parfillskip` and `\prevgraf`. `\parfillskip` and `\prevgraf`.
@@ -358,7 +361,7 @@ Math coverage includes fractions/roots, scripts, `\left...\right` with body-scal
Paragraph units carry a `ParagraphFont`; `Unit::paragraph_with_face` and `Unit::paragraph_with_style_and_face` select Roman, bold, italic, mono, or sans. The corresponding Computer Modern TFM (`cmr10`, `cmbx10`, `cmti10`, `cmbxti10`, `cmtt10`, `cmss10`) supplies advances, kerns, ligatures, and italic correction for layout, while the display list and PDF select the matching Liberation face. `Engine::edit` preserves the face when reflowing an edited paragraph. Paragraph units carry a `ParagraphFont`; `Unit::paragraph_with_face` and `Unit::paragraph_with_style_and_face` select Roman, bold, italic, mono, or sans. The corresponding Computer Modern TFM (`cmr10`, `cmbx10`, `cmti10`, `cmbxti10`, `cmtt10`, `cmss10`) supplies advances, kerns, ligatures, and italic correction for layout, while the display list and PDF select the matching Liberation face. `Engine::edit` preserves the face when reflowing an edited paragraph.
The crate currently has 297 unit tests plus seven route-D integration tests and thirty oracle fixtures. Workspace verification: `cargo fmt --all -- --check`; `cargo test --workspace --offline` runs 449 tests (297 route-D unit, 7 route-D integration, 30 oracle, 71 v1 integration, 26 server, 4 v1 unit, 1 core unit, 12 binary units), with none ignored. v1 remains the live server path. The crate currently has 298 unit tests plus seven route-D integration tests and thirty oracle fixtures. Workspace verification: `cargo fmt --all -- --check`; `cargo test --workspace --offline` runs 450 tests (298 route-D unit, 7 route-D integration, 30 oracle, 71 v1 integration, 26 server, 4 v1 unit, 1 core unit, 13 binary units), with none ignored. v1 remains the live server path.
### M0 incremental demo ### M0 incremental demo
@@ -393,8 +396,9 @@ deliberately open rather than approximated:
interline glue, the default `\sfcode`/`\frenchspacing` sentence spacing, interline glue, the default `\sfcode`/`\frenchspacing` sentence spacing,
explicit `\spaceskip`/`\xspaceskip`, stretch and shrink on the explicit `\spaceskip`/`\xspaceskip`, stretch and shrink on the
inter-paragraph `\parskip` glue, and `\raggedright` (infinite `\rightskip` fil) are modelled. inter-paragraph `\parskip` glue, and `\raggedright` (infinite `\rightskip` fil) are modelled.
- **M2**: the scrolling builder still drives `Document`; `page::PageBuilder` - **M2**: `Engine::layout` keeps the scrolling builder as the non-paged
implements TeX's candidate-breakpoint cost (badness + penalty, glue fallback, while route-D previews and PDFs run `Engine::layout_paged`;
`page::PageBuilder` implements TeX's candidate-breakpoint cost (badness + penalty, glue
stretch/shrink, `\topskip`, `\maxdepth`); a break at glue is only legal stretch/shrink, `\topskip`, `\maxdepth`); a break at glue is only legal
when it follows a non-discardable item, so glue after glue is not a when it follows a non-discardable item, so glue after glue is not a
breakpoint and the glue at a break is discarded and `Engine::layout_paged` runs it breakpoint and the glue at a break is discarded and `Engine::layout_paged` runs it
+13 -7
View File
@@ -68,20 +68,20 @@ pub fn project_preview_json(project_id: &str, source: &str) -> Result<String, St
let recomputed = session.engine.recomputed_pages(); let recomputed = session.engine.recomputed_pages();
(session.engine, changed, recomputed) (session.engine, changed, recomputed)
} else { } else {
let engine = Engine::layout(&document); let engine = layout_document(&document);
let changed: Vec<usize> = (0..engine.pages().len()).collect(); let changed: Vec<usize> = (0..engine.pages().len()).collect();
let recomputed = changed.len(); let recomputed = changed.len();
(engine, changed, recomputed) (engine, changed, recomputed)
} }
} else { } else {
let engine = Engine::layout(&document); let engine = layout_document(&document);
let changed: Vec<usize> = (0..engine.pages().len()).collect(); let changed: Vec<usize> = (0..engine.pages().len()).collect();
let recomputed = changed.len(); let recomputed = changed.len();
(engine, changed, recomputed) (engine, changed, recomputed)
} }
} }
_ => { _ => {
let engine = Engine::layout(&document); let engine = layout_document(&document);
let changed: Vec<usize> = (0..engine.pages().len()).collect(); let changed: Vec<usize> = (0..engine.pages().len()).collect();
let recomputed = changed.len(); let recomputed = changed.len();
(engine, changed, recomputed) (engine, changed, recomputed)
@@ -439,13 +439,19 @@ fn parse_dimension(text: &str) -> Option<i64> {
Some((number * factor * 65_536.0).round() as i64) Some((number * factor * 65_536.0).round() as i64)
} }
/// Lay a document out with the TeX page builder, falling back to the
/// scrolling builder for material the paged builder cannot express.
fn layout_document(document: &Document) -> Engine {
Engine::layout_paged(document).unwrap_or_else(|| Engine::layout(document))
}
/// Build a JSON preview from blank-line-separated plain-text paragraphs. /// Build a JSON preview from blank-line-separated plain-text paragraphs.
pub fn preview_json(source: &str) -> Result<String, String> { pub fn preview_json(source: &str) -> Result<String, String> {
let (body, geometry) = geometry_and_body(source); let (body, geometry) = geometry_and_body(source);
let paragraphs = paragraphs(&body)?; let paragraphs = paragraphs(&body)?;
let mut document = build_document(&paragraphs, &geometry); let mut document = build_document(&paragraphs, &geometry);
apply_geometry(&mut document, &geometry); apply_geometry(&mut document, &geometry);
let engine = Engine::layout(&document); let engine = layout_document(&document);
let json = render_json(&document, &engine, None); let json = render_json(&document, &engine, None);
// Keep the layout so a following `/edit` request can diff against it and // Keep the layout so a following `/edit` request can diff against it and
// reuse page checkpoints instead of starting from a no-op document. // reuse page checkpoints instead of starting from a no-op document.
@@ -461,7 +467,7 @@ pub fn pdf_bytes(source: &str) -> Result<Vec<u8>, String> {
let paragraphs = paragraphs(&body)?; let paragraphs = paragraphs(&body)?;
let mut document = build_document(&paragraphs, &geometry); let mut document = build_document(&paragraphs, &geometry);
apply_geometry(&mut document, &geometry); apply_geometry(&mut document, &geometry);
let engine = Engine::layout(&document); let engine = layout_document(&document);
let pages: Vec<_> = engine let pages: Vec<_> = engine
.pages() .pages()
.iter() .iter()
@@ -498,7 +504,7 @@ pub fn edit_json(source: &str, unit: usize) -> Result<String, String> {
let (_, mut engine) = match slot.take() { let (_, mut engine) = match slot.take() {
Some(session) => session, Some(session) => session,
None => { None => {
let engine = Engine::layout(&next); let engine = layout_document(&next);
(next.clone(), engine) (next.clone(), engine)
} }
}; };
@@ -1209,7 +1215,7 @@ mod source_tests {
assert!(parsed[1].page_break); assert!(parsed[1].page_break);
let document = build_document(&parsed, &PageGeometry::default()); let document = build_document(&parsed, &PageGeometry::default());
assert_eq!(document.page_breaks, vec![1]); assert_eq!(document.page_breaks, vec![1]);
let engine = Engine::layout(&document); let engine = layout_document(&document);
assert_eq!(engine.pages().len(), 2); assert_eq!(engine.pages().len(), 2);
assert!(engine.pages()[0].items.len() >= 1); assert!(engine.pages()[0].items.len() >= 1);
} }
+2 -2
View File
@@ -82,7 +82,7 @@ impl TestServer {
} }
fn wait_ready(&mut self) { fn wait_ready(&mut self) {
for _ in 0..600 { for _ in 0..1800 {
if let Ok(response) = send(self.port, "GET", "/", &[], "text/plain") { if let Ok(response) = send(self.port, "GET", "/", &[], "text/plain") {
if response.status == 200 { if response.status == 200 {
return; return;
@@ -98,7 +98,7 @@ impl TestServer {
std::thread::sleep(Duration::from_millis(50)); std::thread::sleep(Duration::from_millis(50));
} }
panic!( panic!(
"server on port {} did not become ready within 30s:\n{}", "server on port {} did not become ready within 90s:\n{}",
self.port, self.port,
self.log() self.log()
); );