From 9599982b91fa3dc317726a54a92af47aa5b76068 Mon Sep 17 00:00:00 2001 From: gloamxun Date: Fri, 23 Oct 2026 01:45:45 +0800 Subject: [PATCH] Feed simple documents through the TeX page builder --- README.md | 2 +- crates/texrra-tex-core/src/lib.rs | 173 ++++++++++++++++++++++++++++++ docs/ROUTE_D_PLAN.md | 20 ++-- docs/TEX_CORE.md | 17 +-- 4 files changed, 195 insertions(+), 17 deletions(-) diff --git a/README.md b/README.md index 817043e..1c310c0 100644 --- a/README.md +++ b/README.md @@ -583,7 +583,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. Interline spacing follows TeX (`\baselineskip` unless `\lineskiplimit` forces `\lineskip`), and `Document::par_skip` adds `\parskip` between paragraph units. A standalone `page::PageBuilder` already selects page breaks by TeX's badness-plus-penalty cost, including glue setting, `\topskip` and `\maxdepth`; it is covered by unit tests and will replace the scrolling builder next. 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::insertion_classes` caps each insertion class to a page fraction and defers overflow to the next page; `Document::insertion_skip` models `\skip\footins` once per page before the first insertion class, and `InsertionClass::skip` overrides it for one class. The v1 `/preview` and project APIs are unchanged and remain the default. +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. 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, `\topskip` and `\maxdepth`; `Engine::layout_paged` exposes it for documents whose units are single vertical items, while the scrolling builder remains the default until floats, insertions and incremental replay gain paged equivalents. 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::insertion_classes` caps each insertion class to a page fraction and defers overflow to the next page; `Document::insertion_skip` models `\skip\footins` once per page before the first insertion class, and `InsertionClass::skip` overrides it for one class. The v1 `/preview` and project APIs are unchanged and remain the default. Project previews can opt into the new core with `POST /api/projects/{id}/preview?engine=route-d`; the same project preview without the query keeps the v1 pipeline. The web client exposes this as the `引擎: v1` / `引擎: Route-D` toggle in the preview toolbar; the choice is stored in `localStorage` and switches both the preview request and `POST /api/projects/{id}/pdf`, since the PDF handler honors the same `engine=route-d` query. Route-D project previews keep a session, so an unchanged source reports zero recomputed pages; text edits and structural edits with an unchanged paragraph prefix rebuild from the first difference through `Engine::relayout_from`, reusing the sealed pages before it, while edits without a reusable prefix fall back to a full layout. `POST /api/route-d/edit/{unit}` applies one paragraph edit to the last route-D document and returns the same page list plus `changedPages` and diff --git a/crates/texrra-tex-core/src/lib.rs b/crates/texrra-tex-core/src/lib.rs index 15d8399..fe80029 100644 --- a/crates/texrra-tex-core/src/lib.rs +++ b/crates/texrra-tex-core/src/lib.rs @@ -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> { + 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 { + 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) { 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()); + } } diff --git a/docs/ROUTE_D_PLAN.md b/docs/ROUTE_D_PLAN.md index c3a1639..e0db8e4 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`). 301 workspace tests are green and no oracle +PDF opt-in with `?engine=route-d`). 311 workspace tests are green and no oracle fixture is ignored. Known gaps, in dependency order: @@ -62,10 +62,11 @@ Known gaps, in dependency order: glue), but not yet custom `\sfcode` overrides, generic `fil`/`fill` glue orders or `\prevgraf`; 2. the page builder used by `Document` is still the scrolling builder with - fraction policies; `page::PageBuilder` now implements the candidate-breakpoint - cost model (badness + penalty, glue setting, `\topskip`, `\maxdepth`) with - unit tests, but it is not yet wired into `Document` and an interpreted - `\output` is absent; + fraction 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 single-item units, but + floats, insertions and incremental checkpoint replay still use the scrolling + builder, and an interpreted `\output` is absent; 3. `\insert` classes are data structures, not TeX registers and an output routine; 4. `\halign` handles spans/omit/templates but not the full TeX column algorithm; @@ -240,9 +241,12 @@ marks) and chooses each page at the cheapest feasible breakpoint, scoring badness from the page goal and accumulated glue, adding the break penalty, and applying `\topskip` to the first box and `\maxdepth` to the page depth. Seven unit tests cover overfull avoidance, exact glue filling, forced penalties, -penalty-driven earlier breaks, `\topskip`, `\maxdepth` and marks. Wiring this -builder into `Document` and replacing the scrolling path is the next step, -followed by `\voffset`, insertion registers and the interpreted `\output`. +penalty-driven earlier breaks, `\topskip`, `\maxdepth` and marks. +`Engine::layout_paged` now feeds it every document whose units are single +vertical items and materialises the chosen fragments as hashed pages; floats, +insertions and checkpoint replay still fall back to the scrolling builder, which +stays the default until it has a paged equivalent. Next: port those paths, then +`\voffset`, insertion registers and the interpreted `\output`. Acceptance: 10 page fixtures (article text, footnotes, floats, forced breaks); page counts identical and first/last baselines within 1pt of pdfLaTeX. diff --git a/docs/TEX_CORE.md b/docs/TEX_CORE.md index 6bc6d8e..51cd329 100755 --- a/docs/TEX_CORE.md +++ b/docs/TEX_CORE.md @@ -110,7 +110,7 @@ and justification. | --- | --- | --- | | M0 | vertical list, page builder, checkpoint, page hash, edit demo | edit on page 2 rebuilds only page 2 | | M1 | TeX box/glue/penalty + paragraph builder (`\par`, `\hsize`, `\parindent`) | **partial**: item stream, CMR10 metrics, TeX Live en-US hyphenation, TeX demerits and tolerance passes, `\hangindent`/`\parshape`, `\parfillskip`, sentence spacing, `\looseness`, `\baselineskip`/`\lineskip`/`\parskip` interline glue, pdfLaTeX oracle matrix 100-240pt plus register, geometry and vertical-glue fixtures; custom `\sfcode`, generic fil glue and `\prevgraf` next | -| M2 | page builder + `\output`, `\vsize`, `\topskip`, footnotes, floats | **partial**: `\vsize` page goal, `\topskip`, forced penalties, `Insertion` reserve, running `Mark`s, `OutputRoutine` hook, top/bottom `Float` placement; `page::PageBuilder` now scores candidate breakpoints with TeX page badness, glue setting, `\topskip`/`\maxdepth`, but is not yet wired into `Document`; interpreted `\output` next | +| M2 | page builder + `\output`, `\vsize`, `\topskip`, footnotes, floats | **partial**: `\vsize` page goal, `\topskip`, forced penalties, `Insertion` reserve, running `Mark`s, `OutputRoutine` hook, top/bottom `Float` placement; `page::PageBuilder` scores candidate breakpoints with TeX page badness, glue setting, `\topskip`/`\maxdepth`, and `Engine::layout_paged` uses it for documents whose units are single vertical items, while the scrolling builder remains the default; interpreted `\output` next | | M3 | `\halign`, `\omit`, `\span`, `\multispan`, booktabs/longtable | **partial**: source parsing, natural column widths, spans, rule rows, 10pt display-list painting and row-level page splitting; no booktabs/longtable parity yet | | M4 | math lists, scripts, fractions, radicals, accents, delimiters | **partial**: token parser, atom boxes with CMR10 metrics, delimiter scaling, accents and a display-list painter; no CMEX size variants or TeX math spacing classes yet | | M5 | NFSS/TFM metrics, CM/Latin Modern | same line/page breaks as reference | @@ -270,7 +270,7 @@ for a later overlaid slash. | --- | --- | --- | | M0 checkpoint engine | done | page list, page hashes, snapshot/restore, edit replay | | M1 horizontal/paragraphs | partial | boxes/glue/penalties, CMR10 metrics, TeX Live en-US hyphenation, TeX demerits and tolerance passes, `\hangindent`/`\parshape`, `\parfillskip`, sentence spacing (`\sfcode`/`\frenchspacing`), `\baselineskip`/`\lineskip`/`\parskip` interline glue, pdfTeX oracle matrix 100-240pt plus register, geometry and vertical-glue fixtures | -| M2 vertical/page builder | partial | vsize, topskip, insertions, marks, Rust output hook, top/bottom floats, float-page/text fractions, rules, vskip, penalties; `page::PageBuilder` scores breakpoints with page badness and penalties and models `\topskip`/`\maxdepth`, but the document builder still uses the scrolling path; interpreted `\output` absent | +| M2 vertical/page builder | partial | vsize, topskip, insertions, marks, Rust output hook, top/bottom floats, float-page/text fractions, rules, vskip, penalties; `page::PageBuilder` scores breakpoints with page badness and penalties and models `\topskip`/`\maxdepth`; `Engine::layout_paged` builds pages through it for single-item documents, while floats, insertions and incremental replay still use the scrolling path; interpreted `\output` absent | | M3 halign | partial | natural columns, spans, omit, hline rows, templates, noalign skip, rules; no PDF painter | | M4 math | partial | atoms, scripts, fractions, roots, delimiters, accents, operators, classes, braces, boxed, negated; no math painter/shrink wrapping | | M5 NFSS/TFM | partial | runtime `cmr10.tfm` widths/heights/depths/kern pairs and ff/fi/fl/ffi/ffl ligatures; text faces embed Liberation Serif/Mono as Type0 CID fonts with Identity-H, ToUnicode and width arrays; used faces embed per-document TrueType glyf subsets that keep the original glyph IDs, include composite components, and carry a matching ToUnicode CMap; ASCII documents use the compact tier; no Base-14 dependency; SVG carries family/weight/style | @@ -299,7 +299,7 @@ M5 (partial): display-list text carries `FontFace::{Roman,Bold,Italic,BoldItalic M6 (partial): `DisplayItem::Image` becomes a PDF XObject; `DisplayItem::Link` becomes `/Annots /Subtype /Link /URI`; `DisplayItem::Special` injects raw content-stream operators. SVG previews show images as grey rectangles and specials as comments. -M2 (partial): `Page::display_list_with_goal(page_goal)` places insertion material at `page_goal - insertion_height`, adds a 0.4pt separator above footnotes, splits oversized insertions at item boundaries, and paints top/bottom floats from their vertical `content` at the page edges; empty floats keep a dimension rectangle. Floats also size themselves from content, respect `text_fraction_percent`, respect `top_fraction_percent` (TeX `\topfraction`, default 70%) and `bottom_fraction_percent` (TeX `\bottomfraction`, default 30%), and can take a dedicated float page. The incremental edit path applies the same float fractions, float number limits, insertion-class limits and per-class `skip` rules as full layout. `Document::float_sep` (TeX `\floatsep`, default 12pt) reserves a gap between stacked floats of the same placement in both paths. `Document::text_float_sep` (TeX `\textfloatsep`, default 20pt) reserves exactly one gap between the float block and the body text on a page that has both, again in both paths; `Page::display_list_with_layout(page_goal, text_float_sep)` applies the same gap when rendering, while `display_list_with_goal` stays gap-free for callers that do not know the document settings. Float material at the top of a page starts at the top margin: `\topskip` is consumed only by body text, matching TeX float pages. `FloatPlacement::Here` models `[h]` floats: they keep their place in the body flow with `Document::in_text_sep` (TeX `\intextsep`, default 12pt) above and below, move to the next page when they do not fit, and count against `\totalnumber`. The page stores the float's `gap_after` so the display list advances the flow by the same amount the builder reserved. A standalone `page::PageBuilder` implements TeX's candidate-breakpoint cost model (page badness from accumulated glue stretch/shrink plus break penalties, `\topskip` for the first box, `\maxdepth` depth shifting) with seven unit tests; migrating `Document` onto it is the next P2 step. +M2 (partial): `Page::display_list_with_goal(page_goal)` places insertion material at `page_goal - insertion_height`, adds a 0.4pt separator above footnotes, splits oversized insertions at item boundaries, and paints top/bottom floats from their vertical `content` at the page edges; empty floats keep a dimension rectangle. Floats also size themselves from content, respect `text_fraction_percent`, respect `top_fraction_percent` (TeX `\topfraction`, default 70%) and `bottom_fraction_percent` (TeX `\bottomfraction`, default 30%), and can take a dedicated float page. The incremental edit path applies the same float fractions, float number limits, insertion-class limits and per-class `skip` rules as full layout. `Document::float_sep` (TeX `\floatsep`, default 12pt) reserves a gap between stacked floats of the same placement in both paths. `Document::text_float_sep` (TeX `\textfloatsep`, default 20pt) reserves exactly one gap between the float block and the body text on a page that has both, again in both paths; `Page::display_list_with_layout(page_goal, text_float_sep)` applies the same gap when rendering, while `display_list_with_goal` stays gap-free for callers that do not know the document settings. Float material at the top of a page starts at the top margin: `\topskip` is consumed only by body text, matching TeX float pages. `FloatPlacement::Here` models `[h]` floats: they keep their place in the body flow with `Document::in_text_sep` (TeX `\intextsep`, default 12pt) above and below, move to the next page when they do not fit, and count against `\totalnumber`. The page stores the float's `gap_after` so the display list advances the flow by the same amount the builder reserved. A standalone `page::PageBuilder` implements TeX's candidate-breakpoint cost model (page badness from accumulated glue stretch/shrink plus break penalties, `\topskip` for the first box, `\maxdepth` depth shifting) with seven unit tests. `Engine::layout_paged` now builds pages through it for documents whose units are single vertical items (boxes, rules, paragraphs, math, haligns, glue, penalties and marks); floats, insertions and the incremental checkpoint replay still use the scrolling builder, which remains the default until those pieces have a paged equivalent. M3 (partial): `Unit::halign` normalizes column widths, intercolumn gaps, row heights and cell text widths to scaled points; the painter uses 10pt glyphs in 12pt rows. Rules and spans are painted; tall tables split at row boundaries (`Halign::split_for_height`) with column widths preserved. @@ -307,7 +307,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 190 unit tests plus six route-D integration tests and eight oracle fixtures. Workspace verification: `cargo fmt --all -- --check`; `cargo test --workspace --offline` runs 301 tests (190 route-D unit, 6 route-D integration, 8 oracle, 71 v1 integration, 19 server, 4 v1 unit, 1 core unit, 2 binary units), with none ignored. v1 remains the live server path. +The crate currently has 200 unit tests plus six route-D integration tests and eight oracle fixtures. Workspace verification: `cargo fmt --all -- --check`; `cargo test --workspace --offline` runs 311 tests (200 route-D unit, 6 route-D integration, 8 oracle, 71 v1 integration, 19 server, 4 v1 unit, 1 core unit, 2 binary units), with none ignored. v1 remains the live server path. ### M0 incremental demo @@ -343,10 +343,11 @@ deliberately open rather than approximated: are modelled. - **M2**: the scrolling builder still drives `Document`; `page::PageBuilder` implements TeX's candidate-breakpoint cost (badness + penalty, glue - stretch/shrink, `\topskip`, `\maxdepth`) and is covered by unit tests, but - migrating `Document` onto it, `\voffset`, insertion registers - (`\count`/`\dimen`/`\skip` per class) and an interpreted `\output` remain - open. + stretch/shrink, `\topskip`, `\maxdepth`) and `Engine::layout_paged` runs it + for simple documents, but floats, insertions and incremental replay need a + paged equivalent before it can become the default; `\voffset`, insertion + registers (`\count`/`\dimen`/`\skip` per class) and an interpreted + `\output` remain open. - **M5**: `cmr10.tfm` is parsed at runtime with widths, glyph heights/depths and kern pairs. only used text faces embed Liberation Serif/Mono as Type0/Identity-H; each face is subset to the glyphs actually used (composite components included, glyph IDs retained); FontFile2 and ToUnicode streams use Flate compression; the ToUnicode CMap follows the used characters; ff/fi/fl/ffi/ffl ligatures come from TFM, and CMR10 italic corrections are applied at line ends; full NFSS family switching is not implemented. - **M6**: `\output`, `\insert`, mark/float output policies, class-file execution and math limit policies are only partially modeled; `OutputRoutine::wants_break` can force a page break between units, and insertion material is stacked by class from the page bottom; `\output` is still Rust code rather than interpreted tokens.