Apply TeX page offsets in the route-D PDF endpoint
This commit is contained in:
1 parent
5db7acaff2
commit
8d319b3b0c
5 files changed
+75
-11
No files matched your search
@@ -584,7 +584,9 @@ 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, while the scrolling builder remains the default until floats, insertions and incremental replay gain paged equivalents. 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.
|
||||
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.
|
||||
`Document::insertion_classes` caps each insertion class to a page fraction and defers overflow to the next page, 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. 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; 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
|
||||
|
||||
@@ -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`). 316 workspace tests are green and no oracle
|
||||
PDF opt-in with `?engine=route-d`). 317 workspace tests are green and no oracle
|
||||
fixture is ignored.
|
||||
|
||||
Known gaps, in dependency order:
|
||||
@@ -251,7 +251,8 @@ 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`. Floats, insertions and checkpoint replay still fall back
|
||||
with `pdftotext -bbox`, and the PDF endpoint reads leading `\hoffset`/`\voffset`
|
||||
dimension assignments from the source. Floats, insertions and checkpoint replay still fall back
|
||||
to the scrolling builder, which stays the default until it has a paged
|
||||
equivalent. Next: port those paths, then paper margins, held-over insertion
|
||||
material and the interpreted `\output`.
|
||||
|
||||
+2
-2
@@ -304,7 +304,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 seven unit tests. `Engine::layout_paged` now builds pages through it for documents whose units are single vertical items (boxes, rules, paragraphs, math, haligns, glue, penalties and marks); `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. `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`. Floats, insertions and the incremental checkpoint replay still use the scrolling builder, which remains the default until those pieces have a paged equivalent.
|
||||
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 seven unit tests. `Engine::layout_paged` now builds pages through it for documents whose units are single vertical items (boxes, rules, paragraphs, math, haligns, glue, penalties and marks); `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. `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. Floats, insertions and the incremental checkpoint replay still use the scrolling builder, which remains the default until those pieces have a paged equivalent.
|
||||
|
||||
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.
|
||||
|
||||
@@ -312,7 +312,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 204 unit tests plus seven route-D integration tests and eight oracle fixtures. Workspace verification: `cargo fmt --all -- --check`; `cargo test --workspace --offline` runs 316 tests (204 route-D unit, 7 route-D integration, 8 oracle, 71 v1 integration, 19 server, 4 v1 unit, 1 core unit, 2 binary units), with none ignored. v1 remains the live server path.
|
||||
The crate currently has 204 unit tests plus seven route-D integration tests and eight oracle fixtures. Workspace verification: `cargo fmt --all -- --check`; `cargo test --workspace --offline` runs 317 tests (204 route-D unit, 7 route-D integration, 8 oracle, 71 v1 integration, 20 server, 4 v1 unit, 1 core unit, 2 binary units), with none ignored. v1 remains the live server path.
|
||||
|
||||
### M0 incremental demo
|
||||
|
||||
|
||||
+50
-6
@@ -89,6 +89,50 @@ 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) {
|
||||
let mut origin = PageOrigin::default();
|
||||
let mut body = String::new();
|
||||
for line in source.lines() {
|
||||
let trimmed = line.trim();
|
||||
if let Some(value) = dimension_assignment(trimmed, "hoffset") {
|
||||
origin.h_offset = value;
|
||||
} else if let Some(value) = dimension_assignment(trimmed, "voffset") {
|
||||
origin.v_offset = value;
|
||||
} else {
|
||||
body.push_str(line);
|
||||
body.push('\n');
|
||||
}
|
||||
}
|
||||
(body, origin)
|
||||
}
|
||||
|
||||
fn dimension_assignment(line: &str, name: &str) -> Option<i64> {
|
||||
let rest = line.strip_prefix('\\')?;
|
||||
let rest = rest.strip_prefix(name)?;
|
||||
let rest = rest.trim_start().strip_prefix('=')?;
|
||||
parse_dimension(rest.trim())
|
||||
}
|
||||
|
||||
fn parse_dimension(text: &str) -> Option<i64> {
|
||||
let end = text
|
||||
.find(|character: char| {
|
||||
!(character.is_ascii_digit() || character == '.' || character == '-')
|
||||
})
|
||||
.unwrap_or(text.len());
|
||||
let number: f64 = text[..end].parse().ok()?;
|
||||
let factor = match text[end..].trim() {
|
||||
"pt" => 1.0,
|
||||
"bp" => 72.27 / 72.0,
|
||||
"in" => 72.27,
|
||||
"cm" => 72.27 / 2.54,
|
||||
"mm" => 72.27 / 25.4,
|
||||
_ => return None,
|
||||
};
|
||||
Some((number * factor * 65_536.0).round() as 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)?;
|
||||
@@ -99,8 +143,11 @@ 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 paragraphs = paragraphs(latex_body(source))?;
|
||||
let document = build_document(¶graphs);
|
||||
let (body, origin) = strip_page_offsets(latex_body(source));
|
||||
let paragraphs = paragraphs(&body)?;
|
||||
let mut document = build_document(¶graphs);
|
||||
document.h_offset = origin.h_offset;
|
||||
document.v_offset = origin.v_offset;
|
||||
let engine = Engine::layout(&document);
|
||||
let pages: Vec<_> = engine
|
||||
.pages()
|
||||
@@ -115,10 +162,7 @@ pub fn pdf_bytes(source: &str) -> Result<Vec<u8>, String> {
|
||||
Ok(display_lists_to_pdf_with_origin(
|
||||
&pages,
|
||||
PAGE_HEIGHT_PT,
|
||||
PageOrigin {
|
||||
h_offset: document.h_offset,
|
||||
v_offset: document.v_offset,
|
||||
},
|
||||
origin,
|
||||
))
|
||||
}
|
||||
|
||||
|
||||
@@ -594,6 +594,23 @@ fn route_d_pdf_renders_itemize_content() {
|
||||
assert!(response.body.len() > 500);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn route_d_pdf_applies_page_offsets() {
|
||||
let server = TestServer::start("route-d-pdf-origin");
|
||||
let response = server.request(
|
||||
"POST",
|
||||
"/api/route-d/pdf",
|
||||
b"\\voffset=20pt\n\nHello origin",
|
||||
"text/plain",
|
||||
);
|
||||
assert_eq!(response.status, 200, "{}", response.text());
|
||||
let text = String::from_utf8_lossy(&response.body);
|
||||
assert!(
|
||||
text.contains("1 0 0 1 0.000 -20.000 cm"),
|
||||
"page origin translation missing"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn edits_route_d_list_units() {
|
||||
let server = TestServer::start("route-d-edit-list");
|
||||
|
||||
Reference in new issue
Block a user