Cache route-D project previews by expanded source
This commit is contained in:
1 parent
874a327dca
commit
0651e15111
5 files changed
+160
-5
No files matched your search
@@ -467,7 +467,7 @@ from the font's MATH assembly parts. `\\left...\\right` target sizing follows
|
||||
the assignable TeX parameters `\\delimiterfactor` (default 901) and
|
||||
`\\delimitershortfall` (default 5pt), including local and global assignments.
|
||||
|
||||
Route-D text faces follow the NFSS declarations and compose with the surrounding run: `\sffamily\bfseries` selects cmssbx10, `\sffamily\itshape` selects cmssi10, and bold italic sans substitutes cmssbx10 because Computer Modern has no sans bold italic. `\scshape`/`\textsc` select the real cmcsc10 small-caps face, `\slshape`/`\textsl` use cmsl10 (or cmbxsl10 when bold) rather than the italic cmti10, and `\ttfamily\itshape` reaches cmitt10. All twelve text programs (cmr10, cmbx10, cmti10, cmbxti10, cmtt10, cmss10, cmssbx10, cmssi10, cmcsc10, cmsl10, cmbxsl10, cmitt10) are embedded as Type1 outlines. Because Computer Modern has no bold small caps, a bold small-caps request falls back to cmbx10. Section-wide declarations such as `\bfseries` apply from where they appear to the end of their group, and `\em` toggles emphasis relative to the surrounding face. Paragraph base sizes come from `\fontsize{<size>}{<baselineskip>}` and the article size commands (`\tiny` through `\Huge`), scaling glyph metrics and the default interline glue while the measure, indentation and authored skips stay absolute. The class options `10pt`/`11pt`/`12pt` on `\documentclass[...]` set the default base size (and article `\baselineskip` of 12pt/13.6pt/14.5pt); a size command inside a paragraph still overrides the class default. The paragraph measure follows `\textwidth`/`\hsize` (or `\setlength{\textwidth}{...}`), and `\setlength` accepts the other supported layout lengths, including a `\parskip` with plus/minus glue. The `geometry` package's `margin`/`hmargin`/`vmargin`/`left`/`right`/`top`/`bottom`/`textwidth`/`textheight` options (or `\geometry{...}`) are applied to the page measure and height; other package code is not executed. Block environments `center`, `flushleft` and `flushright` set the paragraph alignment, and aligned short lines are centring/flushing within the full measure rather than at the natural line width. `\title`, `\author` and `\date` are captured from the preamble, and `\maketitle` expands into a centered title block at the article class sizes. `\section`, `\subsection` and `\subsubsection` advance article counters, prefix their titles with the number, and paint bold at `\Large`/`\large`/`\normalsize`; starred headings stay unnumbered and an optional `[short]` title is dropped. The `abstract` environment expands into a centered bold heading and a 9pt body, and `\maketitle` joins multiple `\and` authors and turns `\thanks` notes into title footnotes. Section labels resolve `\ref`/`\eqref` to the heading number (standalone `\label` lines attach to the previous heading, unknown references print `??`), `\appendix` restarts sectioning with letter numbers, `\tableofcontents` lists the numbered headings, `\listoffigures`/`\listoftables` reproduce the numbered captions, `verbatim` keeps monospaced source lines, `\href` keeps its link text and `\url` becomes typewriter text,, and the `abstract` environment expands to its heading and body. In route-D, math uses Computer Modern metrics from the bundled `cmmi10`, `cmsy10`, `cmex10`, `msbm10` and `eufm10` TFMs and embeds their Type1 programs, so italic letters, relation symbols, big operators, `\mathcal` capitals, `\mathbb` capitals and `\mathfrak` Fraktur letters each paint with their own face. Fractions can be written as `\frac` or with TeX's infix forms (`\over`, `\atop`, `\choose`, `\brace`, `\brack`, `\overwithdelims`, `\atopwithdelims`); only `\over`-style fractions draw a bar and fractions never draw parentheses. `\left`/`\right` choose CMEX delimiter sizes from the body extent using TeX's delimiterfactor and shortfall, `\middle` delimiters are sized with their group, and `\big`/`\Big`/`\bigg`/`\Bigg` paint at their selected CMEX size. `align`/`align*` displays share column widths, right-align even columns at their relations, and number each row (with `\tag`/`\notag` per row); `gather`/`gather*` centre each row instead. Inter-atom spacing uses TeX's 3/4/5mu classes (`1mu` is `1/18em`), `\mid` is a relation and `\colon` punctuation, and `\mskip`/`\mkern`/`\mspace`/`\hskip`/`\kern`/`\hspace` scan TeX dimensions, taking the natural width of any `plus`/`minus` parts. `\footnote{...}` leaves a numbered marker in the paragraph and sets the note as a 9pt page insertion at the bottom of the page that mentions it. A `thebibliography` environment turns its `\bibitem` entries into numbered `[n]` paragraphs, and `\cite{...}` resolves to `[n]`/`[n, m]` (unknown keys print `[?]`). A `figure` environment becomes a float at its `[t]`/`[b]`/`[h]` placement, its `\caption` numbers as `Figure n:` and feeds `\ref`, and `\includegraphics[width=...]` reserves a rule placeholder. `table` environments likewise become floats carrying their captured `tabular` body, with `Table n:` captions that resolve from `\ref`. Table captions sit above the tabular as in LaTeX, figure captions below the graphic, and `\caption*` leaves either unnumbered. Theorem-like environments (`theorem`, `lemma`, `corollaryLine truncated
|
||||
Route-D text faces follow the NFSS declarations and compose with the surrounding run: `\sffamily\bfseries` selects cmssbx10, `\sffamily\itshape` selects cmssi10, and bold italic sans substitutes cmssbx10 because Computer Modern has no sans bold italic. `\scshape`/`\textsc` select the real cmcsc10 small-caps face, `\slshape`/`\textsl` use cmsl10 (or cmbxsl10 when bold) rather than the italic cmti10, and `\ttfamily\itshape` reaches cmitt10. All twelve text programs (cmr10, cmbx10, cmti10, cmbxti10, cmtt10, cmss10, cmssbx10, cmssi10, cmcsc10, cmsl10, cmbxsl10, cmitt10) are embedded as Type1 outlines. Because Computer Modern has no bold small caps, a bold small-caps request falls back to cmbx10. Section-wide declarations such as `\bfseries` apply from where they appear to the end of their group, and `\em` toggles emphasis relative to the surrounding face. Paragraph base sizes come from `\fontsize{<size>}{<baselineskip>}` and the article size commands (`\tiny` through `\Huge`), scaling glyph metrics and the default interline glue while the measure, indentation and authored skips stay absolute. The class options `10pt`/`11pt`/`12pt` on `\documentclass[...]` set the default base size (and article `\baselineskip` of 12pt/13.6pt/14.5pt); a size command inside a paragraph still overrides the class default. The paragraph measure follows `\textwidth`/`\hsize` (or `\setlength{\textwidth}{...}`), and `\setlength` accepts the other supported layout lengths, including a `\parskip` with plus/minus glue. The `geometry` package's `margin`/`hmargin`/`vmargin`/`left`/`right`/`top`/`bottom`/`textwidth`/`textheight` options (or `\geometry{...}`) are applied to the page measure and height; other package code is not executed. Block environments `center`, `flushleft` and `flushright` set the paragraph alignment, and aligned short lines are centring/flushing within the full measure rather than at the natural line width. `\title`, `\author` and `\date` are captured from the preamble, and `\maketitle` expands into a centered title block at the article class sizes. `\section`, `\subsection` and `\subsubsection` advance article counters, prefix their titles with the number, and paint bold at `\Large`/`\large`/`\normalsize`; starred headings stay unnumbered and an optional `[short]` title is dropped. The `abstract` environment expands into a centered bold heading and a 9pt body, and `\maketitle` joins multiple `\and` authors and turns `\thanks` notes into title footnotes. Section labels resolve `\ref`/`\eqref` to the heading number (standalone `\label` lines attach to the previous heading, unknown references print `??`), `\appendix` restarts sectioning with letter numbers, `\tableofcontents` lists the numbered headings, `\listoffigures`/`\listoftables` reproduce the numbered captions, `verbatim` keeps monospaced source lines, `\href` keeps its link text and `\url` becomes typewriter text, and the `abstract` environment expands to its heading and body. In route-D, math uses Computer Modern metrics from the bundled `cmmi10`, `cmsy10`, `cmex10`, `msbm10` and `eufm10` TFMs and embeds their Type1 programs, so italic letters, relation symbols, big operators, `\mathcal` capitals, `\mathbb` capitals and `\mathfrak` Fraktur letters each paint with their own face. Fractions can be written as `\frac` or with TeX's infix forms (`\over`, `\atop`, `\choose`, `\brace`, `\brack`, `\overwithdelims`, `\atopwithdelims`); only `\over`-style fractions draw a bar and fractions never draw parentheses. `\left`/`\right` choose CMEX delimiter sizes from the body extent using TeX's delimiterfactor and shortfall, `\middle` delimiters are sized with their group, and `\big`/`\Big`/`\bigg`/`\Bigg` paint at their selected CMEX size. `align`/`align*` displays share column widths, right-align even columns at their relations, and number each row (with `\tag`/`\notag` per row); `gather`/`gather*` centre each row instead. Inter-atom spacing uses TeX's 3/4/5mu classes (`1mu` is `1/18em`), `\mid` is a relation and `\colon` punctuation, and `\mskip`/`\mkern`/`\mspace`/`\hskip`/`\kern`/`\hspace` scan TeX dimensions, taking the natural width of any `plus`/`minus` parts. `\footnote{...}` leaves a numbered marker in the paragraph and sets the note as a 9pt page insertion at the bottom of the page that mentions it. A `thebibliography` environment turns its `\bibitem` entries into numbered `[n]` paragraphs, and `\cite{...}` resolves to `[n]`/`[n, m]` (unknown keys print `[?]`). A `figure` environment becomes a float at its `[t]`/`[b]`/`[h]` placement, its `\caption` numbers as `Figure n:` and feeds `\ref`, and `\includegraphics[width=...]` reserves a rule placeholder. `table` environments likewise become floats carrying their captured `tabular` body, with `Table n:` captions that resolve from `\ref`. Table captions sit above the tabular as in LaTeX, figure captions below the graphic, and `\caption*` leaves either unnumbered. Theorem-like environments (`theorem`, `lemma`, `corollary`Line truncated
|
||||
|
||||
Inline `$...$` and `\(...\)` math is laid out inside 10pt paragraphs (larger sizes keep the delimiters literal). `\newcommand`/`\renewcommand` definitions are captured from the preamble and expanded textually, including numbered arguments; TeX's `\def` parameter texts and `\let` aliases are executed the same way, and `\newenvironment` definitions wrap their bodies with the declared begin/end material. `\newif` flags select between `\if...\else...\fi` branches, with assignments honoured in the preamble or the body, so class conditionals like `\ifdraft` work.
|
||||
|
||||
|
||||
@@ -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`). 677 workspace tests are green and no oracle
|
||||
PDF opt-in with `?engine=route-d`). 678 workspace tests are green and no oracle
|
||||
fixture is ignored.
|
||||
|
||||
Status after G1 (P0-P2): the paragraph model reproduces TeX's passes,
|
||||
|
||||
+2
-2
@@ -333,7 +333,7 @@ for a later overlaid slash.
|
||||
| M4 math | partial | atoms, scripts, fractions (including infix `\over`/`\atop`/`\choose`), roots, delimiters, accents, operators, classes, braces, boxed, negated, math alphabets (incl. `\mathcal`, `\mathbb` and `\mathfrak`), `align`/`gather` rows with per-row tags; 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; used faces embed per-document TrueType glyf subsets that keep the original glyph IDs, include composite components, and carry a matching ToUnicode CMap; ASCII documents use the compact tier; no Base-14 dependency; SVG carries family/weight/style; route-D PDFs embed Knuth's Computer Modern Type1 programs (cmr10/cmbx10/cmti10/cmbxti10/cmtt10/cmss10/cmssbx10/cmssi10/cmcsc10/cmsl10/cmbxsl10/cmitt10) as `/Subtype /Type1` fonts with `/FontFile` (`Length1/2/3`), `/Encoding /Differences` and TFM `/Widths`, falling back per face to Liberation when the program does not encode every character |
|
||||
| M6 specials/XObject | partial | raw specials, RGB image XObjects, URI link annotations; route-D reads `\documentclass` size options (10/11/12pt) into the paragraph base size and `\baselineskip`, executes `\newcommand`/`\renewcommand` macros textually (with numbered arguments and an eight-pass recursion guard), and expands `geometry`, `\setlength`, title/author/date, `\maketitle`, sectioning, theorem, float and bibliography markup; executing `.cls`/`.sty` files remains 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/inline-math/itemize/enumerate/description/quote/center/flushleft/flushright mapping; editor toggle in `texrra-web`; inline `$...$`/`\(...\)` math is laid out inside 10pt paragraphs, while larger paragraphs keep delimiters literal |
|
||||
| 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/inline-math/itemize/enumerate/description/quote/center/flushleft/flushright mapping; editor toggle in `texrra-web`; project route-D previews are memoised by a hash of the expanded source (32 entries) and invalidated automatically when the source changes; inline `$...$`/`\(...\)` math is laid out inside 10pt paragraphs, while larger paragraphs keep delimiters literal |
|
||||
|
||||
v1 remains the production renderer; the route-D core is additive and tested independently.
|
||||
|
||||
@@ -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. `Engine::edit` preserves the face when reflowing an edited paragraph.
|
||||
|
||||
The crate currently has 403 unit tests plus eight route-D integration tests and thirty-five oracle fixtures. Workspace verification: `cargo fmt --all -- --check`; `cargo test --workspace --offline` runs 677 tests (403 route-D unit, 116 engine binary unit, 8 route-D integration, 35 oracle, 71 v1 integration, 39 server, 4 engine unit, 1 core unit), with none ignored. v1 remains the live server path.
|
||||
The crate currently has 403 unit tests plus eight route-D integration tests and thirty-five oracle fixtures. Workspace verification: `cargo fmt --all -- --check`; `cargo test --workspace --offline` runs 678 tests (403 route-D unit, 116 engine binary unit, 8 route-D integration, 35 oracle, 71 v1 integration, 40 server, 4 engine unit, 1 core unit), with none ignored. v1 remains the live server path.
|
||||
|
||||
### M0 incremental demo
|
||||
|
||||
|
||||
+109
-1
@@ -1,9 +1,12 @@
|
||||
use std::{
|
||||
collections::hash_map::DefaultHasher,
|
||||
env,
|
||||
fmt::Write as _,
|
||||
fs,
|
||||
hash::{Hash, Hasher},
|
||||
path::{Path, PathBuf},
|
||||
process,
|
||||
sync::{Mutex, OnceLock},
|
||||
};
|
||||
|
||||
use tiny_http::{Header, Method, Request, Response, Server, StatusCode};
|
||||
@@ -555,6 +558,69 @@ fn sanitize_package(source: &str) -> String {
|
||||
.join("\n")
|
||||
}
|
||||
|
||||
fn route_d_cache_key(id: &str, source: &str) -> (String, u64) {
|
||||
let mut hasher = DefaultHasher::new();
|
||||
source.hash(&mut hasher);
|
||||
(id.to_string(), hasher.finish())
|
||||
}
|
||||
|
||||
fn route_d_cache() -> &'static Mutex<Vec<((String, u64), String)>> {
|
||||
static CACHE: OnceLock<Mutex<Vec<((String, u64), String)>>> = OnceLock::new();
|
||||
CACHE.get_or_init(|| Mutex::new(Vec::new()))
|
||||
}
|
||||
|
||||
fn route_d_cached_preview(key: &(String, u64)) -> Option<String> {
|
||||
let cache = route_d_cache().lock().ok()?;
|
||||
cache
|
||||
.iter()
|
||||
.find(|(cached, _)| cached == key)
|
||||
.map(|(_, json)| json.clone())
|
||||
}
|
||||
|
||||
fn replace_number_field(json: &str, field: &str, value: u64) -> String {
|
||||
let Some(start) = json.find(field) else {
|
||||
return json.to_string();
|
||||
};
|
||||
let Some(colon) = json[start..].find(':') else {
|
||||
return json.to_string();
|
||||
};
|
||||
let value_start = start + colon + 1;
|
||||
let rest = &json[value_start..];
|
||||
let Some(end) = rest.find([',', '}']) else {
|
||||
return json.to_string();
|
||||
};
|
||||
format!("{}{value}{}", &json[..value_start], &rest[end..])
|
||||
}
|
||||
|
||||
fn replace_array_field(json: &str, field: &str) -> String {
|
||||
let Some(start) = json.find(field) else {
|
||||
return json.to_string();
|
||||
};
|
||||
let Some(open_rel) = json[start..].find('[') else {
|
||||
return json.to_string();
|
||||
};
|
||||
let open = start + open_rel;
|
||||
let Some(close_rel) = json[open..].find(']') else {
|
||||
return json.to_string();
|
||||
};
|
||||
let close = open + close_rel;
|
||||
format!("{}[]{}", &json[..open], &json[close + 1..])
|
||||
}
|
||||
|
||||
fn preview_without_changes(json: &str) -> String {
|
||||
let json = replace_number_field(json, "\"recomputedPages\"", 0);
|
||||
replace_array_field(&json, "\"changedPages\"")
|
||||
}
|
||||
|
||||
fn store_route_d_preview(key: (String, u64), json: String) {
|
||||
if let Ok(mut cache) = route_d_cache().lock() {
|
||||
cache.push((key, json));
|
||||
if cache.len() > 32 {
|
||||
cache.remove(0);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn expand_project_source(source: &str, store: &projects::ProjectStore, id: &str) -> String {
|
||||
let expanded = expand_project_inputs(source, store, id);
|
||||
let expanded = expand_project_packages(&expanded, store, id);
|
||||
@@ -664,8 +730,50 @@ fn handle_project_request(
|
||||
};
|
||||
if query_param(url, "engine").as_deref() == Some("route-d") {
|
||||
let expanded = expand_project_source(&source, &store, id);
|
||||
let key = route_d_cache_key(id, &expanded);
|
||||
if let Some(json) = route_d_cached_preview(&key) {
|
||||
return respond_json(request, 200, &preview_without_changes(&json));
|
||||
}
|
||||
fn replace_number_field(json: &str, field: &str, value: u64) -> String {
|
||||
let Some(start) = json.find(field) else {
|
||||
return json.to_string();
|
||||
};
|
||||
let Some(colon) = json[start..].find(':') else {
|
||||
return json.to_string();
|
||||
};
|
||||
let value_start = start + colon + 1;
|
||||
let rest = &json[value_start..];
|
||||
let Some(end) = rest.find([',', '}']) else {
|
||||
return json.to_string();
|
||||
};
|
||||
format!("{}{value}{}", &json[..value_start], &rest[end..])
|
||||
}
|
||||
|
||||
fn replace_array_field(json: &str, field: &str) -> String {
|
||||
let Some(start) = json.find(field) else {
|
||||
return json.to_string();
|
||||
};
|
||||
let Some(open_rel) = json[start..].find('[') else {
|
||||
return json.to_string();
|
||||
};
|
||||
let open = start + open_rel;
|
||||
let Some(close_rel) = json[open..].find(']') else {
|
||||
return json.to_string();
|
||||
};
|
||||
let close = open + close_rel;
|
||||
format!("{}[]{}", &json[..open], &json[close + 1..])
|
||||
}
|
||||
|
||||
fn preview_without_changes(json: &str) -> String {
|
||||
let json = replace_number_field(json, "\"recomputedPages\"", 0);
|
||||
replace_array_field(&json, "\"changedPages\"")
|
||||
}
|
||||
|
||||
return match route_d::project_preview_json(id, &expanded) {
|
||||
Ok(json) => respond_json(request, 200, &json),
|
||||
Ok(json) => {
|
||||
store_route_d_preview(key, json.clone());
|
||||
respond_json(request, 200, &json)
|
||||
}
|
||||
Err(error) => respond_api_error(request, 422, &error),
|
||||
};
|
||||
}
|
||||
|
||||
@@ -343,6 +343,53 @@ fn project_preview_expands_local_style_packages() {
|
||||
assert!(!text.contains("ProvidesPackage"), "{text}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn route_d_previews_are_cached_and_invalidated() {
|
||||
let server = TestServer::start("route-d-cache");
|
||||
let source = "\\documentclass{article}\n\\begin{document}\nCached QRX.\n\\end{document}";
|
||||
let put = server.request(
|
||||
"PUT",
|
||||
"/api/projects/hello/file?path=hello.tex",
|
||||
source.as_bytes(),
|
||||
"text/plain; charset=utf-8",
|
||||
);
|
||||
assert_eq!(put.status, 200, "{}", put.text());
|
||||
let first = server.request(
|
||||
"POST",
|
||||
"/api/projects/hello/preview?engine=route-d",
|
||||
&[],
|
||||
"application/json",
|
||||
);
|
||||
let second = server.request(
|
||||
"POST",
|
||||
"/api/projects/hello/preview?engine=route-d",
|
||||
&[],
|
||||
"application/json",
|
||||
);
|
||||
assert_eq!(first.status, 200, "{}", first.text());
|
||||
assert_eq!(second.status, 200, "{}", second.text());
|
||||
let second_json: Value = serde_json::from_slice(&second.body).expect("second JSON");
|
||||
assert_eq!(second_json["recomputedPages"], serde_json::json!(0));
|
||||
assert_eq!(second_json["changedPages"], serde_json::json!([]));
|
||||
let changed = "\\documentclass{article}\n\\begin{document}\nChanged ZZZ.\n\\end{document}";
|
||||
let put = server.request(
|
||||
"PUT",
|
||||
"/api/projects/hello/file?path=hello.tex",
|
||||
changed.as_bytes(),
|
||||
"text/plain; charset=utf-8",
|
||||
);
|
||||
assert_eq!(put.status, 200, "{}", put.text());
|
||||
let third = server.request(
|
||||
"POST",
|
||||
"/api/projects/hello/preview?engine=route-d",
|
||||
&[],
|
||||
"application/json",
|
||||
);
|
||||
assert_eq!(third.status, 200, "{}", third.text());
|
||||
assert_ne!(first.body, third.body, "editing must invalidate the cache");
|
||||
assert!(third.text().contains(">Z</text>"), "{}", third.text());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn route_d_renders_href_and_url() {
|
||||
let server = TestServer::start("route-d-links");
|
||||
|
||||
Reference in new issue
Block a user