diff --git a/README.md b/README.md index da8c011..6edf223 100644 --- a/README.md +++ b/README.md @@ -583,7 +583,9 @@ execution, service and incrementality targets) is in The first M7 service integration is available as `POST /api/route-d/preview`, with PDF export at `POST /api/route-d/pdf`. It accepts blank-line-separated source with a small `\section`/`\textbf`/`\emph`/display-math/list subset, lays it out with the route-D page builder, and returns the v1-compatible preview shape plus per-page hashes and -SVG. Route-D paragraphs are laid out with CMR10 advances, kerns and ligatures; runs of two or three hyphens become en/em dashes, the breaker follows TeX's `\pretolerance`/`\tolerance`/`\emergencystretch` passes with demerits (falling back to TeX's overfull fill when no feasible break exists), and the PDF `/W` array reports the same advances, so extracted text keeps word boundaries. Non-final lines bake their justification into the glue widths, so the PDF and the SVG preview are flush to the measure instead of showing natural spaces. Interline spacing follows TeX (`\baselineskip` unless `\lineskiplimit` forces `\lineskip`), and `Document::par_skip` adds `\parskip` between paragraph units. `page::PageBuilder` selects page breaks by TeX's badness-plus-penalty cost, including glue setting, `\topskip` and `Document::max_depth` (`\maxdepth`), and breaks ties toward the page closest to the goal; `Engine::layout_paged` exposes it for documents whose units are single vertical items, while the scrolling builder remains the default until floats, insertions and incremental replay gain paged equivalents. Embedded text fonts are subset per document to the glyphs actually used (retaining glyph IDs and composite components), and each subset carries a ToUnicode CMap covering its used characters. `Document::insertion_classes` caps each insertion class to a page fraction and defers overflow to the next page, 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. +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 +page body through `pdf::PageOrigin`, leaving the sheet size unchanged. +`Document::insertion_classes` caps each insertion class to a page fraction and defers overflow to the next page, and `InsertionClass::multiplier` applies TeX's `\count` reserve factor; `Document::insertion_skip` models `\skip\footins` once per page before the first insertion class, and `InsertionClass::skip` overrides it for one class. The v1 `/preview` and project APIs are unchanged and remain the default. Project previews can opt into the new core with `POST /api/projects/{id}/preview?engine=route-d`; the same project preview without the query keeps the v1 pipeline. The web client exposes this as the `引擎: v1` / `引擎: Route-D` toggle in the preview toolbar; the choice is stored in `localStorage` and switches both the preview request and `POST /api/projects/{id}/pdf`, since the PDF handler honors the same `engine=route-d` query. Route-D project previews keep a session, so an unchanged source reports zero recomputed pages; text edits and structural edits with an unchanged paragraph prefix rebuild from the first difference through `Engine::relayout_from`, reusing the sealed pages before it, while edits without a reusable prefix fall back to a full layout. `POST /api/route-d/edit/{unit}` applies one paragraph edit to the last route-D document and returns the same page list plus `changedPages` and diff --git a/crates/texrra-tex-core/src/lib.rs b/crates/texrra-tex-core/src/lib.rs index 46bd068..13c9c39 100644 --- a/crates/texrra-tex-core/src/lib.rs +++ b/crates/texrra-tex-core/src/lib.rs @@ -615,6 +615,12 @@ pub struct Document { /// TeX `\parskip`: vertical glue inserted between paragraphs. #[serde(default)] pub par_skip: i64, + /// Extra horizontal displacement of the page origin (`\hoffset`). + #[serde(default)] + pub h_offset: i64, + /// Extra vertical displacement of the page origin (`\voffset`). + #[serde(default)] + pub v_offset: i64, } fn default_text_fraction() -> u8 { @@ -673,6 +679,8 @@ impl Document { text_float_sep: default_text_float_sep(), in_text_sep: default_in_text_sep(), par_skip: 0, + h_offset: 0, + v_offset: 0, } } diff --git a/crates/texrra-tex-core/src/pdf.rs b/crates/texrra-tex-core/src/pdf.rs index b9bd8b1..644b2bf 100755 --- a/crates/texrra-tex-core/src/pdf.rs +++ b/crates/texrra-tex-core/src/pdf.rs @@ -235,13 +235,28 @@ fn font_resource(font: FontFace) -> &'static str { } } +/// TeX page origin offsets (`\hoffset`, `\voffset`) in scaled points. +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] +pub struct PageOrigin { + pub h_offset: i64, + pub v_offset: i64, +} + fn page_content( list: &DisplayList, height: i64, image_names: &BTreeMap, faces: &'static [PdfFace; 6], + origin: PageOrigin, ) -> String { let mut content = String::from("q\n0 0 0 rg\n"); + if origin != PageOrigin::default() { + content.push_str(&format!( + "1 0 0 1 {} {} cm\n", + pt(origin.h_offset), + pt(-origin.v_offset) + )); + } for item in &list.items { match item { DisplayItem::Text { @@ -318,8 +333,18 @@ fn page_content( content } -/// Write several display lists as a multi-page PDF. +/// Write several display lists as a multi-page PDF at the default page origin. pub fn display_lists_to_pdf(pages: &[DisplayList], page_height: i64) -> Vec { + display_lists_to_pdf_with_origin(pages, page_height, PageOrigin::default()) +} + +/// Write several display lists as a multi-page PDF, translating the page body +/// by TeX page origin offsets. +pub fn display_lists_to_pdf_with_origin( + pages: &[DisplayList], + page_height: i64, + origin: PageOrigin, +) -> Vec { let height = page_height.max(792 * 65_536); let width = pages .iter() @@ -473,7 +498,7 @@ pub fn display_lists_to_pdf(pages: &[DisplayList], page_height: i64) -> Vec for (index, slot) in &used { names.insert(*index, format!("Im{slot}")); } - let content = page_content(list, height, &names, faces); + let content = page_content(list, height, &names, faces, origin); objects.push( format!( "<< /Length {} >>\nstream\n{}endstream", diff --git a/crates/texrra-tex-core/tests/route_d.rs b/crates/texrra-tex-core/tests/route_d.rs index de160e3..beae062 100755 --- a/crates/texrra-tex-core/tests/route_d.rs +++ b/crates/texrra-tex-core/tests/route_d.rs @@ -2,8 +2,9 @@ //! incremental paragraph edit. use texrra_tex_core::{ - Document, Engine, ParagraphFont, ParagraphStyle, Unit, cmr10::Cmr10Metrics, - pdf::display_lists_to_pdf, + Document, Engine, ParagraphFont, ParagraphStyle, Unit, + cmr10::Cmr10Metrics, + pdf::{PageOrigin, display_lists_to_pdf, display_lists_to_pdf_with_origin}, }; /// Paragraph style in TeX scaled points, driven by the CMR10 font metrics. @@ -779,3 +780,88 @@ fn route_d_multiline_bands_track_pdftex() { } let _ = std::fs::remove_dir_all(&root); } + +/// TeX `\hoffset`/`\voffset` translate the page body without moving the sheet. +#[test] +fn page_origin_offsets_move_the_page_body() { + use std::path::Path; + use std::process::Command; + + fn has(command: &str, version_arg: &str) -> bool { + Command::new(command) + .arg(version_arg) + .stdout(std::process::Stdio::null()) + .stderr(std::process::Stdio::null()) + .status() + .is_ok_and(|status| status.success()) + } + if !has("pdftotext", "-v") { + return; + } + + fn word_xy(pdf: &Path, out: &Path) -> (f64, f64) { + let status = Command::new("pdftotext") + .arg("-bbox") + .arg(pdf) + .arg(out) + .status() + .expect("pdftotext"); + assert!(status.success(), "pdftotext failed for {}", pdf.display()); + let xml = std::fs::read_to_string(out).expect("read bbox xml"); + let rest = &xml[xml.find("xMin=").expect("xMin")..]; + let number = |key: &str| -> f64 { + let at = rest.find(key).expect(key) + key.len(); + let tail = &rest[at..]; + let end = tail.find('"').expect("quote"); + tail[..end].parse().expect("bbox number") + }; + (number("xMin=\""), number("yMin=\"")) + } + + let document = Document::new( + 600 * 65_536, + vec![Unit::paragraph_with_style_and_face( + 0, + "Origin", + body_style(), + ParagraphFont::Roman, + )], + ); + let engine = Engine::layout(&document); + let mut list = engine.pages()[0].display_list(); + list.width = list.width.max(612 * 65_536); + list.height = list.height.max(792 * 65_536); + let pages = std::slice::from_ref(&list); + + let root = std::env::temp_dir().join(format!("texrra-origin-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&root); + std::fs::create_dir_all(&root).expect("create origin dir"); + let plain = root.join("plain.pdf"); + let moved = root.join("moved.pdf"); + std::fs::write(&plain, display_lists_to_pdf(pages, 792 * 65_536)).expect("write plain pdf"); + std::fs::write( + &moved, + display_lists_to_pdf_with_origin( + pages, + 792 * 65_536, + PageOrigin { + h_offset: 10 * 65_536, + v_offset: 20 * 65_536, + }, + ), + ) + .expect("write moved pdf"); + + let (plain_x, plain_y) = word_xy(&plain, &root.join("plain.html")); + let (moved_x, moved_y) = word_xy(&moved, &root.join("moved.html")); + assert!( + (moved_x - plain_x - 10.0).abs() < 0.6, + "hoffset moved x by {}", + moved_x - plain_x + ); + assert!( + (moved_y - plain_y - 20.0).abs() < 0.6, + "voffset moved y by {}", + moved_y - plain_y + ); +} diff --git a/docs/ROUTE_D_PLAN.md b/docs/ROUTE_D_PLAN.md index bd4904e..925377b 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`). 315 workspace tests are green and no oracle +PDF opt-in with `?engine=route-d`). 316 workspace tests are green and no oracle fixture is ignored. Known gaps, in dependency order: @@ -248,10 +248,13 @@ penalty-driven earlier breaks, `\topskip`, `\maxdepth` and marks. `Engine::layout_paged` now feeds it every document whose units are single vertical items (`Document::max_depth` supplies `\maxdepth`) and materialises the chosen fragments as hashed pages; ties go to the breakpoint closest to the page -goal, so overfull pages take the least overfull break. 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 -`\voffset`, insertion registers and the interpreted `\output`. +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`. 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, held-over insertion +material and the interpreted `\output`. Acceptance: 10 page fixtures (article text, footnotes, floats, forced breaks); page counts identical and first/last baselines within 1pt of pdfLaTeX. diff --git a/docs/TEX_CORE.md b/docs/TEX_CORE.md index a32ef90..c4f7937 100755 --- a/docs/TEX_CORE.md +++ b/docs/TEX_CORE.md @@ -304,7 +304,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. 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 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. `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`. Floats, insertions 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. @@ -312,7 +312,7 @@ Math coverage includes fractions/roots, scripts, `\left...\right` with body-scal Paragraph units carry a `ParagraphFont`; `Unit::paragraph_with_face` and `Unit::paragraph_with_style_and_face` select Roman, bold, italic, mono, or sans. The corresponding Computer Modern TFM (`cmr10`, `cmbx10`, `cmti10`, `cmbxti10`, `cmtt10`, `cmss10`) supplies advances, kerns, ligatures, and italic correction for layout, while the display list and PDF select the matching Liberation face. `Engine::edit` preserves the face when reflowing an edited paragraph. -The crate currently has 204 unit tests plus six route-D integration tests and eight oracle fixtures. Workspace verification: `cargo fmt --all -- --check`; `cargo test --workspace --offline` runs 315 tests (204 route-D unit, 6 route-D integration, 8 oracle, 71 v1 integration, 19 server, 4 v1 unit, 1 core unit, 2 binary units), with none ignored. v1 remains the live server path. +The crate currently has 204 unit tests plus seven route-D integration tests and eight oracle fixtures. Workspace verification: `cargo fmt --all -- --check`; `cargo test --workspace --offline` runs 316 tests (204 route-D unit, 7 route-D integration, 8 oracle, 71 v1 integration, 19 server, 4 v1 unit, 1 core unit, 2 binary units), with none ignored. v1 remains the live server path. ### M0 incremental demo @@ -350,9 +350,9 @@ deliberately open rather than approximated: 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; `\voffset`, insertion - registers (`\count`/`\dimen`/`\skip` per class) and an interpreted - `\output` remain open. + paged equivalent before it can become the default; paper margins, held-over + insertion material 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 math limit policies are only partially modeled; `OutputRoutine::wants_break` can force a page break between units, and insertion material is stacked by class from the page bottom; `\output` is still Rust code rather than interpreted tokens. diff --git a/src/route_d.rs b/src/route_d.rs index 2984809..07bd7b3 100755 --- a/src/route_d.rs +++ b/src/route_d.rs @@ -11,7 +11,7 @@ use std::sync::{Mutex, OnceLock}; use texrra_tex_core::cmr10::Cmr10Metrics; use texrra_tex_core::math::parse_math; -use texrra_tex_core::pdf::display_lists_to_pdf; +use texrra_tex_core::pdf::{PageOrigin, display_lists_to_pdf_with_origin}; use texrra_tex_core::{Document, Engine, ParagraphFont, ParagraphStyle, Unit, VerticalItem}; const SCALE: i64 = 65_536; @@ -112,7 +112,14 @@ pub fn pdf_bytes(source: &str) -> Result, String> { list }) .collect(); - Ok(display_lists_to_pdf(&pages, PAGE_HEIGHT_PT)) + Ok(display_lists_to_pdf_with_origin( + &pages, + PAGE_HEIGHT_PT, + PageOrigin { + h_offset: document.h_offset, + v_offset: document.v_offset, + }, + )) } /// Apply one paragraph edit to the last route-D document and report page