From fb33ac63277c95aca55ea28278873d9fa8a276d7 Mon Sep 17 00:00:00 2001 From: gloamxun Date: Fri, 23 Oct 2026 01:51:19 +0800 Subject: [PATCH] Apply the insertion count multiplier to page space --- README.md | 2 +- crates/texrra-tex-core/src/lib.rs | 155 +++++++++++++++++++++++++++--- docs/ROUTE_D_PLAN.md | 9 +- docs/TEX_CORE.md | 7 +- 4 files changed, 153 insertions(+), 20 deletions(-) diff --git a/README.md b/README.md index c62abdd..da8c011 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. `page::PageBuilder` selects page breaks by TeX's badness-plus-penalty cost, including glue setting, `\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, 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. +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 `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, 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, and `InsertionClass::multiplier` applies TeX's `\count` reserve factor; `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 7cfed89..46bd068 100644 --- a/crates/texrra-tex-core/src/lib.rs +++ b/crates/texrra-tex-core/src/lib.rs @@ -548,6 +548,15 @@ pub struct InsertionClass { /// `None` falls back to `Document::insertion_skip`. #[serde(default)] pub skip: Option, + /// TeX's `\count` 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)] @@ -667,6 +676,17 @@ impl Document { } } + /// Page space reserved by `height` of insertion material in `class`, + /// after applying TeX's `\count` 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 @@ -1124,7 +1144,9 @@ impl Engine { .saturating_sub(document.top_skip) .saturating_sub(gap) .max(1); - if insertion_height + insertion.height > capacity + if insertion_height + + document.insertion_reserve(insertion.class, insertion.height) + > capacity && (!current.items.is_empty() || !current.insertions.is_empty()) { pages.push(std::mem::replace(&mut current, Page::empty())); @@ -1144,10 +1166,13 @@ impl Engine { .insertions .iter() .filter(|entry| entry.class == insertion.class) - .map(|entry| entry.height) + .map(|entry| document.insertion_reserve(entry.class, entry.height)) .sum(); - if (class_height + insertion.height > class_limit - || insertion.height > class_limit) + if (class_height + + document.insertion_reserve(insertion.class, insertion.height) + > class_limit + || document.insertion_reserve(insertion.class, insertion.height) + > class_limit) && !insertion.items.is_empty() { if !current.items.is_empty() || !current.insertions.is_empty() { @@ -1160,13 +1185,18 @@ impl Engine { let mut chunk_gap = gap; for sub_item in &insertion.items { let sub_height = item_height(sub_item); - if chunk_height + sub_height > class_limit && !chunk.is_empty() { + if document + .insertion_reserve(insertion.class, chunk_height + sub_height) + > class_limit + && !chunk.is_empty() + { current.insertions.push(Insertion { class: insertion.class, height: chunk_height, items: std::mem::take(&mut chunk), }); - insertion_height = chunk_gap + chunk_height; + insertion_height = chunk_gap + + document.insertion_reserve(insertion.class, chunk_height); chunk_height = 0; pages.push(std::mem::replace(&mut current, Page::empty())); used = document.top_skip; @@ -1181,19 +1211,27 @@ impl Engine { height: chunk_height, items: chunk, }); - insertion_height = chunk_gap + chunk_height; + insertion_height = chunk_gap + + document.insertion_reserve(insertion.class, chunk_height); } } else { let goal = document.page_goal - insertion_height; if (!current.items.is_empty() || !current.insertions.is_empty()) - && (used + gap + insertion.height > goal - || class_height + insertion.height > class_limit) + && (used + + gap + + document.insertion_reserve(insertion.class, insertion.height) + > goal + || class_height + + document + .insertion_reserve(insertion.class, insertion.height) + > class_limit) { pages.push(std::mem::replace(&mut current, Page::empty())); used = document.top_skip; insertion_height = 0; } - insertion_height += gap + insertion.height; + insertion_height += + gap + document.insertion_reserve(insertion.class, insertion.height); current.insertions.push(insertion.clone()); } } @@ -1737,17 +1775,25 @@ impl Engine { .insertions .iter() .filter(|entry| entry.class == insertion.class) - .map(|entry| entry.height) + .map(|entry| next.insertion_reserve(entry.class, entry.height)) .sum(); - let exceeds = class_height + insertion.height > class_limit - || insertion_height + insertion.height > capacity - || used + gap + insertion.height > next.page_goal; + let exceeds = class_height + + next.insertion_reserve(insertion.class, insertion.height) + > class_limit + || insertion_height + + next.insertion_reserve(insertion.class, insertion.height) + > capacity + || used + + gap + + next.insertion_reserve(insertion.class, insertion.height) + > next.page_goal; if exceeds && !current.items.is_empty() { pages.push(std::mem::replace(&mut current, Page::empty())); used = next.top_skip; insertion_height = 0; } - insertion_height += gap + insertion.height; + insertion_height += + gap + next.insertion_reserve(insertion.class, insertion.height); current.insertions.push(insertion.clone()); } VerticalItem::Mark(mark) => { @@ -2320,6 +2366,7 @@ mod tests { fraction_percent: 30, max_height: None, skip: None, + multiplier: 1000, }]; let layout = Engine::layout(&document); assert_eq!(layout.pages().len(), 2); @@ -2347,12 +2394,14 @@ mod tests { 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); @@ -2379,6 +2428,7 @@ mod tests { fraction_percent: 100, max_height: Some(150), skip: None, + multiplier: 1000, }]; let layout = Engine::layout(&document); assert_eq!(layout.pages().len(), 2); @@ -2507,6 +2557,34 @@ mod tests { assert!(engine.changed_pages().iter().all(|page| *page >= 1)); } + #[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 { @@ -2526,6 +2604,7 @@ mod tests { fraction_percent: 30, max_height: None, skip: None, + multiplier: 1000, }]; let mut engine = Engine::layout(&document); assert_eq!(engine.pages().len(), 2); @@ -2555,6 +2634,7 @@ mod tests { fraction_percent: 100, max_height: None, skip: Some(50), + multiplier: 1000, }]; let layout = Engine::layout(&document); assert_eq!(layout.pages().len(), 2); @@ -2589,6 +2669,7 @@ mod tests { fraction_percent: 100, max_height: None, skip: Some(50), + multiplier: 1000, }]; let mut engine = Engine::layout(&document); assert_eq!(engine.pages().len(), 2); @@ -2615,6 +2696,7 @@ mod tests { fraction_percent: 100, max_height: None, skip: None, + multiplier: 1000, }]; assert_eq!(Engine::layout(&document).pages().len(), 1); @@ -2647,6 +2729,7 @@ mod tests { fraction_percent: 100, max_height: None, skip: None, + multiplier: 1000, }]; assert_eq!(Engine::layout(&exact).pages().len(), 1); } @@ -4373,6 +4456,48 @@ mod tests { assert!(engine.pages().iter().all(|page| page.hash != 0)); } + #[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 { diff --git a/docs/ROUTE_D_PLAN.md b/docs/ROUTE_D_PLAN.md index 87de4dd..bd4904e 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`). 313 workspace tests are green and no oracle +PDF opt-in with `?engine=route-d`). 315 workspace tests are green and no oracle fixture is ignored. Known gaps, in dependency order: @@ -67,7 +67,8 @@ Known gaps, in dependency order: `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 +3. `\insert` classes model `\count`/`\dimen`/`\skip` but are not TeX + registers addressed by number, and there is still no interpreted output routine; 4. `\halign` handles spans/omit/templates but not the full TeX column algorithm; 5. math is a compact subset without the CM math fonts (`cmmi`, `cmsy`, `cmex`), @@ -229,7 +230,9 @@ Scope: `\pageshrink`, `\pagedepth`; - marks: `\mark`, `\botmark`, `\firstmark`, `\topmark`, `\marks`; - insertions: `\insert` with `\count`, `\dimen`, `\skip` per class, split - insertions, held-over material, `\footins` defaults; + insertions, held-over material, `\footins` defaults (the three registers are + now modelled by `InsertionClass::multiplier`, `max_height` and `skip`; TeX's + register arithmetic and held-over bookkeeping remain); - output: `\output` as an interpreted token list, `\box255`, `\shipout`, `\outputpenalty`, `\deadcycles`, page display list assembly; - floats: TeX-compatible policy module used by the default output routine diff --git a/docs/TEX_CORE.md b/docs/TEX_CORE.md index 93cca0a..a32ef90 100755 --- a/docs/TEX_CORE.md +++ b/docs/TEX_CORE.md @@ -208,6 +208,11 @@ oracle fixture is ignored. `Document::insertion_skip` models TeX's `\skip\footins` and is reserved once before the first insertion class on a page; it defaults to zero, and `InsertionClass::skip` overrides it for a single insertion class. + `InsertionClass::multiplier` models `\count` in thousandths: the page + space a class reserves is `height * multiplier / 1000`, so 2000 makes a 30pt + insertion cost 60pt of page height. `max_height` is the `\dimen` + absolute cap. Full layout, incremental replay and the item-boundary splitter + all use the same reserved height. Insertions taller than a page are split at item boundaries across pages. - Page breaking handles vertical boxes/glue, `Document::top_skip` and forced vertical penalties (`penalty <= -10000`); positive penalties are recorded @@ -307,7 +312,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 202 unit tests plus six route-D integration tests and eight oracle fixtures. Workspace verification: `cargo fmt --all -- --check`; `cargo test --workspace --offline` runs 313 tests (202 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 204 unit tests plus six route-D integration tests and eight oracle fixtures. Workspace verification: `cargo fmt --all -- --check`; `cargo test --workspace --offline` runs 315 tests (204 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