From 875f8a76002a3ac7c99f3cd1effcd80c644940da Mon Sep 17 00:00:00 2001 From: GloamXun Date: Tue, 20 Oct 2026 21:15:35 +0800 Subject: [PATCH] Expose route-D pages through a preview endpoint --- Cargo.lock | 1 + Cargo.toml | 1 + README.md | 5 ++ crates/texrra-tex-core/src/render.rs | 4 ++ docs/TEX_CORE.md | 11 ++-- src/main.rs | 22 +++++++ src/route_d.rs | 91 ++++++++++++++++++++++++++++ tests/server.rs | 21 +++++++ 8 files changed, 151 insertions(+), 5 deletions(-) create mode 100755 src/route_d.rs diff --git a/Cargo.lock b/Cargo.lock index bd1beaf..125ae9e 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -957,6 +957,7 @@ dependencies = [ "texlang-common", "texlang-stdlib", "texrra-core", + "texrra-tex-core", "tiny_http", "ttf-parser", ] diff --git a/Cargo.toml b/Cargo.toml index 78af036..f1289f1 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -15,6 +15,7 @@ members = ["crates/texrra-core", "crates/texrra-tex-core"] [dependencies] texrra-core = { path = "crates/texrra-core", features = ["serde"] } +texrra-tex-core = { path = "crates/texrra-tex-core" } flate2 = "1.1" hyphenate = { path = "vendor/hyphenate" } genpdf = { version = "0.2.0", features = ["images"] } diff --git a/README.md b/README.md index 73dc542..bc33303 100644 --- a/README.md +++ b/README.md @@ -562,3 +562,8 @@ boxes/glue, a simple page builder, serializable checkpoints and a page-local edit demo. M1 adds the horizontal box/glue/penalty model, an item-stream Knuth-Plass-style paragraph builder, CMR10 metrics extracted from `cmr10.tfm`, and a matching pdfTeX line-break fixture. The production v1 engine remains the default until the new core reaches layout parity. See `docs/TEX_CORE.md`. + +The first M7 service integration is available as `POST /api/route-d/preview`. +It accepts blank-line-separated plain text, lays it out with the route-D page +builder, and returns the v1-compatible preview shape plus per-page hashes and +SVG. The v1 `/preview` and project APIs are unchanged and remain the default. diff --git a/crates/texrra-tex-core/src/render.rs b/crates/texrra-tex-core/src/render.rs index 4e22998..dcb5e27 100755 --- a/crates/texrra-tex-core/src/render.rs +++ b/crates/texrra-tex-core/src/render.rs @@ -323,6 +323,8 @@ impl Page { VerticalItem::Halign(halign) => halign.width, VerticalItem::Rule { width, .. } => *width, VerticalItem::Box(box_) => box_.width, + VerticalItem::Paragraph(paragraph) => paragraph.width, + VerticalItem::Math { width, .. } => *width, _ => 0, }) .max() @@ -471,6 +473,8 @@ impl Page { .map(|item| match item { VerticalItem::Halign(halign) => halign.width, VerticalItem::Rule { width, .. } => *width, + VerticalItem::Paragraph(paragraph) => paragraph.width, + VerticalItem::Math { width, .. } => *width, _ => 0, }) .max() diff --git a/docs/TEX_CORE.md b/docs/TEX_CORE.md index 003d699..55d34e9 100755 --- a/docs/TEX_CORE.md +++ b/docs/TEX_CORE.md @@ -232,7 +232,7 @@ for a later overlaid slash. | 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; all five text faces embed Liberation Serif/Mono as Type0 CID fonts with Identity-H, ToUnicode and `/W` glyph widths; no Base-14 dependency; SVG carries family/weight/style | | M6 specials/XObject | partial | raw specials, RGB image XObjects, URI link annotations; class/package execution absent | -| M7 incremental integration | partial | edit replay + page hashes, not wired into v1 preview | +| M7 incremental integration | partial | route-D plain-text preview endpoint with page hashes; editor integration pending | v1 remains the production renderer; the route-D core is additive and tested independently. @@ -262,7 +262,7 @@ M3 (partial): `Unit::halign` normalizes column widths, intercolumn gaps, row hei Math coverage includes fractions/roots, scripts, `\left...\right` with body-scaled delimiters, `\middle`, `\big`/`\Big`/`\bigg`/`\Bigg` and their `l`/`r` forms, control-sequence delimiters, accents (dot/check/breve/acute/grave/ring), `\text`/`\mathrm`, `\overbrace`/`\underbrace`, `\overset`/`\underset`, `\binom`, `\cancel`/`\bcancel`/`\xcancel`, `\bmod`/`\pmod`, fence symbols, `\operatorname*` and `\mathop` limits. -The crate currently has 121 unit tests plus one route-D integration test. Workspace verification: `cargo fmt --all -- --check`; `cargo test --workspace --offline` runs 203 tests (122 route-D unit, 1 route-D integration, 71 v1 integration, 4 server, 4 v1 unit, 1 doctest). v1 remains the live server path. +The crate currently has 131 unit tests plus one route-D integration test. Workspace verification: `cargo fmt --all -- --check`; `cargo test --workspace --offline` runs 213 tests (131 route-D unit, 1 route-D integration, 71 v1 integration, 5 server, 4 v1 unit, 1 doctest). v1 remains the live server path. ### M0 incremental demo @@ -292,8 +292,9 @@ deliberately open rather than approximated: - **M5**: `cmr10.tfm` is parsed at runtime with widths, glyph heights/depths and kern pairs. all five text faces embed Liberation Serif/Mono as Type0/Identity-H with `/W` widths; ff/fi/fl/ffi/ffl ligatures come from TFM, but full NFSS family switching and italic correction are not implemented. - **M6**: `\output`, `\insert`, mark/float output policies, class-file execution and math limit policies are only partially modeled. -- **M7**: the route-D engine is not yet wired into the v1 live preview. The server - still uses the v1 semantic pipeline, and page-level checkpoints are exercised by - the route-D integration test only. +- **M7**: first service step is `POST /api/route-d/preview`, which lays out + blank-line-separated plain text and returns route-D pages with SVG and page + hashes. It is not yet the editor preview: LaTeX-to-route-D semantic mapping and + edit-diff reuse inside the project preview remain open. - `\middle` does not scale with its enclosing delimiter; math delimiters are scaled glyphs rather than TeX delimiter variants. diff --git a/src/main.rs b/src/main.rs index e89f69a..d9d4630 100644 --- a/src/main.rs +++ b/src/main.rs @@ -9,6 +9,7 @@ use std::{ use tiny_http::{Header, Method, Request, Response, Server, StatusCode}; mod projects; +mod route_d; use texrra_engine::rust_typeset; @@ -134,6 +135,27 @@ fn handle_request( None => respond(request, 404, "text/plain; charset=utf-8", "not found"), } } + (&Method::Post, "/api/route-d/preview") => { + let bytes = match read_body_bytes(&mut request, MAX_SOURCE_BYTES) { + Ok(bytes) => bytes, + Err(error) => return respond(request, 413, "text/plain; charset=utf-8", &error), + }; + let source = match String::from_utf8(bytes) { + Ok(source) => source, + Err(_) => { + return respond( + request, + 400, + "text/plain; charset=utf-8", + "source is not valid UTF-8", + ); + } + }; + match route_d::preview_json(&source) { + Ok(json) => respond(request, 200, "application/json; charset=utf-8", &json), + Err(error) => respond(request, 422, "application/json; charset=utf-8", &error), + } + } (&Method::Post, "/preview") => { let source = match read_and_save(&mut request, input_path) { Ok(source) => source, diff --git a/src/route_d.rs b/src/route_d.rs new file mode 100755 index 0000000..f0bb0b4 --- /dev/null +++ b/src/route_d.rs @@ -0,0 +1,91 @@ +//! Route-D preview endpoint: a small, independent TeX-style page pipeline. +//! +//! This is intentionally separate from the v1 `DocumentModel` preview. It +//! demonstrates checkpointed, page-hashed output from the route-D core. The +//! v1 preview remains the default and the fallback. + +use std::fmt::Write as _; + +use texrra_tex_core::{Document, Engine, ParagraphStyle, Unit}; + +const SCALE: i64 = 65_536; +const PAGE_HEIGHT_PT: i64 = 792; + +/// Build a JSON preview from blank-line-separated plain-text paragraphs. +/// +/// Each paragraph is a route-D unit, so `Engine` produces per-page checkpoints +/// and hashes. The response shape deliberately mirrors the useful parts of the +/// v1 preview without pretending to parse LaTeX yet. +pub fn preview_json(source: &str) -> Result { + let paragraphs: Vec<&str> = source + .split("\n\n") + .map(str::trim) + .filter(|paragraph| !paragraph.is_empty()) + .collect(); + if paragraphs.is_empty() { + return Err("route-D preview needs at least one paragraph".to_string()); + } + + let style = ParagraphStyle { + line_width: 480 * SCALE, + left_skip: 0, + right_skip: 0, + par_indent: 0, + line_height: 12 * SCALE, + char_width: 10 * SCALE, + space_width: 4 * SCALE, + space_stretch: 6 * SCALE, + space_shrink: 2 * SCALE, + }; + let units = paragraphs + .iter() + .enumerate() + .map(|(index, paragraph)| { + Unit::paragraph_with_style(index as u64, (*paragraph).to_string(), style.clone()) + }) + .collect(); + let document = Document::new(700 * SCALE, units); + let engine = Engine::layout(&document); + + let mut json = String::new(); + json.push_str("{\"status\":\"ok\",\"pageWidthMm\":215.90,\"pageHeightMm\":279.40,\"pages\":["); + let mut page_count = 0usize; + for page in engine.pages() { + let svg = page.display_list().to_svg(); + if page_count > 0 { + json.push(','); + } + write!( + json, + "{{\"index\":{page_count},\"hash\":\"{:016x}\",\"svg\":\"{}\"}}", + page.hash, + escape_json(&svg) + ) + .map_err(|error| error.to_string())?; + page_count += 1; + } + write!( + json, + "],\"pageCount\":{page_count},\"pageHeightPt\":{PAGE_HEIGHT_PT}}}" + ) + .map_err(|error| error.to_string())?; + Ok(json) +} + +fn escape_json(value: &str) -> String { + let mut escaped = String::with_capacity(value.len()); + for character in value.chars() { + match character { + '"' => escaped.push_str("\\\""), + '\\' => escaped.push_str("\\\\"), + '\n' => escaped.push_str("\\n"), + '\r' => escaped.push_str("\\r"), + '\t' => escaped.push_str("\\t"), + character if character < '\u{20}' => { + let _ = write!(escaped, "\\u{:04x}", character as u32); + } + character => escaped.push(character), + } + } + escaped +} diff --git a/tests/server.rs b/tests/server.rs index 39ab5f7..6637026 100644 --- a/tests/server.rs +++ b/tests/server.rs @@ -286,3 +286,24 @@ fn legacy_texrra_endpoint_renders_html_and_old_name_is_gone() { let old = server.request("POST", "/texcraft", source, "text/plain; charset=utf-8"); assert_eq!(old.status, 404); } + +#[test] +fn serves_route_d_preview_pages() { + let server = TestServer::start("route-d"); + let response = server.request( + "POST", + "/api/route-d/preview", + b"Hello route D + +Second paragraph", + "text/plain", + ); + assert_eq!(response.status, 200, "{}", response.text()); + let value: Value = serde_json::from_slice(&response.body).expect("route-D JSON"); + assert_eq!(value["status"], "ok"); + assert!(value["pageCount"].as_u64().unwrap() >= 1); + let svg = value["pages"][0]["svg"].as_str().unwrap(); + assert!(svg.contains("H")); + assert!(value["pages"][0]["hash"].as_str().unwrap().len() == 16); +}