From 30f1df03cad31136783531873a7a096aeda07c8f Mon Sep 17 00:00:00 2001 From: GloamXun Date: Tue, 27 Oct 2026 20:55:51 +0800 Subject: [PATCH] Fix PDF page origin and add the fidelity/latency roadmap The PDF writer received the raw geometry origin instead of the document's effective offsets, so PDFs started at x=0 and clipped running headers above the page even though the preview looked shifted. PDF output now uses the same h_offset/v_offset as the preview. For a geometry document with a 6.5in measure this restores the 1in text block; the arXiv template's page-2/3 headers ("arXiv Template", "A Preprint") now appear. A regression test checks the centred text block. Add docs/TEX_FIDELITY_ROADMAP.md: page-frame/class/font/citation/math fidelity workstreams, incremental revision/patch protocol, milestones and the <100ms warm preview target. Test count is 1070 (433 engine). --- docs/ROUTE_D_PLAN.md | 2 +- docs/ROUTE_D_STATUS.md | 6 +- docs/TEX_CORE.md | 4 +- docs/TEX_FIDELITY_ROADMAP.md | 159 +++++++++++++++++++++++++++++++++ docs/WEB_ROUTE_D_EXPERIMENT.md | 12 ++- src/route_d.rs | 24 ++++- 6 files changed, 197 insertions(+), 10 deletions(-) create mode 100644 docs/TEX_FIDELITY_ROADMAP.md diff --git a/docs/ROUTE_D_PLAN.md b/docs/ROUTE_D_PLAN.md index 1d5a462..c29bd6a 100644 --- a/docs/ROUTE_D_PLAN.md +++ b/docs/ROUTE_D_PLAN.md @@ -51,7 +51,7 @@ floats (`\floatsep`, `\textfloatsep`, `\intextsep`, `\topfraction`, 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`; flat `/preview` and project previews now -prefer route-D with a v1 fallback). 1069 workspace tests are green and no oracle +prefer route-D with a v1 fallback). 1070 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/ROUTE_D_STATUS.md b/docs/ROUTE_D_STATUS.md index 197c2b3..503efa4 100755 --- a/docs/ROUTE_D_STATUS.md +++ b/docs/ROUTE_D_STATUS.md @@ -16,12 +16,12 @@ cargo test --workspace --offline or run `./scripts/verify-route-d.sh`, which executes both. -The workspace currently passes **1069 tests**: +The workspace currently passes **1070 tests**: | Suite | Tests | | --- | --- | | route-D unit (engine) | 444 | -| engine binary unit | 432 | +| engine binary unit | 433 | | server integration | 65 | | v1 integration | 71 | | pdfLaTeX oracle | 42 | @@ -29,7 +29,7 @@ The workspace currently passes **1069 tests**: | engine/core unit | 4 + 1 | Latest full run (web trial increment): `./scripts/verify-route-d.sh` passes -with fmt clean and **1069 tests** green. +with fmt clean and **1070 tests** green. Latest live check (2026-10-27): the debug server served `examples/hello.tex` from `target/debug/texrra serve`; `POST /preview` answered 200 with diff --git a/docs/TEX_CORE.md b/docs/TEX_CORE.md index 5a2ed2e..093f021 100755 --- a/docs/TEX_CORE.md +++ b/docs/TEX_CORE.md @@ -370,7 +370,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 444 unit tests plus ten route-D integration tests and forty-two oracle fixtures. Workspace verification: `cargo fmt --all -- --check`; `cargo test --workspace --offline` runs 1069 tests (444 core unit, 432 engine binary unit, 10 route-D integration, 42 oracle, 71 v1 integration, 65 server, 4 engine unit, 1 core unit), with none ignored. The flat `/preview` endpoint and the project preview/PDF endpoints now try route-D first and fall back to v1 on error (`?engine=v1` or `TEXRRA_ENGINE=v1` forces v1; flat and project responses carry `X-Preview-Engine`, naming the engine used). A geometry-less project now defaults to Letter, matching pdfLaTeX, where the old v1 path used A4. +The crate currently has 444 unit tests plus ten route-D integration tests and forty-two oracle fixtures. Workspace verification: `cargo fmt --all -- --check`; `cargo test --workspace --offline` runs 1070 tests (444 core unit, 433 engine binary unit, 10 route-D integration, 42 oracle, 71 v1 integration, 65 server, 4 engine unit, 1 core unit), with none ignored. The flat `/preview` endpoint and the project preview/PDF endpoints now try route-D first and fall back to v1 on error (`?engine=v1` or `TEXRRA_ENGINE=v1` forces v1; flat and project responses carry `X-Preview-Engine`, naming the engine used). A geometry-less project now defaults to Letter, matching pdfLaTeX, where the old v1 path used A4. ### M0 incremental demo @@ -524,7 +524,7 @@ deliberately open rather than approximated: ## Limits and remaining gaps -The suite currently stands at 1069 passing tests, with the workspace clean. +The suite currently stands at 1070 passing tests, with the workspace clean. Route-D serves both flat `/preview` and project preview/PDF requests by default (automatic v1 fallback; `?engine=v1` or `TEXRRA_ENGINE=v1` opts out). The objective's areas are implemented to the limits below; complex-script shaping is diff --git a/docs/TEX_FIDELITY_ROADMAP.md b/docs/TEX_FIDELITY_ROADMAP.md new file mode 100644 index 0000000..2caaf8e --- /dev/null +++ b/docs/TEX_FIDELITY_ROADMAP.md @@ -0,0 +1,159 @@ +# Route-D fidelity and incremental-preview roadmap + +Status: active goal, started 2026-10-27. The target is a route-D that produces +TeX-compatible output for the supported article/arXiv subset **and** keeps a +Typst-like edit-to-preview loop. These are separate workstreams that must be +measured together: fidelity work can easily make preview latency worse. + +## Definition of done + +For a curated corpus of article/arXiv projects: + +1. PDF fidelity + - page count matches TeX Live; + - text-block origin, measure, headers/footers and page numbers match within + a small tolerance; + - title, author block, section style, citations/references, floats, tables + and display math are visually recognisable as the TeX output; + - a per-page image-diff report is checked into the test harness, with known + exceptions listed explicitly. +2. Incremental preview + - warm edit-to-preview p95 under 100 ms for documents up to 10 pages; + - only changed pages are transferred and re-rendered on the client; + - a full PDF can continue in the background without blocking preview; + - typing does not wait for a 450 ms save timer. +3. Honest grading + - every unsupported construct produces a warning or a documented exception; + - no project silently loses a column, citation or figure. + +The supported subset is explicit: article/report/arXiv-style papers that use the +engine's class, list, table, float, citation and math subset. Arbitrary LaTeX +execution is not a goal. + +## Current baseline (2026-10-27) + +- Both engines produce 3 pages for the uploaded arXiv template. +- Route-D content is present: tables, basic BibTeX references, citations, + headers and page numbers now render. +- Page frame was just fixed: PDF page origin now honours the document's + horizontal/vertical offsets, so a `geometry` document gets its centred + 6.5in text block and page-2/page-3 headers instead of content at x=0. +- Still visibly different from TeX: + - body face is CMR/fallback, not Times from `\rmdefault{ptm}`; + - title/author block, small caps and rules are simplified; + - reference style is numeric, not natbib author-year; + - display math is approximate; + - `\fbox`/rule figures, vector images and float placement differ. +- Incremental foundation exists: + - `Engine::edit` + page hashes; + - project-scoped sessions and changed-page reporting; + - web `applyPages` skips pages whose hash is unchanged; + - a 90 ms preview debounce and 450 ms save debounce. +- Incremental bottlenecks: + - the server still returns every page's SVG JSON; + - the browser downloads all pages before hash-skipping; + - project edits wait for the save timer before preview; + - the arxiv project's preview/layout is still in the 1.4–1.5 s range; + - no WebSocket/SSE stream or dirty-page patch protocol. + +## Architecture + +### Fidelity layers + +- **F1 — Page frame**: paper size, text-block origin (left/top), headers, + footers, page numbers, running marks. The route-D PDF and preview must share + the exact same origin. +- **F2 — Class styles**: `\maketitle`, title/author/date blocks, section and + caption styles, abstract, keywords. Parse the class's declarations rather + than special-casing a single template. +- **F3 — Fonts and metrics**: TeX TFM-compatible widths/kerns/ligatures for + Computer Modern and Times (`ptm`), then line breaking uses the correct + measures. A font metric provider must be independent of the PDF backend. +- **F4 — Floats, tables, math**: float placement/order, booktabs and + multicolumn, real inline math in table cells, display-math layout. +- **F5 — Citations and references**: natbib author-year and numeric styles, + `.bib` field coverage, sorting and labels. + +### Incremental layers + +- **I1 — Revisions and stable IDs**: each block gets a stable source range/ID; + an edit produces a revision with a minimal changed range, not a new string + compared by prefix. +- **I2 — Incremental parse**: reparse only affected blocks, preserving + unchanged block IR. Then relayout only pages whose dependency set changed. +- **I3 — Patch protocol**: a persistent WebSocket/SSE channel sends + `{revision, changedPages:[{index, hash, svg}], removedPages, pageCount, + durationMs, warnings}`. The client patches those pages only. +- **I4 — Preview without disk round-trip**: the editor sends its buffer and + revision; the server compiles the buffer, while a background job writes the + file and builds the full PDF. Cancellation is keyed by revision. + +## Milestones + +### M1 — Page frame and class title/author (fidelity) + +Acceptance: + +- geometry documents have the same text-block origin as TeX within 1 pt; +- page 2/3 headers and page numbers appear at the TeX positions; +- title/author/date block gets its own line structure and vertical spacing; +- a regression test compares PDF text coordinates and preview coordinates. + +### M2 — Times metrics and section styles + +Acceptance: + +- `\rmdefault{ptm}` selects Times-compatible metrics for text and line breaks; +- section/subsection sizes and spacing follow the class declarations; +- line-break differences against TeX drop measurably on the article corpus. + +### M3 — Citations, floats and table math + +Acceptance: + +- natbib author-year output for the arXiv sample, plus numeric mode; +- floats land on the same page as TeX for the corpus, or a warning explains + why they cannot; +- table cells typeset inline math instead of the ASCII fallback; +- `\fbox`/rule figure bodies draw a frame. + +### M4 — Incremental protocol + +Acceptance: + +- WebSocket/SSE revision stream with page patches; +- warm p95 edit-to-preview <100 ms for a 10-page document; +- typing does not wait for disk save; +- full PDF compilation continues in the background; +- aborted revisions never paint stale pages. + +### M5 — Fidelity/latency harness in CI + +Acceptance: + +- TeX Live compiles the corpus in CI (or a pinned docker image); +- route-D PDFs are rasterised and diffed page-by-page; +- preview latency percentiles are recorded per commit; +- the dashboard reports both fidelity and speed, so one cannot regress silently. + +## Immediate next steps + +1. Finish M1: title/author block and a coordinate regression harness. The page + frame fix is already in the working tree. +2. Add Times TFM metrics (M2) before touching math, because line breaking and + page breaks depend on the correct font metrics. +3. Build the patch protocol (M4) in parallel with fidelity work; it is mostly + server/web plumbing and does not depend on the math engine. +4. Keep the TeX Live comparison PDF and the generated reference images as the + visual oracle for each milestone. + +## Risks and non-goals + +- Exact TeX parity for arbitrary packages is not feasible without executing + TeX. The roadmap targets a documented article/arXiv subset. +- Math typesetting is the largest single risk; a full TeX math engine may be a + separate project. +- Incremental layout must not be faked by caching the last response: stale + pages and revision races are correctness bugs. +- Do not trade fidelity for latency silently; every shortcut must be visible in + warnings and in the fidelity report. diff --git a/docs/WEB_ROUTE_D_EXPERIMENT.md b/docs/WEB_ROUTE_D_EXPERIMENT.md index 141b5c1..15c322d 100644 --- a/docs/WEB_ROUTE_D_EXPERIMENT.md +++ b/docs/WEB_ROUTE_D_EXPERIMENT.md @@ -46,7 +46,7 @@ now means route-D. | Area | Route-D | Evidence / impact | | --- | --- | --- | -| Article/report basics: title, sections, lists, TOC, page numbers | Supported | corpus and 1069-test suite | +| Article/report basics: title, sections, lists, TOC, page numbers | Supported | corpus and 1070-test suite | | Inline/display math, equations, tags, cleveref | Supported | math tests, oracle fixtures | | Floats, captions, tables, booktabs | Supported | table/math tests, corpus | | PNG/JPEG/BMP `\includegraphics` | Supported | project image tests | @@ -137,8 +137,8 @@ PDF was rendered page-by-page next to the route-D output. | --- | --- | --- | | Page count / paper | 3 pages, letter | 3 pages, letter | | Typeface | Times (`ptm`, arxiv.sty) | Computer Modern / Liberation fallback | -| Text block | 1in left/right margins, 6.5in measure | starts at x=0 with a 6.67in measure | -| Running header | `arxiv Template` / `A PREPRINT` | absent | +| Text block | 1in left/right margins, 6.5in measure | 1in margins and 6.5in measure after the page-origin fix; body face still differs | +| Running header | `arxiv Template` / `A PREPRINT` | `arXiv Template` / `A Preprint` on pages 2–3; small-caps styling differs | | Title | `A TEMPLATE FOR THE arxiv STYLE`, small caps, rules above/below | normal case, no rules | | Author block | two affiliations, ORCID icons, footnote symbols | one concatenated paragraph, no ORCID | | Abstract/keywords | small-caps heading, bold `Keywords`, `·` separators | bold heading, comma separators | @@ -149,6 +149,12 @@ PDF was rendered page-by-page next to the route-D output. | References | author-year, italic venue, DOI link | numeric `[1]`–`[3]`, plain venue text | | Float order | figure/table on page 3 with section 3.4 | figure/table float to page 2 top | +After this comparison, the PDF page origin was fixed: the PDF writer had +ignored the document's horizontal/vertical offsets, so route-D PDFs started at +x=0 and clipped headers above the page. The revised PDF now has the 1in text +block and page 2/3 headers. Title vertical spacing, Times metrics, author +blocks, citation style, math and float placement still differ. + The visual difference is therefore not a single bug. Route-D models the document semantically and lays out paragraphs/tables/floats with its own page builder; it does not execute the LaTeX page builder, class styling, natbib diff --git a/src/route_d.rs b/src/route_d.rs index 12d1d7d..7777a67 100755 --- a/src/route_d.rs +++ b/src/route_d.rs @@ -156,6 +156,9 @@ struct PageGeometry { bottom_margin: Option, /// `\textwidth` / `\hsize` / `\linewidth`, in scaled points. line_width: Option, + /// The source uses the `geometry` package, so a text block with no explicit + /// `\hoffset` is centred between the paper edges. + geometry_package: bool, par_indent: Option, par_skip: Option, par_skip_stretch: Option, @@ -2325,6 +2328,7 @@ fn geometry_package_options(line: &str) -> Option { /// Apply the subset of the `geometry` package that route-D can honour. fn apply_geometry_package(geometry: &mut PageGeometry, options: &str) { + geometry.geometry_package = true; let paper_width = geometry.paper_width.unwrap_or(612 * SCALE); let paper_height = geometry.paper_height.unwrap_or(792 * SCALE); let mut left = None; @@ -7138,6 +7142,11 @@ fn renewcommand_length(line: &str, name: &str) -> Option { fn apply_geometry(document: &mut Document, geometry: &PageGeometry) { document.h_offset = geometry.origin.h_offset; + if geometry.geometry_package && document.h_offset == 0 { + let paper_width = geometry.paper_width.unwrap_or(612 * SCALE); + let line_width = geometry.line_width.unwrap_or(480 * SCALE); + document.h_offset = ((paper_width - line_width) / 2).max(0); + } // geometry's `top` places the text block below the sheet edge; the // display list and the PDF writer both honour the offset. document.v_offset = geometry.origin.v_offset + geometry.top_margin.unwrap_or(0); @@ -7629,11 +7638,15 @@ pub fn pdf_bytes_with_images( .and_then(|name| color_spec(name, &geometry.colors)) }, }; + let origin = PageOrigin { + h_offset: document.h_offset, + v_offset: document.v_offset, + }; Ok(display_lists_to_pdf_with_cm_type1_and_metadata( &pages, document.paper_width, document.paper_height, - geometry.origin, + origin, &metadata, )) } @@ -19358,6 +19371,15 @@ left & right \\ ); } + #[test] + fn geometry_centers_the_text_block_horizontally() { + let source = "\\documentclass{article}\n\\usepackage[letterpaper,textwidth=6.5in]{geometry}\n\\begin{document}\n\nText.\n\n\\end{document}\n"; + let json = preview_json(source).expect("preview"); + let texts = svg_texts(&json); + let (_, x, _) = texts.iter().find(|(text, _, _)| text == "T").expect("text"); + assert!((*x - 72.0).abs() < 1.0, "text starts at {x}pt"); + } + #[test] fn geometry_top_margin_offsets_the_page_body() { let first_y = |json: &str| -> f64 {