From 97b72ac5d97a1a9a37bcb519f48cf9d56e77ccd3 Mon Sep 17 00:00:00 2001 From: GloamXun Date: Fri, 23 Oct 2026 13:07:11 +0800 Subject: [PATCH] Honour textheight geometry and widen the page oracle --- crates/texrra-tex-core/tests/oracle.rs | 84 +++++++++++++++++++++++++- docs/ROUTE_D_PLAN.md | 2 +- docs/TEX_CORE.md | 4 +- src/route_d.rs | 81 +++++++++++++++---------- tests/server.rs | 32 ++++++++++ 5 files changed, 167 insertions(+), 36 deletions(-) diff --git a/crates/texrra-tex-core/tests/oracle.rs b/crates/texrra-tex-core/tests/oracle.rs index 8f79df8..2d5bf9d 100644 --- a/crates/texrra-tex-core/tests/oracle.rs +++ b/crates/texrra-tex-core/tests/oracle.rs @@ -280,6 +280,15 @@ fn page_alnum_text(page: &texrra_tex_core::Page) -> String { /// metrics that match the pdfTeX fixtures (`\hsize` 345pt, `\topskip` 12pt, /// `\vsize` 550pt, `\parskip` 0). fn route_pages_text(paragraphs: &[String], par_skip: i64) -> Vec { + route_pages_text_with(paragraphs, par_skip, 550, 12) +} + +fn route_pages_text_with( + paragraphs: &[String], + par_skip: i64, + page_goal_pt: i64, + top_skip_pt: i64, +) -> Vec { let mut units = Vec::new(); for (index, text) in paragraphs.iter().enumerate() { let style = ParagraphStyle { @@ -290,8 +299,8 @@ fn route_pages_text(paragraphs: &[String], par_skip: i64) -> Vec { }; units.push(Unit::paragraph_with_style(index as u64 + 1, text, style)); } - let mut document = Document::new(550 * PT, units); - document.top_skip = 12 * PT; + let mut document = Document::new(page_goal_pt * PT, units); + document.top_skip = top_skip_pt * PT; document.par_skip = par_skip * PT; document.text_float_sep = 0; Engine::layout(&document) @@ -556,6 +565,77 @@ fn pages_break_like_pdftex_with_paragraph_spacing() { } } +#[test] +fn pages_break_like_pdftex_on_a_shorter_page() { + let paragraphs: Vec = (0..80) + .map(|index| format!("p{index} alpha beta gamma")) + .collect(); + let body: String = paragraphs + .iter() + .map(|paragraph| format!("{paragraph}\\par\n")) + .collect(); + let source = format!( + "\\documentclass[10pt]{{article}}\n\ + \\pdfpagewidth=612bp \\pdfpageheight=792bp\n\ + \\pagestyle{{empty}}\n\ + \\textheight=300pt\n\ + \\begin{{document}}\n\ + \\hsize=345pt \\parindent=15pt \\parskip=0pt \\topskip=12pt\n\ + {body}\\end{{document}}\n" + ); + let Some(reference) = pdftex_pages(&source) else { + eprintln!("skipping: pdflatex/pdftotext are not installed"); + return; + }; + assert!(reference.len() > 2, "fixture should span pages"); + let ours = route_pages_text_with(¶graphs, 0, 300, 12); + assert_eq!( + ours.len(), + reference.len(), + "route-D produced {} pages, pdfLaTeX {}", + ours.len(), + reference.len() + ); + for (index, (ours, reference)) in ours.iter().zip(&reference).enumerate() { + assert_eq!(ours, reference, "text on page {}", index + 1); + } +} + +#[test] +fn pages_break_like_pdftex_with_a_taller_topskip() { + let paragraphs: Vec = (0..80) + .map(|index| format!("p{index} alpha beta gamma")) + .collect(); + let body: String = paragraphs + .iter() + .map(|paragraph| format!("{paragraph}\\par\n")) + .collect(); + let source = format!( + "\\documentclass[10pt]{{article}}\n\ + \\pdfpagewidth=612bp \\pdfpageheight=792bp\n\ + \\pagestyle{{empty}}\n\ + \\begin{{document}}\n\ + \\hsize=345pt \\parindent=15pt \\parskip=0pt \\topskip=30pt \\vsize=550pt\n\ + {body}\\end{{document}}\n" + ); + let Some(reference) = pdftex_pages(&source) else { + eprintln!("skipping: pdflatex/pdftotext are not installed"); + return; + }; + assert!(reference.len() > 1, "fixture should span pages"); + let ours = route_pages_text_with(¶graphs, 0, 550, 30); + assert_eq!( + ours.len(), + reference.len(), + "route-D produced {} pages, pdfLaTeX {}", + ours.len(), + reference.len() + ); + for (index, (ours, reference)) in ours.iter().zip(&reference).enumerate() { + assert_eq!(ours, reference, "text on page {}", index + 1); + } +} + #[test] fn pages_split_paragraphs_like_pdftex() { let sentence = "alpha beta gamma delta epsilon zeta eta theta iota kappa. "; diff --git a/docs/ROUTE_D_PLAN.md b/docs/ROUTE_D_PLAN.md index 315e2a1..5889514 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`). 407 workspace tests are green and no oracle +PDF opt-in with `?engine=route-d`). 410 workspace tests are green and no oracle fixture is ignored. Known gaps, in dependency order: diff --git a/docs/TEX_CORE.md b/docs/TEX_CORE.md index 8738563..729c468 100755 --- a/docs/TEX_CORE.md +++ b/docs/TEX_CORE.md @@ -338,7 +338,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 unit tests covering overfull avoidance, exact glue filling, forced and costed breaks, `\topskip`, `\maxdepth`, marks, insertion limits and top-float placement; every fragment records the penalty that broke it. `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; held-over material starts with `Document::split_top_skip` (TeX `\splittopskip`, default 10pt) when the class capacity can also hold its first item); `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_paper` translates the page body without moving the sheet; a route-D fixture checks a 10pt/20pt shift against `pdftotext -bbox`. `Document::paper_width` and `paper_height` (TeX `\paperwidth`/`\paperheight`, default US Letter) set the PDF MediaBox and the preview page box, and both route-D endpoints strip leading `\hoffset`/`\voffset`/`\paperwidth`/`\paperheight`/`\vsize` dimension assignments from the source and apply them (`\vsize` sets the page goal). `Engine::top_mark`, `first_mark` and `bot_mark` implement TeX's carried mark registers per class. `Document::output_routine` runs an interpreted `\output` program over the paged fragments (`output::OutputProgram`: `\shipout\box255`, `\relax`, `\message`, `\ifdim`, `\ifnum`, `\ifodd` and `\ifcase` over the page registers, now including `\pageno`, `\outputpenalty` and `\deadcycles`), dropping pages the routine does not ship. Assignments such as `\pageno=10`, `\deadcycles=0`, `\count2=2000`, `\dimen2=30pt`, `\skip2=6pt` and `\vsize=300pt` mutate the per-page context, and `\pageno` is carried into the next page's context; for documents without insertions or floats the paged builder runs the routine after each page, so an assigned `\vsize` sets the goal of the pages the routine has not seen yet. The `\pagegoal` register handed to the output routine is reduced by the insertion space reserved on that page. Paged layouts record the node index that starts each page, so `Engine::edit` on a paged layout reuses the sealed prefix and rebuilds only from the edited unit's page onward; an interpreted `\output` routine still forces a full rebuild, and an edit whose replay would begin before the first insertion does too, because held-over material and dropped pages move page boundaries. The scrolling builder's float path remains to be ported. The oracle harness also compares whole pages: three page fixtures (single-line paragraphs, `\parskip=6pt`, and multi-line paragraphs split across pages) assert the same page count and the same per-page alphanumeric text as pdfLaTeX at 345pt measure, 550pt `\vsize`, 12pt `\topskip` and 15pt `\parindent`. +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 unit tests covering overfull avoidance, exact glue filling, forced and costed breaks, `\topskip`, `\maxdepth`, marks, insertion limits and top-float placement; every fragment records the penalty that broke it. `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; held-over material starts with `Document::split_top_skip` (TeX `\splittopskip`, default 10pt) when the class capacity can also hold its first item); `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_paper` translates the page body without moving the sheet; a route-D fixture checks a 10pt/20pt shift against `pdftotext -bbox`. `Document::paper_width` and `paper_height` (TeX `\paperwidth`/`\paperheight`, default US Letter) set the PDF MediaBox and the preview page box, and both route-D endpoints strip leading `\hoffset`/`\voffset`/`\paperwidth`/`\paperheight`/`\vsize`/`\textheight` dimension assignments from the source (preamble included) and apply them; `\textheight` wins over `\vsize` because LaTeX resets `\vsize` from `\textheight` on every page, and project previews reuse the same geometry parsing. `Engine::top_mark`, `first_mark` and `bot_mark` implement TeX's carried mark registers per class. `Document::output_routine` runs an interpreted `\output` program over the paged fragments (`output::OutputProgram`: `\shipout\box255`, `\relax`, `\message`, `\ifdim`, `\ifnum`, `\ifodd` and `\ifcase` over the page registers, now including `\pageno`, `\outputpenalty` and `\deadcycles`), dropping pages the routine does not ship. Assignments such as `\pageno=10`, `\deadcycles=0`, `\count2=2000`, `\dimen2=30pt`, `\skip2=6pt` and `\vsize=300pt` mutate the per-page context, and `\pageno` is carried into the next page's context; for documents without insertions or floats the paged builder runs the routine after each page, so an assigned `\vsize` sets the goal of the pages the routine has not seen yet. The `\pagegoal` register handed to the output routine is reduced by the insertion space reserved on that page. Paged layouts record the node index that starts each page, so `Engine::edit` on a paged layout reuses the sealed prefix and rebuilds only from the edited unit's page onward; an interpreted `\output` routine still forces a full rebuild, and an edit whose replay would begin before the first insertion does too, because held-over material and dropped pages move page boundaries. The scrolling builder's float path remains to be ported. The oracle harness also compares whole pages: five page fixtures (single-line paragraphs, `\parskip=6pt`, multi-line paragraphs split across pages, a 300pt `\textheight`, and a 30pt `\topskip`) assert the same page count and the same per-page alphanumeric text as pdfLaTeX at 345pt measure, 550pt `\vsize`, 12pt `\topskip` and 15pt `\parindent`. 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. @@ -346,7 +346,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 282 unit tests plus seven route-D integration tests and seventeen oracle fixtures. Workspace verification: `cargo fmt --all -- --check`; `cargo test --workspace --offline` runs 407 tests (282 route-D unit, 7 route-D integration, 17 oracle, 71 v1 integration, 23 server, 4 v1 unit, 1 core unit, 2 binary units), with none ignored. v1 remains the live server path. +The crate currently has 282 unit tests plus seven route-D integration tests and nineteen oracle fixtures. Workspace verification: `cargo fmt --all -- --check`; `cargo test --workspace --offline` runs 410 tests (282 route-D unit, 7 route-D integration, 19 oracle, 71 v1 integration, 24 server, 4 v1 unit, 1 core unit, 2 binary units), with none ignored. v1 remains the live server path. ### M0 incremental demo diff --git a/src/route_d.rs b/src/route_d.rs index a13077f..68994ae 100755 --- a/src/route_d.rs +++ b/src/route_d.rs @@ -22,6 +22,7 @@ thread_local! { struct ProjectSession { paragraphs: Vec, + geometry: PageGeometry, engine: Engine, } @@ -42,17 +43,19 @@ fn latex_body(source: &str) -> &str { /// `Engine::edit`, starting from the earliest changed paragraph. Structural /// edits fall back to a full layout. The v1 project preview remains the default. pub fn project_preview_json(project_id: &str, source: &str) -> Result { - let paragraphs = paragraphs(latex_body(source))?; - let document = build_document(¶graphs); + let (body, geometry) = geometry_and_body(source); + let paragraphs = paragraphs(&body)?; + let mut document = build_document(¶graphs); + apply_geometry(&mut document, &geometry); let mut sessions = project_sessions() .lock() .map_err(|_| "route-D session lock".to_string())?; let previous = sessions.remove(project_id); let (engine, changed, recomputed) = match previous { Some(mut session) => { - if session.paragraphs == paragraphs { + if session.paragraphs == paragraphs && session.geometry == geometry { (session.engine, Vec::new(), 0) - } else { + } else if session.geometry == geometry { let prefix = session .paragraphs .iter() @@ -70,6 +73,11 @@ pub fn project_preview_json(project_id: &str, source: &str) -> Result = (0..engine.pages().len()).collect(); + let recomputed = changed.len(); + (engine, changed, recomputed) } } _ => { @@ -82,23 +90,29 @@ pub fn project_preview_json(project_id: &str, source: &str) -> Result, paper_height: Option, vsize: Option, + textheight: Option, } -/// Pull `\hoffset`/`\voffset`/`\paperwidth`/`\paperheight`/`\vsize` -/// assignments out of the source and return the remaining body. Each command -/// takes a TeX dimension. +/// Pull `\hoffset`/`\voffset`/`\paperwidth`/`\paperheight`/`\vsize`/ +/// `\textheight` assignments out of the source and return the remaining body. +/// Each command takes a TeX dimension. LaTeX resets `\vsize` from +/// `\textheight` at every page, so `\textheight` wins when both appear. fn strip_page_geometry(source: &str) -> (String, PageGeometry) { let mut geometry = PageGeometry::default(); let mut body = String::new(); @@ -114,6 +128,8 @@ fn strip_page_geometry(source: &str) -> (String, PageGeometry) { geometry.paper_height = Some(value); } else if let Some(value) = dimension_assignment(trimmed, "vsize") { geometry.vsize = Some(value); + } else if let Some(value) = dimension_assignment(trimmed, "textheight") { + geometry.textheight = Some(value); } else { body.push_str(line); body.push('\n'); @@ -122,6 +138,27 @@ fn strip_page_geometry(source: &str) -> (String, PageGeometry) { (body, geometry) } +/// Strip geometry assignments from the whole source (preamble included) and +/// return the LaTeX body with them removed. +fn geometry_and_body(source: &str) -> (String, PageGeometry) { + let (stripped, geometry) = strip_page_geometry(source); + (latex_body(&stripped).to_string(), geometry) +} + +fn apply_geometry(document: &mut Document, geometry: &PageGeometry) { + document.h_offset = geometry.origin.h_offset; + document.v_offset = geometry.origin.v_offset; + if let Some(width) = geometry.paper_width { + document.paper_width = width; + } + if let Some(height) = geometry.paper_height { + document.paper_height = height; + } + if let Some(height) = geometry.textheight.or(geometry.vsize) { + document.page_goal = height; + } +} + fn dimension_assignment(line: &str, name: &str) -> Option { let rest = line.strip_prefix('\\')?; let rest = rest.strip_prefix(name)?; @@ -149,18 +186,10 @@ fn parse_dimension(text: &str) -> Option { /// Build a JSON preview from blank-line-separated plain-text paragraphs. pub fn preview_json(source: &str) -> Result { - let (body, geometry) = strip_page_geometry(source); + let (body, geometry) = geometry_and_body(source); let paragraphs = paragraphs(&body)?; let mut document = build_document(¶graphs); - if let Some(width) = geometry.paper_width { - document.paper_width = width; - } - if let Some(height) = geometry.paper_height { - document.paper_height = height; - } - if let Some(height) = geometry.vsize { - document.page_goal = height; - } + apply_geometry(&mut document, &geometry); let engine = Engine::layout(&document); let json = render_json(&document, &engine, None); // Keep the layout so a following `/edit` request can diff against it and @@ -173,20 +202,10 @@ pub fn preview_json(source: &str) -> Result { /// Render the same checkpointed document as a route-D PDF. pub fn pdf_bytes(source: &str) -> Result, String> { - let (body, geometry) = strip_page_geometry(latex_body(source)); + let (body, geometry) = geometry_and_body(source); let paragraphs = paragraphs(&body)?; let mut document = build_document(¶graphs); - document.h_offset = geometry.origin.h_offset; - document.v_offset = geometry.origin.v_offset; - if let Some(width) = geometry.paper_width { - document.paper_width = width; - } - if let Some(height) = geometry.paper_height { - document.paper_height = height; - } - if let Some(height) = geometry.vsize { - document.page_goal = height; - } + apply_geometry(&mut document, &geometry); let engine = Engine::layout(&document); let pages: Vec<_> = engine .pages() diff --git a/tests/server.rs b/tests/server.rs index edf322b..fce8d87 100644 --- a/tests/server.rs +++ b/tests/server.rs @@ -657,6 +657,38 @@ fn route_d_pdf_renders_itemize_content() { assert!(response.body.len() > 500); } +#[test] +fn route_d_honours_text_height() { + let server = TestServer::start("route-d-textheight"); + let body = "word ".repeat(400); + let default = server.request( + "POST", + "/api/route-d/preview", + body.as_bytes(), + "text/plain", + ); + assert_eq!(default.status, 200, "{}", default.text()); + let default: Value = serde_json::from_slice(&default.body).expect("route-D JSON"); + let default_pages = default["pageCount"].as_u64().unwrap(); + + let source = format!("\\textheight=200pt\n\n{body}"); + let custom = server.request( + "POST", + "/api/route-d/preview", + source.as_bytes(), + "text/plain", + ); + assert_eq!(custom.status, 200, "{}", custom.text()); + let custom: Value = serde_json::from_slice(&custom.body).expect("route-D JSON"); + let custom_pages = custom["pageCount"].as_u64().unwrap(); + + assert_eq!(default_pages, 1, "default page goal should fit the body"); + assert!( + custom_pages > default_pages, + "custom \\textheight should force more pages: {custom_pages} vs {default_pages}" + ); +} + #[test] fn route_d_pdf_applies_page_offsets() { let server = TestServer::start("route-d-pdf-origin");