Read paragraph registers from route-D sources and measure with TFM advances

This commit is contained in:
gloamxun committed 2026-10-23 13:28:43 +08:00
1 parent be23fe9686
commit 4f4171a6d1
4 files changed
+105 -23

No files matched your search

+1 -1
View File
@@ -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`). 421 workspace tests are green and no oracle
PDF opt-in with `?engine=route-d`). 422 workspace tests are green and no oracle
fixture is ignored.
Known gaps, in dependency order:
+2 -2
View File
@@ -338,7 +338,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 unit tests covering overfull avoidance, exact glue filling, forced and costed breaks, `\topskip`, `\maxdepth`, marks, insertion limits and top-float placement; every fragment records the penalty that broke it. `Engine::layout_paged` now builds pages through it for documents whose units are single vertical items (boxes, rules, paragraphs, math, haligns, glue, penalties, marks and insertion classes, including per-class limits and held-over material; held-over material starts with `Document::split_top_skip` (TeX `\splittopskip`, default 10pt) when the class capacity can also hold its first item); `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. Paragraphs also split across pages at line boundaries, so body material no longer overflows a page as one box. `Document::h_offset` and `v_offset` (TeX `\hoffset`/`\voffset`, default zero) feed `pdf::PageOrigin`, and `display_lists_to_pdf_with_paper` translates the page body without moving the sheet; a route-D fixture checks a 10pt/20pt shift against `pdftotext -bbox`. `Document::paper_width` and `paper_height` (TeX `\paperwidth`/`\paperheight`, default US Letter) set the PDF MediaBox and the preview page box, and both route-D endpoints strip leading `\hoffset`/`\voffset`/`\paperwidth`/`\paperheight`/`\vsize`/`\textheight` dimension assignments from the source (preamble included) and apply them; `\textheight` wins over `\vsize` because LaTeX resets `\vsize` from `\textheight` on every page, and project previews reuse the same geometry parsing. `Engine::top_mark`, `first_mark` and `bot_mark` implement TeX's carried mark registers per class. `Document::output_routine` runs an interpreted `\output` program over the paged fragments (`output::OutputProgram`: `\shipout\box255`, `\relax`, `\message`, `\ifdim`, `\ifnum`, `\ifodd` and `\ifcase` over the page registers, now including `\pageno`, `\outputpenalty` and `\deadcycles`), dropping pages the routine does not ship. Assignments such as `\pageno=10`, `\deadcycles=0`, `\count2=2000`, `\dimen2=30pt`, `\skip2=6pt` and `\vsize=300pt` mutate the per-page context; `\pageno` and the insertion registers keep their assigned values for later pages, since TeX's output registers are global; for documents without insertions or floats the paged builder runs the routine after each page, so an assigned `\vsize` sets the goal of the pages the routine has not seen yet. The `\pagegoal` register handed to the output routine is reduced by the insertion space reserved on that page. Paged layouts record the node index that starts each page, so `Engine::edit` on a paged layout reuses the sealed prefix and rebuilds only from the edited unit's page onward; an interpreted `\output` routine still forces a full rebuild, and an edit whose replay would begin before the first insertion does too, because held-over material and dropped pages move page boundaries. The scrolling builder's float path remains to be ported. The oracleLine truncated
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 unit tests covering overfull avoidance, exact glue filling, forced and costed breaks, `\topskip`, `\maxdepth`, marks, insertion limits and top-float placement; every fragment records the penalty that broke it. `Engine::layout_paged` now builds pages through it for documents whose units are single vertical items (boxes, rules, paragraphs, math, haligns, glue, penalties, marks and insertion classes, including per-class limits and held-over material; held-over material starts with `Document::split_top_skip` (TeX `\splittopskip`, default 10pt) when the class capacity can also hold its first item); `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. Paragraphs also split across pages at line boundaries, so body material no longer overflows a page as one box. `Document::h_offset` and `v_offset` (TeX `\hoffset`/`\voffset`, default zero) feed `pdf::PageOrigin`, and `display_lists_to_pdf_with_paper` translates the page body without moving the sheet; a route-D fixture checks a 10pt/20pt shift against `pdftotext -bbox`. `Document::paper_width` and `paper_height` (TeX `\paperwidth`/`\paperheight`, default US Letter) set the PDF MediaBox and the preview page box, and both route-D endpoints strip leading `\hoffset`/`\voffset`/`\paperwidth`/`\paperheight`/`\vsize`/`\textheight` dimension assignments from the source (preamble included) and apply them, and the same pass reads `\parindent`, `\parskip`, `\baselineskip`, `\leftskip`, `\rightskip`, `\emergencystretch`, `\tolerance` and `\pretolerance` into the paragraph styles; body paragraphs are measured with CMR10/per-face TFM advances rather than fixed cells; `\textheight` wins over `\vsize` because LaTeX resets `\vsize` from `\textheight` on every page, and project previews reuse the same geometry parsing. `Engine::top_mark`, `first_mark` and `bot_mark` implement TeX's carried mark registers per class. `Document::output_routine` runs an interpreted `\output` program over the paged fragments (`output::OutputProgram`: `\shipout\box255`, `\relax`, `\message`, `\ifdim`, `\ifnum`, `\ifodd` and `\ifcase` over the page registers, now including `\pageno`, `\outputpenalty` and `\deadcycles`), dropping pages the routine does not ship. Assignments such as `\pageno=10`, `\deadcycles=0`, `\count2=2000`, `\dimen2=30pt`, `\skip2=6pt` and `\vsize=300pt` mutate the per-page context; `\pageno` and the insertion registers keep their assigned values for later pages, since TeX's output registers are global; for documents without insertions or floats the paged builder runs the routine after each page, so an assigned `\vsize` sets the goal of the pages the routine has not seen yet. The `\pagegoal` register handed to the output routine is reduced by the insertion space reserved on that page. Paged layouts record the node index that starts each page, so `Engine::edit` on a paged layout reuses the sealed prefix and rebuilds only from the edited unit's page onward; an interLine truncated
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.
@@ -346,7 +346,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 288 unit tests plus seven route-D integration tests and twenty-four oracle fixtures. Workspace verification: `cargo fmt --all -- --check`; `cargo test --workspace --offline` runs 421 tests (288 route-D unit, 7 route-D integration, 24 oracle, 71 v1 integration, 24 server, 4 v1 unit, 1 core unit, 2 binary units), with none ignored. v1 remains the live server path.
The crate currently has 288 unit tests plus seven route-D integration tests and twenty-four oracle fixtures. Workspace verification: `cargo fmt --all -- --check`; `cargo test --workspace --offline` runs 422 tests (288 route-D unit, 7 route-D integration, 24 oracle, 71 v1 integration, 24 server, 4 v1 unit, 1 core unit, 2 binary units), with none ignored. v1 remains the live server path.
### M0 incremental demo
+64 -20
View File
@@ -12,7 +12,7 @@ use std::sync::{Mutex, OnceLock};
use texrra_tex_core::cmr10::Cmr10Metrics;
use texrra_tex_core::math::parse_math;
use texrra_tex_core::pdf::{PageOrigin, display_lists_to_pdf_with_paper};
use texrra_tex_core::{Document, Engine, ParagraphFont, ParagraphStyle, Unit, VerticalItem};
use texrra_tex_core::{Document, Engine, ParagraphFont, ParagraphStyle, Unit};
const SCALE: i64 = 65_536;
@@ -45,7 +45,7 @@ fn latex_body(source: &str) -> &str {
pub fn project_preview_json(project_id: &str, source: &str) -> Result<String, String> {
let (body, geometry) = geometry_and_body(source);
let paragraphs = paragraphs(&body)?;
let mut document = build_document(&paragraphs);
let mut document = build_document(&paragraphs, &geometry);
apply_geometry(&mut document, &geometry);
let mut sessions = project_sessions()
.lock()
@@ -107,6 +107,14 @@ struct PageGeometry {
paper_height: Option<i64>,
vsize: Option<i64>,
textheight: Option<i64>,
par_indent: Option<i64>,
par_skip: Option<i64>,
baseline_skip: Option<i64>,
left_skip: Option<i64>,
right_skip: Option<i64>,
tolerance: Option<i64>,
pretolerance: Option<i64>,
emergency_stretch: Option<i64>,
}
/// Pull `\hoffset`/`\voffset`/`\paperwidth`/`\paperheight`/`\vsize`/
@@ -130,6 +138,22 @@ fn strip_page_geometry(source: &str) -> (String, PageGeometry) {
geometry.vsize = Some(value);
} else if let Some(value) = dimension_assignment(trimmed, "textheight") {
geometry.textheight = Some(value);
} else if let Some(value) = dimension_assignment(trimmed, "parindent") {
geometry.par_indent = Some(value);
} else if let Some(value) = dimension_assignment(trimmed, "parskip") {
geometry.par_skip = Some(value);
} else if let Some(value) = dimension_assignment(trimmed, "baselineskip") {
geometry.baseline_skip = Some(value);
} else if let Some(value) = dimension_assignment(trimmed, "leftskip") {
geometry.left_skip = Some(value);
} else if let Some(value) = dimension_assignment(trimmed, "rightskip") {
geometry.right_skip = Some(value);
} else if let Some(value) = dimension_assignment(trimmed, "emergencystretch") {
geometry.emergency_stretch = Some(value);
} else if let Some(value) = integer_assignment(trimmed, "tolerance") {
geometry.tolerance = Some(value);
} else if let Some(value) = integer_assignment(trimmed, "pretolerance") {
geometry.pretolerance = Some(value);
} else {
body.push_str(line);
body.push('\n');
@@ -157,6 +181,20 @@ fn apply_geometry(document: &mut Document, geometry: &PageGeometry) {
if let Some(height) = geometry.textheight.or(geometry.vsize) {
document.page_goal = height;
}
if let Some(skip) = geometry.par_skip {
document.par_skip = skip;
}
}
/// Read a plain integer assignment such as `\tolerance=1000`.
fn integer_assignment(line: &str, name: &str) -> Option<i64> {
let rest = line.strip_prefix('\\')?;
let rest = rest.strip_prefix(name)?;
rest.trim_start().strip_prefix('=')?;
rest.trim()
.parse::<i64>()
.ok()
.map(|value| value.clamp(0, 10_000))
}
fn dimension_assignment(line: &str, name: &str) -> Option<i64> {
@@ -188,7 +226,7 @@ fn parse_dimension(text: &str) -> Option<i64> {
pub fn preview_json(source: &str) -> Result<String, String> {
let (body, geometry) = geometry_and_body(source);
let paragraphs = paragraphs(&body)?;
let mut document = build_document(&paragraphs);
let mut document = build_document(&paragraphs, &geometry);
apply_geometry(&mut document, &geometry);
let engine = Engine::layout(&document);
let json = render_json(&document, &engine, None);
@@ -204,7 +242,7 @@ pub fn preview_json(source: &str) -> Result<String, String> {
pub fn pdf_bytes(source: &str) -> Result<Vec<u8>, String> {
let (body, geometry) = geometry_and_body(source);
let paragraphs = paragraphs(&body)?;
let mut document = build_document(&paragraphs);
let mut document = build_document(&paragraphs, &geometry);
apply_geometry(&mut document, &geometry);
let engine = Engine::layout(&document);
let pages: Vec<_> = engine
@@ -229,14 +267,15 @@ pub fn pdf_bytes(source: &str) -> Result<Vec<u8>, String> {
/// Apply one paragraph edit to the last route-D document and report page
/// checkpoints that were reused versus rebuilt.
pub fn edit_json(source: &str, unit: usize) -> Result<String, String> {
let paragraphs = paragraphs(source)?;
let (body, geometry) = geometry_and_body(source);
let paragraphs = paragraphs(&body)?;
if unit >= paragraphs.len() {
return Err(format!(
"unit {unit} is out of range for {} paragraphs",
paragraphs.len()
));
}
let next = build_document(&paragraphs);
let next = build_document(&paragraphs, &geometry);
ROUTE_D_SESSION.with(|slot| {
let mut slot = slot.borrow_mut();
let (_, mut engine) = match slot.take() {
@@ -426,7 +465,7 @@ fn parse_paragraph(raw: &str) -> SourceParagraph {
}
}
fn build_document(paragraphs: &[SourceParagraph]) -> Document {
fn build_document(paragraphs: &[SourceParagraph], geometry: &PageGeometry) -> Document {
let units = paragraphs
.iter()
.enumerate()
@@ -440,11 +479,11 @@ fn build_document(paragraphs: &[SourceParagraph]) -> Document {
}
let style = ParagraphStyle {
line_width: 480 * SCALE,
left_skip: paragraph.left_skip * SCALE,
left_skip: paragraph.left_skip * SCALE + geometry.left_skip.unwrap_or(0),
centered: paragraph.centered,
right_aligned: paragraph.right_aligned,
ragged_right: false,
right_skip: 0,
right_skip: geometry.right_skip.unwrap_or(0),
hang_indent: 0,
hang_after: 1,
par_shape: Vec::new(),
@@ -453,13 +492,13 @@ fn build_document(paragraphs: &[SourceParagraph]) -> Document {
par_fillskip_fil: true,
frenchspacing: false,
space_factor_codes: Vec::new(),
baselineskip: 12 * 65536,
baselineskip: geometry.baseline_skip.unwrap_or(12 * 65536),
lineskip: 65536,
lineskiplimit: 0,
par_indent: 0,
emergencystretch: 0,
pretolerance: 100,
tolerance: 200,
par_indent: geometry.par_indent.unwrap_or(0),
emergencystretch: geometry.emergency_stretch.unwrap_or(0),
pretolerance: geometry.pretolerance.unwrap_or(100),
tolerance: geometry.tolerance.unwrap_or(200),
hyphen_penalty: 50,
ex_hyphen_penalty: 50,
double_hyphen_demerits: 10_000,
@@ -467,7 +506,11 @@ fn build_document(paragraphs: &[SourceParagraph]) -> Document {
line_penalty: 10,
adj_demerits: 10_000,
hyphenation_exceptions: Vec::new(),
line_height: paragraph.line_height * SCALE,
line_height: if paragraph.line_height == 12 {
geometry.baseline_skip.unwrap_or(12 * 65536)
} else {
paragraph.line_height * SCALE
},
char_width: 10 * SCALE,
space_width: 4 * SCALE,
space_stretch: 6 * SCALE,
@@ -475,11 +518,12 @@ fn build_document(paragraphs: &[SourceParagraph]) -> Document {
space_skip: None,
xspace_skip: None,
};
let mut unit = Unit::paragraph_with_style(index as u64, paragraph.text.clone(), style);
if let Some(VerticalItem::Paragraph(paragraph_box)) = unit.items.first_mut() {
paragraph_box.font = paragraph.font;
}
unit
Unit::paragraph_with_style_and_face(
index as u64,
paragraph.text.clone(),
style,
paragraph.font,
)
})
.collect();
Document::new(700 * SCALE, units)
+38
View File
@@ -781,6 +781,44 @@ fn route_d_renders_flushright_blocks() {
assert!(x > 50.0, "{x}");
}
#[test]
fn route_d_applies_source_paragraph_registers() {
let server = TestServer::start("route-d-parregisters");
let plain = server.request("POST", "/api/route-d/preview", b"Alpha beta", "text/plain");
assert_eq!(plain.status, 200, "{}", plain.text());
let plain: Value = serde_json::from_slice(&plain.body).expect("route-D JSON");
let plain_svg = plain["pages"][0]["svg"].as_str().unwrap();
let plain_x = text_x(plain_svg, ">A</text>");
let indented = server.request(
"POST",
"/api/route-d/preview",
b"\\parindent=30pt\n\nAlpha beta",
"text/plain",
);
assert_eq!(indented.status, 200, "{}", indented.text());
let indented: Value = serde_json::from_slice(&indented.body).expect("route-D JSON");
let indented_svg = indented["pages"][0]["svg"].as_str().unwrap();
let indented_x = text_x(indented_svg, ">A</text>");
assert!(
indented_x - plain_x > 20.0,
"parindent should shift the first line: {indented_x} vs {plain_x}"
);
}
fn text_x(svg: &str, needle: &str) -> f64 {
let index = svg.find(needle).expect("text run");
let prefix = &svg[..index];
let start = prefix.rfind("<text x=\"").expect("text x");
prefix[start + 9..]
.split('"')
.next()
.unwrap()
.parse()
.unwrap()
}
#[test]
fn edits_route_d_preview_pages() {
let server = TestServer::start("route-d-edit");