Honour declared paper size in route-D output

This commit is contained in:
gloamxun committed 2026-10-23 03:53:32 +08:00
1 parent 043ae7f072
commit 7b9d543e49
7 files changed
+142 -33

No files matched your search

+5 -3
View File
@@ -590,9 +590,11 @@ The first M7 service integration is available as `POST /api/route-d/preview`, wi
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; insertion classes are placed through the same builder, with per-class limits and held-over material, while the scrolling builder remains the default until bottom/in-text floats gain a paged equivalent; paged layouts replay edits from the edited page, falling back to a full rebuild when insertions or an `\output` routine are present. `Document::output_routine` runs an interpreted `\output` program (`\shipout\box255`, `\relax`, `\message`, `\ifdim`, `\ifnum` and `\ifodd` over page registers; `\pageno`, `\outputpenalty` and `\deadcycles` are readable, and each page fragment records the penalty that broke it) over those paged fragments, so a routine can drop pages it does not ship, or ship only the pages it wants based on the break penalty or page number. 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; the
route-D PDF endpoint reads leading `\hoffset`/`\voffset` dimension assignments
from the submitted source. Page marks collected by `\mark` are exposed through
page body through `pdf::PageOrigin`, leaving the sheet size unchanged, while
`Document::paper_width`/`paper_height` (`\paperwidth`/`\paperheight`, default US
Letter) set the MediaBox and the preview page box; the route-D endpoints read
leading `\hoffset`/`\voffset`/`\paperwidth`/`\paperheight` dimension
assignments from the submitted source. Page marks collected by `\mark` are exposed through
`Engine::top_mark`, `first_mark` and `bot_mark` with TeX's carry-forward rules.
`Document::insertion_classes` caps each insertion class to a page fraction and defers overflow to the next page (the paged builder applies the same limits and carries overflow onto dedicated pages), and `InsertionClass::multiplier` applies TeX's `\count<number>` reserve factor; `Document::insertion_skip` models `\skip\footins` once per page before the first insertion class, and `InsertionClass::skip` overrides it for one class. `Engine::layout_paged` feeds the same material through `page::PageBuilder`, which places top floats at the head of a page, defers a late float, reserves `Document::text_float_sep` above the body and applies the insertion class limits; bottom and in-text floats still run through the scrolling builder. The v1 `/preview` and project APIs are unchanged and remain the default.
+23
View File
@@ -566,6 +566,12 @@ fn default_insertion_multiplier() -> u32 {
pub struct Document {
pub units: Vec<Unit>,
pub page_goal: i64,
/// TeX `\paperwidth`: width of the output page.
#[serde(default = "default_paper_width")]
pub paper_width: i64,
/// TeX `\paperheight`: height of the output page.
#[serde(default = "default_paper_height")]
pub paper_height: i64,
/// TeX-like `\topskip`: distance from the page top to the first baseline.
#[serde(default)]
pub top_skip: i64,
@@ -630,6 +636,14 @@ pub struct Document {
pub output_routine: Option<String>,
}
fn default_paper_width() -> i64 {
612 * 65_536
}
fn default_paper_height() -> i64 {
792 * 65_536
}
fn default_text_fraction() -> u8 {
50
}
@@ -671,6 +685,8 @@ impl Document {
Self {
units,
page_goal,
paper_width: default_paper_width(),
paper_height: default_paper_height(),
top_skip: 0,
max_depth: 0,
text_fraction_percent: default_text_fraction(),
@@ -2401,6 +2417,13 @@ impl Engine {
mod tests {
use super::*;
#[test]
fn documents_default_to_letter_paper() {
let document = Document::new(100, Vec::new());
assert_eq!(document.paper_width, 612 * 65_536);
assert_eq!(document.paper_height, 792 * 65_536);
}
fn document() -> Document {
Document::new(
50,
+23 -7
View File
@@ -345,13 +345,29 @@ pub fn display_lists_to_pdf_with_origin(
page_height: i64,
origin: PageOrigin,
) -> Vec<u8> {
let height = page_height.max(792 * 65_536);
let width = pages
.iter()
.map(|page| page.width)
.max()
.unwrap_or(612 * 65_536)
.max(612 * 65_536);
display_lists_to_pdf_with_paper(
pages,
pages
.iter()
.map(|page| page.width)
.max()
.unwrap_or(612 * 65_536)
.max(612 * 65_536),
page_height.max(792 * 65_536),
origin,
)
}
/// Write several display lists as a multi-page PDF with an explicit paper
/// size (TeX `\paperwidth`/`\paperheight`) and page origin offsets.
pub fn display_lists_to_pdf_with_paper(
pages: &[DisplayList],
page_width: i64,
page_height: i64,
origin: PageOrigin,
) -> Vec<u8> {
let width = page_width;
let height = page_height;
let mut objects: Vec<Vec<u8>> = Vec::new();
objects.push(b"<< /Type /Catalog /Pages 2 0 R >>".to_vec());
+6 -3
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`). 367 workspace tests are green and no oracle
PDF opt-in with `?engine=route-d`). 370 workspace tests are green and no oracle
fixture is ignored.
Known gaps, in dependency order:
@@ -270,8 +270,11 @@ chosen fragments as hashed pages; ties go to the breakpoint closest to the page
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`, and the PDF endpoint reads leading `\hoffset`/`\voffset`
dimension assignments from the source. Insertion classes are placed by the
with `pdftotext -bbox`. `Document::paper_width`/`paper_height`
(`\paperwidth`/`\paperheight`, default US Letter) set the MediaBox and preview
page box, and the endpoints read leading
`\hoffset`/`\voffset`/`\paperwidth`/`\paperheight` dimension assignments from
the source. Insertion classes are placed by the
paged builder with their limits and held-over material, and top floats are
placed at the head of a fragment with `\textfloatsep` reserved above the body;
bottom/in-text floats still fall back to the scrolling builder, which stays
+2 -2
View File
@@ -331,7 +331,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); `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_origin` translates the page body without moving the sheet; a route-D fixture checks a 10pt/20pt shift against `pdftotext -bbox`, and the route-D PDF endpoint strips leading `\hoffset`/`\voffset` dimension assignments from the source and applies them. `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. 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 (documents with insertions or an interpreted `\output` routine still fall back to a full rebuild, because held-over material and dropped pages move page boundaries). Bottom/in-text floats and the scrolling builder's float path remain to be ported. The oracle harness also compares whole pages: three page fixtures (single-line paragraphs, `\parskip=6pt`, and multi-line paragraphs split across pages) assert the same page count and the same per-page alphanumeric text as pdfLaTeX at 345pt measure, 550pt `\vsize`, 12pt `\topskip` and 15pt `\parindent`.
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); `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` dimension assignments from the source and apply them. `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. 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 (documents with insertions or an interpreted `\output` routine still fall back to a full rebuild, because held-over material and dropped pages move page boundaries). Bottom/in-text floats and the scrolling builder's float path remain to be ported. The oracle harness also compares whole pages: three page fixtures (single-line paragraphs, `\parskip=6pt`, and multi-line paragraphs split across pages) assert the same page count and the same per-page alphanumeric text as pdfLaTeX at 345pt measure, 550pt `\vsize`, 12pt `\topskip` and 15pt `\parindent`.
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.
@@ -339,7 +339,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 246 unit tests plus seven route-D integration tests and sixteen oracle fixtures. Workspace verification: `cargo fmt --all -- --check`; `cargo test --workspace --offline` runs 367 tests (246 route-D unit, 7 route-D integration, 16 oracle, 71 v1 integration, 20 server, 4 v1 unit, 1 core unit, 2 binary units), with none ignored. v1 remains the live server path.
The crate currently has 247 unit tests plus seven route-D integration tests and sixteen oracle fixtures. Workspace verification: `cargo fmt --all -- --check`; `cargo test --workspace --offline` runs 370 tests (247 route-D unit, 7 route-D integration, 16 oracle, 71 v1 integration, 22 server, 4 v1 unit, 1 core unit, 2 binary units), with none ignored. v1 remains the live server path.
### M0 incremental demo
+43 -18
View File
@@ -11,12 +11,10 @@ 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_origin};
use texrra_tex_core::pdf::{PageOrigin, display_lists_to_pdf_with_paper};
use texrra_tex_core::{Document, Engine, ParagraphFont, ParagraphStyle, Unit, VerticalItem};
const SCALE: i64 = 65_536;
const PAGE_HEIGHT_PT: i64 = 792;
const PAGE_WIDTH_PT: i64 = 612;
thread_local! {
static ROUTE_D_SESSION: RefCell<Option<(Document, Engine)>> = const { RefCell::new(None) };
@@ -89,10 +87,13 @@ pub fn project_preview_json(project_id: &str, source: &str) -> Result<String, St
Ok(json)
}
/// Pull `\hoffset`/`\voffset` assignments out of the source and return the
/// remaining body. Both commands take a TeX dimension.
fn strip_page_offsets(source: &str) -> (String, PageOrigin) {
/// Pull `\hoffset`/`\voffset`/`\paperwidth`/`\paperheight` assignments out of
/// the source and return the remaining body. Each command takes a TeX
/// dimension.
fn strip_page_geometry(source: &str) -> (String, PageOrigin, Option<i64>, Option<i64>) {
let mut origin = PageOrigin::default();
let mut paper_width = None;
let mut paper_height = None;
let mut body = String::new();
for line in source.lines() {
let trimmed = line.trim();
@@ -100,12 +101,16 @@ fn strip_page_offsets(source: &str) -> (String, PageOrigin) {
origin.h_offset = value;
} else if let Some(value) = dimension_assignment(trimmed, "voffset") {
origin.v_offset = value;
} else if let Some(value) = dimension_assignment(trimmed, "paperwidth") {
paper_width = Some(value);
} else if let Some(value) = dimension_assignment(trimmed, "paperheight") {
paper_height = Some(value);
} else {
body.push_str(line);
body.push('\n');
}
}
(body, origin)
(body, origin, paper_width, paper_height)
}
fn dimension_assignment(line: &str, name: &str) -> Option<i64> {
@@ -135,8 +140,15 @@ fn parse_dimension(text: &str) -> Option<i64> {
/// Build a JSON preview from blank-line-separated plain-text paragraphs.
pub fn preview_json(source: &str) -> Result<String, String> {
let paragraphs = paragraphs(source)?;
let document = build_document(&paragraphs);
let (body, _origin, paper_width, paper_height) = strip_page_geometry(source);
let paragraphs = paragraphs(&body)?;
let mut document = build_document(&paragraphs);
if let Some(width) = paper_width {
document.paper_width = width;
}
if let Some(height) = paper_height {
document.paper_height = height;
}
let engine = Engine::layout(&document);
let json = render_json(&document, &engine, None);
// Keep the layout so a following `/edit` request can diff against it and
@@ -149,11 +161,17 @@ pub fn preview_json(source: &str) -> Result<String, String> {
/// Render the same checkpointed document as a route-D PDF.
pub fn pdf_bytes(source: &str) -> Result<Vec<u8>, String> {
let (body, origin) = strip_page_offsets(latex_body(source));
let (body, origin, paper_width, paper_height) = strip_page_geometry(latex_body(source));
let paragraphs = paragraphs(&body)?;
let mut document = build_document(&paragraphs);
document.h_offset = origin.h_offset;
document.v_offset = origin.v_offset;
if let Some(width) = paper_width {
document.paper_width = width;
}
if let Some(height) = paper_height {
document.paper_height = height;
}
let engine = Engine::layout(&document);
let pages: Vec<_> = engine
.pages()
@@ -161,14 +179,15 @@ pub fn pdf_bytes(source: &str) -> Result<Vec<u8>, String> {
.map(|page| {
let mut list =
page.display_list_with_layout(document.page_goal, document.text_float_sep);
list.width = list.width.max(PAGE_WIDTH_PT * SCALE);
list.height = list.height.max(PAGE_HEIGHT_PT * SCALE);
list.width = list.width.max(document.paper_width);
list.height = list.height.max(document.paper_height);
list
})
.collect();
Ok(display_lists_to_pdf_with_origin(
Ok(display_lists_to_pdf_with_paper(
&pages,
PAGE_HEIGHT_PT,
document.paper_width,
document.paper_height,
origin,
))
}
@@ -433,11 +452,17 @@ fn build_document(paragraphs: &[SourceParagraph]) -> Document {
fn render_json(document: &Document, engine: &Engine, edit: Option<(&[usize], usize)>) -> String {
let mut json = String::new();
json.push_str("{\"status\":\"ok\",\"pageWidthMm\":215.90,\"pageHeightMm\":279.40,\"pages\":[");
let page_width_mm = document.paper_width as f64 / SCALE as f64 * 25.4 / 72.0;
let page_height_mm = document.paper_height as f64 / SCALE as f64 * 25.4 / 72.0;
let page_height_pt = document.paper_height as f64 / SCALE as f64;
let _ = write!(
json,
"{{\"status\":\"ok\",\"pageWidthMm\":{page_width_mm:.2},\"pageHeightMm\":{page_height_mm:.2},\"pages\":["
);
for (index, page) in engine.pages().iter().enumerate() {
let mut list = page.display_list_with_layout(document.page_goal, document.text_float_sep);
list.width = list.width.max(PAGE_WIDTH_PT * SCALE);
list.height = list.height.max(PAGE_HEIGHT_PT * SCALE);
list.width = list.width.max(document.paper_width);
list.height = list.height.max(document.paper_height);
if index > 0 {
json.push(',');
}
@@ -456,7 +481,7 @@ fn render_json(document: &Document, engine: &Engine, edit: Option<(&[usize], usi
changed
);
}
json.push_str(",\"pageHeightPt\":792}");
let _ = write!(json, ",\"pageHeightPt\":{page_height_pt:.0}}}");
json
}
+40
View File
@@ -743,3 +743,43 @@ changed {long}
);
assert!(value["pages"].as_array().is_some());
}
#[test]
fn route_d_pdf_uses_declared_paper_size() {
let server = TestServer::start("route-d-pdf-paper");
let response = server.request(
"POST",
"/api/route-d/pdf",
b"\\paperwidth=300pt\n\\paperheight=400pt\n\nHello paper",
"text/plain",
);
assert_eq!(response.status, 200, "{}", response.text());
let text = String::from_utf8_lossy(&response.body);
assert!(
text.contains("/MediaBox [0 0 300.000 400.000]"),
"paper MediaBox missing"
);
}
#[test]
fn route_d_preview_reports_declared_paper_size() {
let server = TestServer::start("route-d-preview-paper");
let response = server.request(
"POST",
"/api/route-d/preview",
b"\\paperwidth=300pt\n\\paperheight=400pt\n\nHello paper",
"text/plain",
);
assert_eq!(response.status, 200, "{}", response.text());
let text = String::from_utf8_lossy(&response.body);
assert!(
text.contains("\"pageWidthMm\":105.83"),
"{}",
&text[..200.min(text.len())]
);
assert!(
text.contains("\"pageHeightMm\":141.11"),
"{}",
&text[..200.min(text.len())]
);
}