From 52a74755f79d9e7720aaad71304a517792b603da Mon Sep 17 00:00:00 2001 From: GloamXun Date: Mon, 26 Oct 2026 00:53:40 +0800 Subject: [PATCH] Check matrix and cases positions against pdfLaTeX --- crates/texrra-tex-core/src/math.rs | 47 ++++++-- crates/texrra-tex-core/src/render.rs | 3 +- crates/texrra-tex-core/tests/oracle.rs | 146 ++++++++++++++++++++++++- docs/ROUTE_D_PLAN.md | 2 +- docs/TEX_CORE.md | 6 +- 5 files changed, 183 insertions(+), 21 deletions(-) diff --git a/crates/texrra-tex-core/src/math.rs b/crates/texrra-tex-core/src/math.rs index bef1680..9072daa 100755 --- a/crates/texrra-tex-core/src/math.rs +++ b/crates/texrra-tex-core/src/math.rs @@ -26,6 +26,10 @@ pub enum MathColumnAlign { Right, } +fn default_matrix_row_lead() -> i64 { + 12 * 65_536 +} + #[derive(Clone, Debug, PartialEq, Eq, Hash, serde::Serialize, serde::Deserialize)] pub enum MathAtom { Symbol(char), @@ -102,6 +106,8 @@ pub enum MathAtom { align: Vec, left: Option, right: Option, + #[serde(default = "default_matrix_row_lead")] + row_lead: i64, }, /// Rows of a `multline`: first flush left, last flush right, middle centred. Multline { @@ -635,6 +641,7 @@ pub(crate) fn matrix_layout( _align: &[MathColumnAlign], left: Option, right: Option, + row_lead: i64, ) -> MatrixLayout { let boxes: Vec> = rows .iter() @@ -665,7 +672,7 @@ pub(crate) fn matrix_layout( .collect(); let mut baselines = vec![0_i64; boxes.len()]; for index in 1..boxes.len() { - let advance = (row_depths[index - 1] + row_heights[index] + 2 * 65_536).max(655_360); + let advance = (row_depths[index - 1] + row_heights[index] + 2 * 65_536).max(row_lead); baselines[index] = baselines[index - 1] + advance; } let first_height = row_heights.first().copied().unwrap_or(0); @@ -849,15 +856,26 @@ fn math_environment(chars: &[char], index: usize) -> Option<(MathAtom, usize)> { .collect() }) .collect(); - let (left, right, default_align) = match name.as_str() { - "cases" => (Some('{'), None, MathColumnAlign::Left), - "matrix" => (None, None, MathColumnAlign::Center), - "pmatrix" => (Some('('), Some(')'), MathColumnAlign::Center), - "bmatrix" => (Some('['), Some(']'), MathColumnAlign::Center), - "Bmatrix" => (Some('{'), Some('}'), MathColumnAlign::Center), - "vmatrix" => (Some('|'), Some('|'), MathColumnAlign::Center), - "Vmatrix" => (Some('\u{2016}'), Some('\u{2016}'), MathColumnAlign::Center), - "array" => (None, None, MathColumnAlign::Center), + let (left, right, default_align, row_lead) = match name.as_str() { + "cases" => ( + Some('{'), + None, + MathColumnAlign::Left, + // amsmath applies \arraystretch{1.2} inside cases. + 943_718, + ), + "matrix" => (None, None, MathColumnAlign::Center, 12 * 65_536), + "pmatrix" => (Some('('), Some(')'), MathColumnAlign::Center, 12 * 65_536), + "bmatrix" => (Some('['), Some(']'), MathColumnAlign::Center, 12 * 65_536), + "Bmatrix" => (Some('{'), Some('}'), MathColumnAlign::Center, 12 * 65_536), + "vmatrix" => (Some('|'), Some('|'), MathColumnAlign::Center, 12 * 65_536), + "Vmatrix" => ( + Some('\u{2016}'), + Some('\u{2016}'), + MathColumnAlign::Center, + 12 * 65_536, + ), + "array" => (None, None, MathColumnAlign::Center, 12 * 65_536), _ => return None, }; let columns = rows.iter().map(|row| row.len()).max().unwrap_or(0); @@ -872,6 +890,7 @@ fn math_environment(chars: &[char], index: usize) -> Option<(MathAtom, usize)> { align, left, right, + row_lead, }, end, )) @@ -973,8 +992,9 @@ pub fn layout_math(atom: &MathAtom, font: &Cmr10Metrics) -> MathBox { align, left, right, + row_lead, } => { - let layout = matrix_layout(rows, font, align, *left, *right); + let layout = matrix_layout(rows, font, align, *left, *right, *row_lead); MathBox { width: layout.width, height: layout.height, @@ -2687,6 +2707,7 @@ mod tests { align, left, right, + .. } = atom else { panic!("expected a cases matrix"); @@ -2703,6 +2724,7 @@ mod tests { align, left: Some('{'), right: None, + row_lead: 943_718, }, &Cmr10Metrics::default(), ); @@ -2745,6 +2767,7 @@ mod tests { align, left, right, + .. } = atom else { panic!("expected a matrix atom"); @@ -2760,6 +2783,7 @@ mod tests { align, left: Some('('), right: Some(')'), + row_lead: 12 * 65_536, }, &Cmr10Metrics::default(), ); @@ -2782,6 +2806,7 @@ mod tests { align, left, right, + .. } = atom else { panic!("expected an array matrix"); diff --git a/crates/texrra-tex-core/src/render.rs b/crates/texrra-tex-core/src/render.rs index 9dec2b1..fcc2825 100755 --- a/crates/texrra-tex-core/src/render.rs +++ b/crates/texrra-tex-core/src/render.rs @@ -1031,8 +1031,9 @@ impl Page { align, left, right, + row_lead, } => { - let layout = math::matrix_layout(rows, font, align, *left, *right); + let layout = math::matrix_layout(rows, font, align, *left, *right, *row_lead); let base_extent = |delimiter: char| font.height(delimiter) + font.depth(delimiter); let scaled = |metrics: (char, i64, i64, i64)| -> (i64, i64) { let base = base_extent(metrics.0); diff --git a/crates/texrra-tex-core/tests/oracle.rs b/crates/texrra-tex-core/tests/oracle.rs index cf7418f..59ee79c 100644 --- a/crates/texrra-tex-core/tests/oracle.rs +++ b/crates/texrra-tex-core/tests/oracle.rs @@ -22,6 +22,12 @@ struct Word { text: String, /// Offset from the start of its line, in TeX points. x: f64, + /// Absolute left edge on the page, in TeX points. + #[allow(dead_code)] + abs_x: f64, + /// Absolute top edge on the page, in TeX points. + #[allow(dead_code)] + abs_y: f64, } #[derive(Clone, Debug)] @@ -121,11 +127,12 @@ fn parse_bbox(xhtml: &str) -> Vec { }); current_y = y_min; } - lines - .last_mut() - .expect("line") - .words - .push(Word { text, x: x_min }); + lines.last_mut().expect("line").words.push(Word { + text, + x: x_min, + abs_x: x_min * BP_TO_PT, + abs_y: y_min * BP_TO_PT, + }); rest = &rest[close + "".len()..]; } for line in &mut lines { @@ -138,6 +145,18 @@ fn parse_bbox(xhtml: &str) -> Vec { lines } +/// Flatten pdfLaTeX word boxes into absolute page positions. +fn tex_word_positions(source: &str) -> Option> { + let lines = pdftex_lines(source)?; + Some( + lines + .into_iter() + .flat_map(|line| line.words) + .map(|word| (word.text, word.abs_x, word.abs_y)) + .collect(), + ) +} + /// Lay out a paragraph after applying paragraph-register overrides. fn route_d_lines_with( text: &str, @@ -189,6 +208,8 @@ fn route_d_lines_with( words.push(Word { text: std::mem::take(&mut word), x: word_x, + abs_x: 0.0, + abs_y: 0.0, }); } x += *width as f64 / PT as f64; @@ -200,6 +221,8 @@ fn route_d_lines_with( words.push(Word { text: word, x: word_x, + abs_x: 0.0, + abs_y: 0.0, }); } let start = words.first().map(|word| word.x).unwrap_or(0.0); @@ -1237,3 +1260,116 @@ fn hfill_matches_pdftex() { fn hfill_and_hfil_match_pdftex() { compare_fixture_with("alpha \\hfil beta \\hfill gamma", 150, "", |_| {}); } + +#[test] +fn pmatrix_word_positions_match_pdftex() { + let source = r"\documentclass[10pt]{article} +\usepackage{amsmath} +\pagestyle{empty} +\begin{document} +\[ \begin{pmatrix} a & b \\ c & d \end{pmatrix} \] +\end{document} +"; + let Some(tex) = tex_word_positions(source) else { + eprintln!("skipping: pdflatex/pdftotext are not installed"); + return; + }; + let tex = |letter: &str| { + tex.iter() + .find(|(text, _, _)| text == letter) + .map(|(_, x, y)| (*x, *y)) + .unwrap_or_else(|| panic!("pdfLaTeX produced no `{letter}`")) + }; + + let atom = texrra_tex_core::math::parse_math(r"\begin{pmatrix} a & b \\ c & d \end{pmatrix}"); + let font = texrra_tex_core::cmr10::Cmr10Metrics::default(); + let unit = Unit::math(1, atom, &font); + let document = Document::new(700 * PT, vec![unit]); + let engine = Engine::layout(&document); + let page = engine.pages().first().expect("one page"); + let display = page.display_list(); + let ours = |letter: &str| { + display + .items + .iter() + .find_map(|item| match item { + texrra_tex_core::render::DisplayItem::Text { text, x, y, .. } if text == letter => { + Some((*x as f64 / PT as f64, *y as f64 / PT as f64)) + } + _ => None, + }) + .unwrap_or_else(|| panic!("route-D produced no `{letter}`")) + }; + + let (origin_x, origin_y) = ours("a"); + let (tex_x, tex_y) = tex("a"); + let mut max_dx = 0.0_f64; + let mut max_dy = 0.0_f64; + for letter in ["b", "c", "d"] { + let (x, y) = ours(letter); + let (reference_x, reference_y) = tex(letter); + let dx = (x - origin_x) - (reference_x - tex_x); + let dy = (y - origin_y) - (reference_y - tex_y); + max_dx = max_dx.max(dx.abs()); + max_dy = max_dy.max(dy.abs()); + } + eprintln!("pmatrix maximum offsets: ({max_dx:.2}, {max_dy:.2}) pt"); + assert!( + max_dx <= 1.0 && max_dy <= 1.0, + "pmatrix words are off by up to ({max_dx:.2}, {max_dy:.2}) pt" + ); +} + +#[test] +fn cases_row_spacing_matches_pdftex() { + let source = r"\documentclass[10pt]{article} +\usepackage{amsmath} +\pagestyle{empty} +\begin{document} +\[ \begin{cases} a & x>0 \\ b & y<0 \end{cases} \] +\end{document} +"; + let Some(tex) = tex_word_positions(source) else { + eprintln!("skipping: pdflatex/pdftotext are not installed"); + return; + }; + let tex = |word: &str| { + tex.iter() + .find(|(text, _, _)| text == word || text.starts_with(word)) + .map(|(_, x, y)| (*x, *y)) + .unwrap_or_else(|| panic!("pdfLaTeX produced no `{word}`")) + }; + + let atom = texrra_tex_core::math::parse_math(r"\begin{cases} a & x>0 \\ b & y<0 \end{cases}"); + let font = texrra_tex_core::cmr10::Cmr10Metrics::default(); + let unit = Unit::math(1, atom, &font); + let document = Document::new(700 * PT, vec![unit]); + let engine = Engine::layout(&document); + let page = engine.pages().first().expect("one page"); + let display = page.display_list(); + let ours = |letter: &str| { + display + .items + .iter() + .find_map(|item| match item { + texrra_tex_core::render::DisplayItem::Text { text, x, y, .. } if text == letter => { + Some((*x as f64 / PT as f64, *y as f64 / PT as f64)) + } + _ => None, + }) + .unwrap_or_else(|| panic!("route-D produced no `{letter}`")) + }; + + let (origin_x, origin_y) = ours("a"); + let (tex_x, tex_y) = tex("a"); + for word in ["b", "x"] { + let (x, y) = ours(word); + let (reference_x, reference_y) = tex(word); + let dx = (x - origin_x) - (reference_x - tex_x); + let dy = (y - origin_y) - (reference_y - tex_y); + assert!( + dx.abs() <= 1.5 && dy.abs() <= 1.5, + "`{word}` is off by ({dx:.2}, {dy:.2}) pt" + ); + } +} diff --git a/docs/ROUTE_D_PLAN.md b/docs/ROUTE_D_PLAN.md index 6d83488..b55c89a 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`). 814 workspace tests are green and no oracle +PDF opt-in with `?engine=route-d`). 816 workspace tests are green and no oracle fixture is ignored. Preview JSON also carries a `warnings` array naming environments route-D cannot lay out and control words that survived layout, so unsupported source is reported instead of being silently typeset. diff --git a/docs/TEX_CORE.md b/docs/TEX_CORE.md index f75367c..060c7a7 100755 --- a/docs/TEX_CORE.md +++ b/docs/TEX_CORE.md @@ -367,7 +367,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`, `cmssbx10`, `cmssi10`, `cmcsc10`) supplies advances, kerns, ligatures, and italic correction for layout, the display list selects the matching face, and the PDF writes Computer Modern Type1 outlines for each built-in face (`cmr10`/`cmbx10`/`cmti10`/`cmbxti10`/`cmtt10`/`cmss10`/`cmssbx10`/`cmssi10`/`cmcsc10`, plus `cmmi10` for mathematical italic letters, `cmsy10` for math symbols and `cmex10` for big operators), falling back to Liberation subsets only for characters the Type1 encodings cannot address; those fallback glyphs keep their Unicode text under PDF extraction, so accented and Greek words round-trip; Type1 faces carry a ToUnicode CMap built from the requested characters, so glyphs whose names are ambiguous in the Adobe Glyph List (capital Omega, which would otherwise extract as U+2126) keep their intended code points. `Engine::edit` preserves the face when reflowing an edited paragraph. -The crate currently has 419 unit tests plus ten route-D integration tests and thirty-five oracle fixtures. Workspace verification: `cargo fmt --all -- --check`; `cargo test --workspace --offline` runs 814 tests (419 route-D unit, 214 engine binary unit, 10 route-D integration, 35 oracle, 71 v1 integration, 60 server, 4 engine unit, 1 core unit), with none ignored. v1 remains the live server path. +The crate currently has 419 unit tests plus ten route-D integration tests and thirty-seven oracle fixtures. Workspace verification: `cargo fmt --all -- --check`; `cargo test --workspace --offline` runs 816 tests (419 route-D unit, 214 engine binary unit, 10 route-D integration, 37 oracle, 71 v1 integration, 60 server, 4 engine unit, 1 core unit), with none ignored. v1 remains the live server path. ### M0 incremental demo @@ -415,12 +415,12 @@ Residual approximations, documented rather than special-cased: The `M3`-`M7` stage of the roadmap is implemented to the extent recorded below. The goal ran for 90 rounds and landed 123 commits (`8c42f2d..c9a074b`); the -workspace suite is at 814 tests. +workspace suite is at 816 tests. | Milestone | Evidence | | --- | --- | | M3 `\halign` | shared column widths, `l`/`c`/`r`/`p{width}` with wrapped cells, `\tabskip`, `@{}`/`@{\hspace{...}}`, booktabs rule weights and partial spans, `\cline`, `\noalign{\vskip}`, `\multicolumn`, longtable heads/feet, `*{n}{cols}`, vertical `|` rules, optional position/bracket arguments, row `\\[dim]` gaps, LaTeX `tabular`/`longtable` capture, and page splitting that keeps column geometry. | -| M4 math | `cases`, `matrix`/`pmatrix`/`bmatrix`/`Bmatrix`/`vmatrix`/`Vmatrix` and `array` environments laid out as two-dimensional grids with sized delimiters; Computer Modern math metrics (cmmi/cmsy/cmex/msbm/eufm) embedded as Type1 outlines, TeX's 3/4/5mu class table, `\mid`/`\colon`, `\mskip`-family dimension scans, `\frac` and infix fraction forms, `\left`/`\right`/`\middle` and `\big` CMEX sizing, `align`/`gather`/`alignat` row layout with per-row tags, `split` blocks numbered once and `multline` edge alignment, equation numbering with `\eqref`/`\ref`/`\tag`/`\notag`, `cases` with `&`-separated cells, matrix delimiters and `array` column specs, math alphabets (`\mathbf`/`\mathit`/`\mathsf`/`\mathtt`/`\mathcal`/`\mathbb`/`\mathfrak`) and wide-display line splitting. | +| M4 math | `cases`, `matrix`/`pmatrix`/`bmatrix`/`Bmatrix`/`vmatrix`/`Vmatrix` and `array` environments laid out as two-dimensional grids with sized delimiters; Computer Modern math metrics (cmmi/cmsy/cmex/msbm/eufm) embedded as Type1 outlines, TeX's 3/4/5mu class table, `\mid`/`\colon`, `\mskip`-family dimension scans, `\frac` and infix fraction forms, `\left`/`\right`/`\middle` and `\big` CMEX sizing, `align`/`gather`/`alignat` row layout with per-row tags, `split` blocks numbered once and `multline` edge alignment, equation numbering with `\eqref`/`\ref`/`\tag`/`\notag`, `cases` with `&`-separated cells, matrix delimiters and `array` column specs (matrix rows advance 12pt and cases 14.4pt, matching amsmath's `\arraystretch`, and pmatrix/cases word positions are checked against pdfLaTeX within 1pt), math alphabets (`\mathbf`/`\mathit`/`\mathsf`/`\mathtt`/`\mathcal`/`\mathbb`/`\mathfrak`) and wide-display line splitting. | | M5 fonts | twelve Computer Modern text programs (roman/bold/italic/bold-italic/mono/sans/sans-bold/sans-italic/small-caps/slanted/bold-slanted/mono-italic) plus four math programs, all embedded as Type1 with TFM widths; NFSS declarations, legacy switches, paragraph/inline runs with relative composition, per-run base sizes, superscripts/subscripts, accent composition, case commands, per-glyph Liberation fallback and Type1 ToUnicode CMaps. | | M6 class execution | article size options and `\linespread`, title/author/date and `\maketitle`, five-level sectioning with counters, TOC and float lists with page numbers and dot leaders, floats and in-text graphics with `\includegraphics` sizing/`\graphicspath`, footnote insertions, `thebibliography`/`\cite`, theorem environments and `\newtheorem`, nested lists with article skips and hanging indents, `quotation`/`quote`/`verse`, `minipage`, `\today`, page numbering, label/counter renaming, and preamble macro execution (`\newcommand`/`\def`/`\let`/`\newenvironment`/`\newif`/`\newlength`/`\newcounter`). Project `.cls`/`.sty` files are inlined with `\DeclareOption`/`\ProcessOptions`/`\ExecuteOptions`, `\LoadClass` inheritance, recursive `\RequirePackage`, local `\input`, `\AtBeginDocument` hooks and `\PassOptionsToClass`/`\PassOptionsToPackage`. | | M7 service | route-D preview/PDF/edit endpoints and the `?engine=route-d` project switch, `TEXRRA_ENGINE` default, memoised project previews/PDFs (source and image bytes in the key), flat endpoint caches with FIFO eviction and concurrency coverage, JSON 422 errors, PDF `/Link` annotations from `\href`, per-glyph Unicode extraction, and a `warnings` array in preview JSON that reports unsupported environments and control words that survived layout instead of failing silently. |