diff --git a/README.md b/README.md index 794eccd..e65d50b 100644 --- a/README.md +++ b/README.md @@ -577,6 +577,6 @@ It accepts blank-line-separated source with a small `\section`/`\textbf`/`\emph` 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, and the PDF `/W` array reports the same advances, so extracted text keeps word boundaries. `Document::insertion_classes` caps each insertion class to a page fraction and defers overflow to the next page; `Document::insertion_skip` models `\skip\footins` once per page before the first insertion 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, and one or more paragraph edits return the changed/recomputed page set after replaying `Engine::edit` from the earliest changed paragraph. `POST /api/route-d/edit/{unit}` applies one paragraph edit to the last route-D +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 `recomputedPages`, exposing the checkpoint/page-hash diff from the core. diff --git a/crates/texrra-tex-core/src/lib.rs b/crates/texrra-tex-core/src/lib.rs index e5d022f..b34bd9a 100644 --- a/crates/texrra-tex-core/src/lib.rs +++ b/crates/texrra-tex-core/src/lib.rs @@ -1118,14 +1118,31 @@ impl Engine { return; }; next.units[unit_index] = Unit::paragraph_with_style(unit_id, source, style); + self.relayout_from(&next, unit_index); + } + /// Rebuild pages from the checkpoint before `start_index`, keeping every + /// sealed page before it. This generalizes `edit` to structural changes: + /// callers may add, remove or replace units at and after `start_index` as + /// long as the prefix is unchanged. + pub fn relayout_from(&mut self, document: &Document, start_index: usize) { + if start_index == 0 || start_index >= self.layout.checkpoints.len() { + self.layout = Self::layout(document).layout; + self.layout.recomputed_pages = self.layout.pages.len(); + self.layout.changed_pages = (0..self.layout.pages.len()).collect(); + return; + } + self.relayout_from_checkpoint(document, start_index); + } + + fn relayout_from_checkpoint(&mut self, next: &Document, start_index: usize) { let mut checkpoint = self.layout .checkpoints - .get(unit_index) + .get(start_index) .cloned() .unwrap_or(Checkpoint { - unit_index, + unit_index: start_index, page_index: 0, used: 0, page_items: Vec::new(), @@ -1134,7 +1151,7 @@ impl Engine { page_marks: Vec::new(), page_floats: Vec::new(), }); - let edited_height: i64 = next.units[unit_index] + let edited_height: i64 = next.units[start_index] .items .iter() .map(|item| match item { @@ -1167,9 +1184,9 @@ impl Engine { }; let mut used = checkpoint.used; let mut insertion_height = checkpoint.insertion_height; - let mut checkpoints = self.layout.checkpoints[..unit_index].to_vec(); + let mut checkpoints = self.layout.checkpoints[..start_index].to_vec(); - for (index, unit) in next.units.iter().enumerate().skip(unit_index) { + for (index, unit) in next.units.iter().enumerate().skip(start_index) { checkpoints.push(Checkpoint { unit_index: index, page_index: pages.len(), @@ -1193,7 +1210,7 @@ impl Engine { < next.float_page_fraction_percent as i64 * next.page_goal / 100 { pages.push(std::mem::replace(&mut current, Page::empty())); - used = document.top_skip; + used = next.top_skip; insertion_height = 0; } match item { @@ -1387,7 +1404,7 @@ impl Engine { current.floats.push(float.clone()); } else { pages.push(std::mem::replace(&mut current, Page::empty())); - used = document.top_skip; + used = next.top_skip; insertion_height = 0; current.floats.push(float.clone()); } @@ -1841,6 +1858,34 @@ mod tests { assert_eq!(layout.pages()[1].insertions.len(), 1); } + #[test] + fn relayout_from_keeps_the_unchanged_page_prefix() { + let first = Unit::paragraph(0, "alpha"); + let mut document = Document::new( + 20, + vec![ + first.clone(), + Unit::paragraph(1, "beta"), + Unit::paragraph(2, "gamma"), + ], + ); + let mut engine = Engine::layout(&document); + let prefix_hash = engine.pages()[0].hash; + document = Document::new( + 20, + vec![ + first, + Unit::paragraph(3, "inserted"), + Unit::paragraph(1, "beta changed"), + Unit::paragraph(2, "gamma"), + ], + ); + engine.relayout_from(&document, 1); + assert_eq!(engine.pages()[0].hash, prefix_hash); + assert!(engine.pages().len() >= 2); + assert!(engine.changed_pages().iter().all(|page| *page >= 1)); + } + #[test] fn incremental_layout_respects_insertion_class_limits() { let rule = VerticalItem::Rule { diff --git a/docs/TEX_CORE.md b/docs/TEX_CORE.md index b8e71ea..14863db 100755 --- a/docs/TEX_CORE.md +++ b/docs/TEX_CORE.md @@ -239,7 +239,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; text faces embed Liberation Serif/Mono as Type0 CID fonts with Identity-H, ToUnicode and width arrays; only faces used on a page are embedded, and ASCII documents use the 110-glyph minimal tier (one-page Roman PDF is about 21 KB); 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 | route-D preview/PDF/edit endpoints plus opt-in `?engine=route-d` project preview, content-based page hashes and section/emphasis/display-math/itemize/enumerate/description/quote/center/flushright mapping; editor toggle UI and inline math pending | +| M7 incremental integration | partial | route-D preview/PDF/edit endpoints plus opt-in `?engine=route-d` project preview, content-based page hashes and section/emphasis/display-math/itemize/enumerate/description/quote/center/flushright mapping; editor toggle in `texrra-web`; inline math pending | v1 remains the production renderer; the route-D core is additive and tested independently. @@ -269,7 +269,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 155 unit tests plus three route-D integration tests. Workspace verification: `cargo fmt --all -- --check`; `cargo test --workspace --offline` runs 254 tests (155 route-D unit, 3 route-D integration, 71 v1 integration, 19 server, 4 v1 unit, 1 core unit, 1 binary unit). v1 remains the live server path. +The crate currently has 156 unit tests plus three route-D integration tests. Workspace verification: `cargo fmt --all -- --check`; `cargo test --workspace --offline` runs 256 tests (156 route-D unit, 3 route-D integration, 71 v1 integration, 19 server, 4 v1 unit, 1 core unit, 2 binary units). v1 remains the live server path. ### M0 incremental demo @@ -307,10 +307,10 @@ deliberately open rather than approximated: project preview can opt in with `POST /api/projects/{id}/preview?engine=route-d`; `route_d::project_preview_json` strips the preamble/body wrapper and keeps a project-scoped `(paragraphs, Engine)` session. An unchanged source returns - `changedPages: []` and `recomputedPages: 0`; one or more same-count paragraph - edits are applied sequentially through `Engine::edit` from the earliest - changed paragraph and report the changed/recomputed pages, while structural - edits fall back to a full layout. The v1 semantic pipeline remains + `changedPages: []` and `recomputedPages: 0`; same-count paragraph edits and structural edits that keep a + non-empty paragraph prefix are rebuilt from the first difference through + `Engine::relayout_from`, which reuses the sealed pages before that + checkpoint; edits without a reusable prefix fall back to a full layout. The v1 semantic pipeline remains the default fallback. LaTeX-to-route-D semantic mapping is still a subset, and `route_d_page_matches_pdftex_raster_geometry` lays out a 480pt CMR10 paragraph at the same scaled-point geometry the server uses, rasterizes the route-D PDF and a pdfTeX Letter page at 72 dpi, and asserts matching ink line count plus left/right/bottom edges. It skips on hosts without `pdflatex`/`pdftoppm`. Exact glyph-outline pixel equality is still open because the two paths use different font outlines. - `\middle` does not scale with its enclosing delimiter; math delimiters are diff --git a/src/route_d.rs b/src/route_d.rs index eb0b4bf..5e29671 100755 --- a/src/route_d.rs +++ b/src/route_d.rs @@ -5,7 +5,7 @@ //! core. The v1 preview remains the default and the fallback. use std::cell::RefCell; -use std::collections::{BTreeSet, HashMap}; +use std::collections::HashMap; use std::fmt::Write as _; use std::sync::{Mutex, OnceLock}; @@ -23,7 +23,7 @@ thread_local! { } struct ProjectSession { - paragraphs: Vec, + paragraphs: Vec, engine: Engine, } @@ -45,53 +45,34 @@ fn latex_body(source: &str) -> &str { /// 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 texts: Vec = paragraphs.iter().map(|entry| entry.text.clone()).collect(); let document = build_document(¶graphs); 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(session) - if session.paragraphs.len() == texts.len() - && session + Some(mut session) => { + if session.paragraphs == paragraphs { + (session.engine, Vec::new(), 0) + } else { + let prefix = session .paragraphs .iter() - .zip(&texts) - .filter(|(a, b)| a != b) - .count() - == 0 => - { - (session.engine, Vec::new(), 0) - } - Some(mut session) - if session.paragraphs.len() == texts.len() - && session.paragraphs.iter().zip(&texts).any(|(a, b)| a != b) => - { - let changed_indices: Vec = session - .paragraphs - .iter() - .zip(&texts) - .enumerate() - .filter(|(_, (a, b))| a != b) - .map(|(index, _)| index) - .collect(); - let mut changed = BTreeSet::new(); - let mut recomputed = 0; - for (edit, &index) in changed_indices.iter().enumerate() { - session - .engine - .edit(&document, index as u64, texts[index].clone()); - if edit == 0 { - recomputed = session.engine.recomputed_pages(); + .zip(¶graphs) + .take_while(|(a, b)| a == b) + .count(); + if prefix > 0 && prefix < session.paragraphs.len() && prefix < paragraphs.len() { + session.engine.relayout_from(&document, prefix); + let changed = session.engine.changed_pages().to_vec(); + let recomputed = session.engine.recomputed_pages(); + (session.engine, changed, recomputed) + } else { + let engine = Engine::layout(&document); + let changed: Vec = (0..engine.pages().len()).collect(); + let recomputed = changed.len(); + (engine, changed, recomputed) } - changed.extend(session.engine.changed_pages().iter().copied()); } - ( - session.engine, - changed.into_iter().collect::>(), - recomputed, - ) } _ => { let engine = Engine::layout(&document); @@ -103,10 +84,7 @@ pub fn project_preview_json(project_id: &str, source: &str) -> Result Result { }) } -#[derive(Clone)] +#[derive(Clone, PartialEq, Eq)] struct SourceParagraph { text: String, centered: bool, @@ -462,4 +440,36 @@ mod tests { let recomputed = second["recomputedPages"].as_u64().expect("recomputed"); assert!(recomputed < page_count, "changed pages should be a subset"); } + + #[test] + fn structural_edit_keeps_pages_before_the_inserted_paragraph() { + let source = multi_page_source(); + let first = + project_preview_json("route-d-structural-edit", &source).expect("first preview"); + let first: serde_json::Value = serde_json::from_str(&first).expect("first JSON"); + let first_hash = first["pages"][0]["hash"].as_str().expect("first hash"); + + let inserted = source.replacen( + "Paragraph 21 ", + "Paragraph inserted before twenty-one with enough words to make a line.\n\nParagraph 21 ", + 1, + ); + let second = + project_preview_json("route-d-structural-edit", &inserted).expect("inserted preview"); + let second: serde_json::Value = serde_json::from_str(&second).expect("second JSON"); + assert_eq!( + second["pages"][0]["hash"].as_str().expect("second hash"), + first_hash + ); + let page_count = second["pageCount"].as_u64().expect("page count"); + assert!( + second["changedPages"] + .as_array() + .is_some_and(|pages| !pages.is_empty()) + ); + assert!( + second["recomputedPages"].as_u64().expect("recomputed") < page_count, + "the unchanged prefix should not be recomputed" + ); + } }