From 6b3145fd097899cc50cb62e882bae05d5f259267 Mon Sep 17 00:00:00 2001 From: GloamXun Date: Fri, 23 Oct 2026 15:02:52 +0800 Subject: [PATCH] Route route-D page breaking through the paged builder --- README.md | 2 +- crates/texrra-tex-core/src/lib.rs | 81 +++++++++++++++++++++++++++++-- docs/ROUTE_D_PLAN.md | 14 +++--- docs/TEX_CORE.md | 18 ++++--- src/route_d.rs | 20 +++++--- tests/server.rs | 4 +- 6 files changed, 113 insertions(+), 26 deletions(-) diff --git a/README.md b/README.md index 217be4d..c82084a 100644 --- a/README.md +++ b/README.md @@ -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`. 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 -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 `Document::paper_width`/`paper_height` (`\paperwidth`/`\paperheight`, default US Letter) set the MediaBox and the preview page box; the route-D endpoints read diff --git a/crates/texrra-tex-core/src/lib.rs b/crates/texrra-tex-core/src/lib.rs index 46408c0..4af45ae 100644 --- a/crates/texrra-tex-core/src/lib.rs +++ b/crates/texrra-tex-core/src/lib.rs @@ -867,8 +867,11 @@ fn source_hash(source: &str) -> u64 { /// 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. Floats return `None`, leaving the scrolling builder in -/// charge. +/// reservations and floats become top, bottom or in-text nodes. A paragraph +/// expands to one node per line with a zero-width interline glue between +/// lines, which is the legal breakpoint that lets a page break inside it. +/// `None` means the document holds material the paged builder cannot express +/// yet. fn document_nodes( document: &Document, ) -> Option<(Vec, Vec, Vec)> { @@ -905,6 +908,41 @@ fn document_nodes( 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, @@ -2427,7 +2465,9 @@ impl Engine { /// 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); + if !self.relayout_paged_incremental(document, start_index) { + self.replace_with_paged(document); + } return; } 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)); } + #[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( diff --git a/docs/ROUTE_D_PLAN.md b/docs/ROUTE_D_PLAN.md index 7af3302..d90774f 100644 --- a/docs/ROUTE_D_PLAN.md +++ b/docs/ROUTE_D_PLAN.md @@ -48,7 +48,7 @@ floats (`\floatsep`, `\textfloatsep`, `\intextsep`, `\topfraction`, `\bottomnumber`, `\totalnumber`), insertion classes (`\skip`, fraction and 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 -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. Known gaps, in dependency order: @@ -67,11 +67,13 @@ source-level `\hyphenation{...}` exceptions and `\parshape` measures, `\raggedright` (infinite `\rightskip` fil), explicit `\hfil`/`\hfill` glue orders, and `\prevgraf` visibility in the output routine; -2. the default builder is still the scrolling builder with fraction - policies, now with line-level paragraph splits; `page::PageBuilder` - implements the candidate-breakpoint cost model (badness + penalty, glue - setting, `\topskip`, `\maxdepth`) and `Engine::layout_paged` runs it for - documents made of box/glue/penalty/mark units, insertion classes +2. the scrolling builder remains the non-paged fallback with fraction float + policies; `page::PageBuilder` implements the candidate-breakpoint cost + model (badness + penalty, glue setting, `\topskip`, `\maxdepth`) and + `Engine::layout_paged` runs it for documents made of + 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 (`\textfloatsep` above the body, `\floatsep` between stacked bottom floats, `\bottomfraction` cap); in-text floats flow inline, so every diff --git a/docs/TEX_CORE.md b/docs/TEX_CORE.md index ef0c3f7..a490ba4 100755 --- a/docs/TEX_CORE.md +++ b/docs/TEX_CORE.md @@ -156,10 +156,13 @@ and justification. Interline glue follows TeX: each baseline advances by `\baselineskip` when the resulting gap clears `\lineskiplimit`, otherwise by `\lineskip`; `\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 - boundaries (`Paragraph::split_at`): the fragment keeps its baseline grid on - the next page, `\parskip` is not charged inside the paragraph, and only a - single unsplittable line is allowed to overflow at the top of a page. + paragraph does not fit on the page it is split at line boundaries + (`Paragraph::split_at`): the fragment keeps its baseline grid on the next + page, `\parskip` is not charged inside the paragraph, and only a single + 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 `\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. -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 @@ -393,8 +396,9 @@ deliberately open rather than approximated: interline glue, the default `\sfcode`/`\frenchspacing` sentence spacing, explicit `\spaceskip`/`\xspaceskip`, stretch and shrink on the inter-paragraph `\parskip` glue, and `\raggedright` (infinite `\rightskip` fil) are modelled. -- **M2**: the scrolling builder still drives `Document`; `page::PageBuilder` - implements TeX's candidate-breakpoint cost (badness + penalty, glue +- **M2**: `Engine::layout` keeps the scrolling builder as the non-paged + 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 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 diff --git a/src/route_d.rs b/src/route_d.rs index 07d9d4b..d348510 100755 --- a/src/route_d.rs +++ b/src/route_d.rs @@ -68,20 +68,20 @@ pub fn project_preview_json(project_id: &str, source: &str) -> Result = (0..engine.pages().len()).collect(); let recomputed = changed.len(); (engine, changed, recomputed) } } else { - let engine = Engine::layout(&document); + let engine = layout_document(&document); let changed: Vec = (0..engine.pages().len()).collect(); let recomputed = changed.len(); (engine, changed, recomputed) } } _ => { - let engine = Engine::layout(&document); + let engine = layout_document(&document); let changed: Vec = (0..engine.pages().len()).collect(); let recomputed = changed.len(); (engine, changed, recomputed) @@ -439,13 +439,19 @@ fn parse_dimension(text: &str) -> Option { 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. pub fn preview_json(source: &str) -> Result { let (body, geometry) = geometry_and_body(source); let paragraphs = paragraphs(&body)?; let mut document = build_document(¶graphs, &geometry); apply_geometry(&mut document, &geometry); - let engine = Engine::layout(&document); + let engine = layout_document(&document); let json = render_json(&document, &engine, None); // Keep the layout so a following `/edit` request can diff against it and // reuse page checkpoints instead of starting from a no-op document. @@ -461,7 +467,7 @@ pub fn pdf_bytes(source: &str) -> Result, String> { let paragraphs = paragraphs(&body)?; let mut document = build_document(¶graphs, &geometry); apply_geometry(&mut document, &geometry); - let engine = Engine::layout(&document); + let engine = layout_document(&document); let pages: Vec<_> = engine .pages() .iter() @@ -498,7 +504,7 @@ pub fn edit_json(source: &str, unit: usize) -> Result { let (_, mut engine) = match slot.take() { Some(session) => session, None => { - let engine = Engine::layout(&next); + let engine = layout_document(&next); (next.clone(), engine) } }; @@ -1209,7 +1215,7 @@ mod source_tests { assert!(parsed[1].page_break); let document = build_document(&parsed, &PageGeometry::default()); assert_eq!(document.page_breaks, vec![1]); - let engine = Engine::layout(&document); + let engine = layout_document(&document); assert_eq!(engine.pages().len(), 2); assert!(engine.pages()[0].items.len() >= 1); } diff --git a/tests/server.rs b/tests/server.rs index 87d8d1d..fbab1ac 100644 --- a/tests/server.rs +++ b/tests/server.rs @@ -82,7 +82,7 @@ impl TestServer { } fn wait_ready(&mut self) { - for _ in 0..600 { + for _ in 0..1800 { if let Ok(response) = send(self.port, "GET", "/", &[], "text/plain") { if response.status == 200 { return; @@ -98,7 +98,7 @@ impl TestServer { std::thread::sleep(Duration::from_millis(50)); } panic!( - "server on port {} did not become ready within 30s:\n{}", + "server on port {} did not become ready within 90s:\n{}", self.port, self.log() );