diff --git a/README.md b/README.md index 0efe07e..dc6ec25 100644 --- a/README.md +++ b/README.md @@ -589,12 +589,12 @@ 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::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. 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, Insertion classes are placed through the same builder, with per-class limits and held-over material, while the scrolling builder remains the default until floats 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::h_offset` and `v_offset` (`\hoffset`/`\voffset`) shift the exported page body through `pdf::PageOrigin`, leaving the sheet size unchanged; the route-D PDF endpoint reads leading `\hoffset`/`\voffset` dimension assignments from the submitted source. Page marks collected by `\mark` are exposed through `Engine::top_mark`, `first_mark` and `bot_mark` with TeX's carry-forward rules. -`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. +`Document::insertion_classes` caps each insertion class to a page fraction and defers overflow to the next page (the paged builder applies the same limits and carries overflow onto dedicated pages), 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 7e7c6d8..3199b53 100644 --- a/crates/texrra-tex-core/src/lib.rs +++ b/crates/texrra-tex-core/src/lib.rs @@ -8,7 +8,9 @@ mod subset; pub mod tfm; pub use cmr10::Cmr10Metrics; -use page::{PageBuilder, VerticalGlue, VerticalNode}; +use std::collections::BTreeMap; + +use page::{InsertionLimit, 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, @@ -768,8 +770,9 @@ 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); floats and insertions return `None`, leaving the -/// scrolling builder in charge. +/// split across pages); insertion classes become [`VerticalNode::Insertion`] +/// reservations. Floats return `None`, leaving the scrolling builder in +/// charge. fn document_nodes( document: &Document, ) -> Option<(Vec, Vec, Vec)> { @@ -802,7 +805,11 @@ fn document_nodes( 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, + VerticalItem::Insertion(insertion) => VerticalNode::Insertion { + class: insertion.class, + height: document.insertion_reserve(insertion.class, insertion.height), + }, + VerticalItem::Float(_) => return None, }; nodes.push(node); owners.push(index); @@ -826,6 +833,60 @@ fn item_height(item: &VerticalItem) -> i64 { } } +/// Take the longest prefix of `items` whose reserved height fits `capacity`. +/// +/// Returns `(accepted, remainder, reserved_height)`. A single item larger than +/// the capacity is still accepted alone: TeX only splits insertion material at +/// item boundaries. +fn take_insertion_prefix( + document: &Document, + class: u8, + items: Vec, + capacity: i64, +) -> (Vec, Vec, i64) { + let mut accepted = Vec::new(); + let mut reserved = 0_i64; + let mut rest = items.into_iter(); + let mut remainder = Vec::new(); + while let Some(item) = rest.next() { + let reserve = document.insertion_reserve(class, item_height(&item)); + if reserved + reserve <= capacity { + accepted.push(item); + reserved += reserve; + continue; + } + if accepted.is_empty() { + reserved += reserve; + accepted.push(item); + } else { + remainder.push(item); + } + remainder.extend(rest); + break; + } + (accepted, remainder, reserved) +} + +fn attach_insertion( + insertions: &mut BTreeMap, + used: &mut BTreeMap, + class: u8, + accepted: Vec, + reserved: i64, +) { + if accepted.is_empty() && reserved == 0 { + return; + } + *used.entry(class).or_insert(0) += reserved; + let entry = insertions.entry(class).or_insert_with(|| Insertion { + class, + height: 0, + items: Vec::new(), + }); + entry.height += reserved; + entry.items.extend(accepted); +} + fn top_float_height(page: &Page) -> i64 { page.floats .iter() @@ -1562,41 +1623,105 @@ impl Engine { /// 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. + /// vertical items (boxes, rules, paragraphs, math, haligns, glue, penalties + /// and marks). Insertion classes are laid out here too, including material + /// held over past the class limit. Floats still make it return `None`, + /// because their placement belongs to the incremental builder for now. pub fn layout_paged(document: &Document) -> Option { let (nodes, owners, node_items) = document_nodes(document)?; let builder = PageBuilder { page_goal: document.page_goal, top_skip: document.top_skip, max_depth: document.max_depth, + insertion_limits: document + .insertion_classes + .iter() + .map(|class| InsertionLimit { + class: class.number, + height: document.insertion_class_limit(class.number), + }) + .collect(), }; let mut pages = Vec::new(); + let mut held: BTreeMap> = BTreeMap::new(); for fragment in builder.build(&nodes) { let mut items = Vec::new(); let mut marks = Vec::new(); let mut sources = Vec::new(); - for index in fragment.start..fragment.end { - let item = node_items[index].clone(); - if let VerticalItem::Mark(mark) = &item { - marks.push(mark.clone()); - } else { - items.push(item); + let mut insertions: BTreeMap = BTreeMap::new(); + let mut used: BTreeMap = BTreeMap::new(); + + // Material held over from the previous page fills its class first. + let held_classes: Vec = held.keys().copied().collect(); + for class in held_classes { + let material = held.remove(&class).unwrap_or_default(); + let limit = document.insertion_class_limit(class); + let capacity = (limit - used.get(&class).copied().unwrap_or(0)).max(0); + let (accepted, remainder, reserved) = + take_insertion_prefix(document, class, material, capacity); + attach_insertion(&mut insertions, &mut used, class, accepted, reserved); + if !remainder.is_empty() { + held.insert(class, remainder); } + } + + for index in fragment.start..fragment.end { + let item = &node_items[index]; let unit = &document.units[owners[index]]; if sources.last().map(|(id, _)| *id) != Some(unit.id) { sources.push((unit.id, source_hash(&unit.source))); } + match item { + VerticalItem::Mark(mark) => marks.push(mark.clone()), + VerticalItem::Insertion(insertion) => { + let class = insertion.class; + let limit = document.insertion_class_limit(class); + let capacity = (limit - used.get(&class).copied().unwrap_or(0)).max(0); + let (accepted, remainder, reserved) = take_insertion_prefix( + document, + class, + insertion.items.clone(), + capacity, + ); + attach_insertion(&mut insertions, &mut used, class, accepted, reserved); + if !remainder.is_empty() { + held.entry(class).or_default().extend(remainder); + } + } + other => items.push(other.clone()), + } } + let mut page = Page::empty(); page.items = items; page.marks = marks; + page.insertions = insertions.into_values().collect(); page.sources = sources; page.seal_in_place(); pages.push(page); } + + // Insertion material that did not fit its class limit on the page where + // it was raised is carried to dedicated pages, as TeX holds it over. + while !held.is_empty() { + let classes: Vec = held.keys().copied().collect(); + let mut insertions: BTreeMap = BTreeMap::new(); + let mut used: BTreeMap = BTreeMap::new(); + for class in classes { + let material = held.remove(&class).unwrap_or_default(); + let limit = document.insertion_class_limit(class); + let (accepted, remainder, reserved) = + take_insertion_prefix(document, class, material, limit); + attach_insertion(&mut insertions, &mut used, class, accepted, reserved); + if !remainder.is_empty() { + held.insert(class, remainder); + } + } + let mut page = Page::empty(); + page.insertions = insertions.into_values().collect(); + page.seal_in_place(); + pages.push(page); + } let count = pages.len(); Some(Self { layout: Layout { @@ -4847,11 +4972,71 @@ mod tests { } #[test] - fn paged_layout_refuses_floats_and_insertions() { + fn paged_layout_refuses_floats_but_places_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()); + + let insertion = Document::new( + 100, + vec![ + Unit::rule(1, 80, 20), + Unit::insertion( + 2, + 0, + 40, + vec![VerticalItem::Rule { + width: 80, + height: 40, + }], + ), + ], + ); + let layout = Engine::layout_paged(&insertion).expect("insertions are page-buildable"); + assert_eq!(layout.pages().len(), 1); + assert_eq!(layout.pages()[0].insertions.len(), 1); + assert_eq!(layout.pages()[0].insertions[0].height, 40); + assert_eq!(layout.pages()[0].insertions[0].items.len(), 1); + } + + #[test] + fn paged_layout_holds_over_insertion_material() { + let mut document = Document::new( + 100, + vec![ + Unit::rule(1, 80, 20), + Unit::insertion( + 2, + 0, + 80, + vec![ + VerticalItem::Rule { + width: 80, + height: 40, + }, + VerticalItem::Rule { + width: 80, + height: 40, + }, + ], + ), + Unit::rule(3, 80, 10), + ], + ); + document.insertion_classes = vec![InsertionClass { + number: 0, + fraction_percent: 50, + max_height: None, + skip: None, + multiplier: 1000, + }]; + let layout = Engine::layout_paged(&document).expect("insertions are page-buildable"); + assert_eq!(layout.pages().len(), 2); + assert_eq!(layout.pages()[0].insertions[0].items.len(), 1); + assert_eq!(layout.pages()[1].insertions[0].items.len(), 1); + // Body text keeps filling the page after a split insertion; the held + // over material gets a page of its own. + assert_eq!(layout.pages()[0].items.len(), 2); + assert!(layout.pages()[1].items.is_empty()); } #[test] diff --git a/crates/texrra-tex-core/src/page.rs b/crates/texrra-tex-core/src/page.rs index 121ca77..07c973b 100644 --- a/crates/texrra-tex-core/src/page.rs +++ b/crates/texrra-tex-core/src/page.rs @@ -7,6 +7,8 @@ //! insertion classes are still handled by the incremental builder in //! `Engine`; wiring this module into `Document` is the next P2 step. +use std::collections::BTreeMap; + use crate::Mark; /// Vertical glue with the stretch and shrink TeX uses to set a page. @@ -27,17 +29,40 @@ impl VerticalGlue { } } +/// Upper bound for one insertion class on a page (`\dimen` in TeX). +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub struct InsertionLimit { + pub class: u8, + pub height: i64, +} + +/// Space one insertion class occupies on a page. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub struct InsertionSpace { + pub class: u8, + pub height: i64, +} + /// Material that can appear in a vertical list handed to the page builder. #[derive(Clone, Debug, PartialEq, Eq)] pub enum VerticalNode { - Box { height: i64, depth: i64 }, + Box { + height: i64, + depth: i64, + }, Glue(VerticalGlue), Penalty(i64), Mark(Mark), + /// `\insert` material: reserved at the page bottom, capped by the + /// class limit; the remainder is held over to the next page. + Insertion { + class: u8, + height: i64, + }, } /// One page chosen by [`PageBuilder::build`]. -#[derive(Clone, Copy, Debug, PartialEq, Eq)] +#[derive(Clone, Debug, PartialEq, Eq)] pub struct PageFragment { /// Index of the first node that belongs to this page. pub start: usize, @@ -51,25 +76,31 @@ pub struct PageFragment { pub height: i64, /// Depth of the page box, capped at `max_depth`. pub depth: i64, + /// Accepted insertion space per class, including material held over from + /// the previous page. + pub insertions: Vec, } -#[derive(Clone, Copy, Debug)] +#[derive(Clone, Debug)] struct Candidate { cost: i64, badness: i64, height: i64, depth: i64, shrink: i64, + reserved: i64, end: usize, next: usize, } -/// TeX page builder parameters (`\vsize`, `\topskip`, `\maxdepth`). -#[derive(Clone, Copy, Debug, PartialEq, Eq)] +/// TeX page builder parameters (`\vsize`, `\topskip`, `\maxdepth`) plus one +/// `\dimen` limit per insertion class. +#[derive(Clone, Debug, PartialEq, Eq)] pub struct PageBuilder { pub page_goal: i64, pub top_skip: i64, pub max_depth: i64, + pub insertion_limits: Vec, } impl PageBuilder { @@ -78,19 +109,30 @@ impl PageBuilder { page_goal, top_skip: 0, max_depth: 0, + insertion_limits: Vec::new(), } } + /// Upper bound for `class` on one page; unlisted classes share the page. + fn insertion_limit(&self, class: u8) -> i64 { + self.insertion_limits + .iter() + .find(|limit| limit.class == class) + .map_or(self.page_goal, |limit| limit.height.max(0)) + } + /// Split `nodes` into pages, choosing the cheapest legal break each time. pub fn build(&self, nodes: &[VerticalNode]) -> Vec { let mut pages = Vec::new(); + let mut held = BTreeMap::new(); let mut start = self.skip_leading(nodes, 0); while start < nodes.len() { - let Some((fragment, next)) = self.best_fragment(nodes, start) else { + let Some((fragment, next, next_held)) = self.best_fragment(nodes, start, &held) else { break; }; let next = next.max(start + 1); pages.push(fragment); + held = next_held; start = self.skip_leading(nodes, next); } pages @@ -106,12 +148,19 @@ impl PageBuilder { index } - fn best_fragment(&self, nodes: &[VerticalNode], start: usize) -> Option<(PageFragment, usize)> { + fn best_fragment( + &self, + nodes: &[VerticalNode], + start: usize, + held: &BTreeMap, + ) -> Option<(PageFragment, usize, BTreeMap)> { let mut height = 0_i64; let mut stretch = 0_i64; let mut shrink = 0_i64; let mut depth = 0_i64; let mut first_box = true; + let mut usage: BTreeMap = held.clone(); + let mut reserved: i64 = usage.values().sum(); let mut candidates: Vec = Vec::new(); for index in start..nodes.len() { @@ -131,7 +180,9 @@ impl PageBuilder { } VerticalNode::Glue(glue) => { if index > start { - candidates.push(self.candidate(height, depth, stretch, shrink, 0, index)); + candidates.push( + self.candidate(height, depth, stretch, shrink, reserved, 0, index), + ); } height += glue.width; stretch += glue.stretch.max(0); @@ -140,21 +191,46 @@ impl PageBuilder { VerticalNode::Penalty(penalty) => { if *penalty <= -10_000 { let end = index.max(start); - let badness = self.badness(height, stretch, shrink); - let fragment = - self.fragment(start, end, height, depth, badness, badness + penalty); - return Some((fragment, index + 1)); + let badness = self.badness(height, reserved, stretch, shrink); + let fragment = self.fragment( + start, + end, + height, + depth, + badness, + badness + penalty, + self.insertion_space(nodes, start, end, held), + ); + return Some(( + fragment, + index + 1, + self.insertion_overflow(nodes, start, end, held), + )); } if index > start { - candidates - .push(self.candidate(height, depth, stretch, shrink, *penalty, index)); + candidates.push( + self.candidate( + height, depth, stretch, shrink, reserved, *penalty, index, + ), + ); } } + VerticalNode::Insertion { + class, + height: insert, + } => { + let limit = self.insertion_limit(*class); + let used = usage.entry(*class).or_insert(0); + let capacity = (limit - *used).max(0); + let taken = (*insert).min(capacity); + *used += taken; + reserved += taken; + } VerticalNode::Mark(_) => {} } } - candidates.push(self.candidate(height, depth, stretch, shrink, 0, nodes.len())); + candidates.push(self.candidate(height, depth, stretch, shrink, reserved, 0, nodes.len())); let best = self.select(candidates)?; let fragment = self.fragment( start, @@ -163,8 +239,57 @@ impl PageBuilder { best.depth, best.badness, best.cost, + self.insertion_space(nodes, start, best.end, held), ); - Some((fragment, best.next)) + Some(( + fragment, + best.next, + self.insertion_overflow(nodes, start, best.end, held), + )) + } + + fn insertion_space( + &self, + nodes: &[VerticalNode], + start: usize, + end: usize, + held: &BTreeMap, + ) -> Vec { + let mut usage = held.clone(); + for node in &nodes[start..end] { + if let VerticalNode::Insertion { class, height } = node { + let limit = self.insertion_limit(*class); + let used = usage.entry(*class).or_insert(0); + let capacity = (limit - *used).max(0); + *used += (*height).min(capacity); + } + } + usage + .into_iter() + .map(|(class, height)| InsertionSpace { class, height }) + .collect() + } + + fn insertion_overflow( + &self, + nodes: &[VerticalNode], + start: usize, + end: usize, + held: &BTreeMap, + ) -> BTreeMap { + let mut requested = held.clone(); + for node in &nodes[start..end] { + if let VerticalNode::Insertion { class, height } = node { + *requested.entry(*class).or_insert(0) += height; + } + } + requested + .into_iter() + .filter_map(|(class, total)| { + let overflow = total - self.insertion_limit(class); + (overflow > 0).then_some((class, overflow)) + }) + .collect() } fn candidate( @@ -173,6 +298,7 @@ impl PageBuilder { depth: i64, stretch: i64, shrink: i64, + reserved: i64, penalty: i64, end: usize, ) -> Candidate { @@ -182,26 +308,28 @@ impl PageBuilder { } else { (height, depth) }; - let badness = self.badness(height, stretch, shrink); + let badness = self.badness(height, reserved, stretch, shrink); Candidate { cost: badness + penalty, badness, height, depth, shrink, + reserved, end, next: end + 1, } } - fn badness(&self, height: i64, stretch: i64, shrink: i64) -> i64 { - if height == self.page_goal { + fn badness(&self, height: i64, reserved: i64, stretch: i64, shrink: i64) -> i64 { + let goal = self.page_goal - reserved; + if height == goal { return 0; } - let (shortfall, slack) = if height < self.page_goal { - (self.page_goal - height, stretch) + let (shortfall, slack) = if height < goal { + (goal - height, stretch) } else { - (height - self.page_goal, shrink) + (height - goal, shrink) }; if slack <= 0 { return 10_000; @@ -215,6 +343,7 @@ impl PageBuilder { } } + #[allow(clippy::too_many_arguments)] fn fragment( &self, start: usize, @@ -223,6 +352,7 @@ impl PageBuilder { depth: i64, badness: i64, cost: i64, + insertions: Vec, ) -> PageFragment { PageFragment { start, @@ -231,25 +361,30 @@ impl PageBuilder { badness, height, depth, + insertions, } } fn select(&self, candidates: Vec) -> Option { let feasible: Vec = candidates .iter() - .copied() .filter(|candidate| { - candidate.height <= self.page_goal - || candidate.height - self.page_goal <= candidate.shrink + let page = candidate.height + candidate.reserved; + page <= self.page_goal || page - self.page_goal <= candidate.shrink }) + .cloned() .collect(); let pool = if feasible.is_empty() { candidates } else { feasible }; - pool.into_iter() - .min_by_key(|candidate| (candidate.cost, (candidate.height - self.page_goal).abs())) + pool.into_iter().min_by_key(|candidate| { + ( + candidate.cost, + (candidate.height + candidate.reserved - self.page_goal).abs(), + ) + }) } } @@ -386,4 +521,77 @@ mod tests { assert_eq!(pages[0].height, 60); assert_eq!((pages[0].start, pages[0].end), (0, 5)); } + + fn limit(class: u8, height: i64) -> InsertionLimit { + InsertionLimit { class, height } + } + + #[test] + fn insertion_reservation_pushes_the_break_earlier() { + let mut builder = PageBuilder::new(100); + builder.insertion_limits = vec![limit(1, 100)]; + let nodes = vec![ + box_(60, 0), + VerticalNode::Insertion { + class: 1, + height: 30, + }, + glue(0, 10, 0), + box_(40, 0), + ]; + let pages = builder.build(&nodes); + assert_eq!(pages.len(), 2, "the reservation must split the page"); + assert_eq!(pages[0].height, 60); + assert_eq!( + pages[0].insertions, + vec![InsertionSpace { + class: 1, + height: 30 + }] + ); + assert_eq!(pages[1].height, 40); + assert!(pages[1].insertions.is_empty()); + } + + #[test] + fn insertion_overflow_is_held_over_to_the_next_page() { + let builder = PageBuilder { + insertion_limits: vec![limit(1, 20)], + ..PageBuilder::new(100) + }; + let nodes = vec![ + box_(30, 0), + VerticalNode::Insertion { + class: 1, + height: 20, + }, + glue(0, 40, 0), + box_(30, 0), + VerticalNode::Insertion { + class: 1, + height: 20, + }, + glue(0, 40, 0), + box_(30, 0), + ]; + let pages = builder.build(&nodes); + assert_eq!(pages.len(), 2); + assert_eq!(pages[0].height, 60); + assert_eq!( + pages[0].insertions, + vec![InsertionSpace { + class: 1, + height: 20 + }] + ); + assert_eq!(pages[1].height, 30); + assert_eq!( + pages[1].insertions, + vec![InsertionSpace { + class: 1, + height: 20 + }], + "the overflow material is held over to the next page" + ); + } } diff --git a/crates/texrra-tex-core/tests/oracle.rs b/crates/texrra-tex-core/tests/oracle.rs index 2a9488f..3267cd3 100644 --- a/crates/texrra-tex-core/tests/oracle.rs +++ b/crates/texrra-tex-core/tests/oracle.rs @@ -246,10 +246,6 @@ fn assert_lines_match(label: &str, ours: &[Line], reference: &[Line]) { } } -fn paragraph_fixture(text: &str, width_pt: u32) -> String { - paragraph_fixture_with(text, width_pt, "") -} - fn paragraph_fixture_with(text: &str, width_pt: u32, prefix: &str) -> String { format!( "\\documentclass[10pt]{{article}}\n\ diff --git a/docs/ROUTE_D_PLAN.md b/docs/ROUTE_D_PLAN.md index df6e12b..2380ed8 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`). 333 workspace tests are green and no oracle +PDF opt-in with `?engine=route-d`). 336 workspace tests are green and no oracle fixture is ignored. Known gaps, in dependency order: @@ -66,7 +66,8 @@ yet generic `fil`/`fill` glue 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, but floats, insertions and incremental + documents made of box/glue/penalty/mark units and insertion classes + (per-class limits with held-over material), but floats and incremental checkpoint replay still use the scrolling builder, and an interpreted `\output` is absent; 3. `\insert` classes model `\count`/`\dimen`/`\skip` but are not TeX @@ -260,9 +261,10 @@ goal, so overfull pages take the least overfull break. `Document::h_offset` and `v_offset` feed the PDF writer's `pdf::PageOrigin`, which translates the page body without moving the sheet; a route-D integration fixture checks the shift with `pdftotext -bbox`, and the PDF endpoint reads leading `\hoffset`/`\voffset` -dimension assignments from the source. 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 paper margins and the interpreted +dimension assignments from the source. Insertion classes are placed by the +paged builder with their limits and held-over material; floats 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 paper margins and the interpreted `\output`. Acceptance: 10 page fixtures (article text, footnotes, floats, forced breaks); diff --git a/docs/TEX_CORE.md b/docs/TEX_CORE.md index 11618ea..00f2500 100755 --- a/docs/TEX_CORE.md +++ b/docs/TEX_CORE.md @@ -292,7 +292,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 with default and custom `\sfcode`/`\frenchspacing`, explicit `\spaceskip`/`\xspaceskip`, `\baselineskip`/`\lineskip`/`\parskip` interline glue, pdfTeX oracle matrix 90-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`; `Engine::layout_paged` builds pages through it for documents made of box/glue/penalty/mark vertical material (a unit may span pages), while floats, insertions and incremental replay still use 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 documents made of box/glue/penalty/mark vertical material (a unit may span pages), while floats and incremental replay still use the scrolling path, insertions are placed through the builder too; 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 | @@ -321,7 +321,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. `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); `Document::max_depth` feeds TeX's `\maxdepth` into the builder, and among equal-cost breakpoints the candidate closest to the page goal wins, so an overfull page takes the least overfull break. Paragraphs also split across pages at line boundaries, so body material no longer overflows a page as one box. `Document::h_offset` and `v_offset` (TeX `\hoffset`/`\voffset`, default zero) feed `pdf::PageOrigin`, and `display_lists_to_pdf_with_origin` translates the page body without moving the sheet; a route-D fixture checks a 10pt/20pt shift against `pdftotext -bbox`, and the route-D PDF endpoint strips leading `\hoffset`/`\voffset` dimension assignments from the source and applies them. `Engine::top_mark`, `first_mark` and `bot_mark` implement TeX's carried mark registers per class. Floats, insertions and the incremental checkpoint replay still use the scrolling builder, which remains the default until those pieces have a paged equivalent. +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, marks and insertion classes, including per-class limits and held-over material); `Document::max_depth` feeds TeX's `\maxdepth` into the builder, and among equal-cost breakpoints the candidate closest to the page goal wins, so an overfull page takes the least overfull break. Paragraphs also split across pages at line boundaries, so body material no longer overflows a page as one box. `Document::h_offset` and `v_offset` (TeX `\hoffset`/`\voffset`, default zero) feed `pdf::PageOrigin`, and `display_lists_to_pdf_with_origin` translates the page body without moving the sheet; a route-D fixture checks a 10pt/20pt shift against `pdftotext -bbox`, and the route-D PDF endpoint strips leading `\hoffset`/`\voffset` dimension assignments from the source and applies them. `Engine::top_mark`, `first_mark` and `bot_mark` implement TeX's carried mark registers per class. Floats 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. @@ -329,7 +329,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 215 unit tests plus seven route-D integration tests and thirteen oracle fixtures. Workspace verification: `cargo fmt --all -- --check`; `cargo test --workspace --offline` runs 333 tests (215 route-D unit, 7 route-D integration, 13 oracle, 71 v1 integration, 20 server, 4 v1 unit, 1 core unit, 2 binary units), with none ignored. v1 remains the live server path. +The crate currently has 218 unit tests plus seven route-D integration tests and thirteen oracle fixtures. Workspace verification: `cargo fmt --all -- --check`; `cargo test --workspace --offline` runs 336 tests (218 route-D unit, 7 route-D integration, 13 oracle, 71 v1 integration, 20 server, 4 v1 unit, 1 core unit, 2 binary units), with none ignored. v1 remains the live server path. ### M0 incremental demo @@ -366,9 +366,9 @@ deliberately open rather than approximated: - **M2**: the scrolling builder still drives `Document`; `page::PageBuilder` implements TeX's candidate-breakpoint cost (badness + penalty, glue 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; paper margins, held-over - insertion material and an interpreted `\output` remain open (explicit + for simple documents, but floats and incremental replay need a paged + equivalent before it can become the default; paper margins and an interpreted + `\output` remain open (explicit `\hoffset`/`\voffset` offsets are applied by the PDF writer). - **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