Ship pages conditionally on parity in the output routine
This commit is contained in:
1 parent
a2a2eafab5
commit
7964765605
5 files changed
+66
-9
No files matched your search
@@ -589,7 +589,7 @@ execution, service and incrementality targets) is in
|
||||
The first M7 service integration is available as `POST /api/route-d/preview`, with PDF export at `POST /api/route-d/pdf`.
|
||||
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 floats and incremental replay gain paged equivalents. `Document::output_routine` runs an interpreted `\output` program (`\shipout\box255`, `\relax`, `\message`, `\ifdim` and `\ifnum` 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
|
||||
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 floats and incremental replay gain paged equivalents. `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
|
||||
|
||||
@@ -4896,6 +4896,19 @@ mod tests {
|
||||
assert_eq!(engine.pages().len(), 1);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn interpreted_output_can_ship_only_odd_pages() {
|
||||
let mut document = Document::new(100, Vec::new());
|
||||
document.output_routine = Some(r"\ifodd\pageno\shipout\box255\fi".to_owned());
|
||||
document.units = vec![
|
||||
Unit::rule(0, 10, 40),
|
||||
Unit::penalty(1, -10_000),
|
||||
Unit::rule(2, 10, 40),
|
||||
];
|
||||
let engine = Engine::layout_paged(&document).expect("paged layout");
|
||||
assert_eq!(engine.pages().len(), 1);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn paged_layout_expands_vertical_units() {
|
||||
let document = Document::new(
|
||||
|
||||
@@ -74,6 +74,11 @@ enum Op {
|
||||
then_ops: Vec<Op>,
|
||||
else_ops: Vec<Op>,
|
||||
},
|
||||
IfOdd {
|
||||
value: Integer,
|
||||
then_ops: Vec<Op>,
|
||||
else_ops: Vec<Op>,
|
||||
},
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
@@ -351,6 +356,27 @@ fn parse_sequence(tokens: &[Token], index: &mut usize, stop: &[&str]) -> Result<
|
||||
else_ops,
|
||||
});
|
||||
}
|
||||
"ifodd" => {
|
||||
*index += 1;
|
||||
let value = parse_integer(tokens, index)?;
|
||||
let then_ops = parse_sequence(tokens, index, &["else", "fi"])?;
|
||||
let mut else_ops = Vec::new();
|
||||
if let Some(Token::Command(name)) = tokens.get(*index)
|
||||
&& name == "else"
|
||||
{
|
||||
*index += 1;
|
||||
else_ops = parse_sequence(tokens, index, &["fi"])?;
|
||||
}
|
||||
match tokens.get(*index) {
|
||||
Some(Token::Command(name)) if name == "fi" => *index += 1,
|
||||
_ => return Err("\\ifodd is missing \\fi".to_owned()),
|
||||
}
|
||||
ops.push(Op::IfOdd {
|
||||
value,
|
||||
then_ops,
|
||||
else_ops,
|
||||
});
|
||||
}
|
||||
other => return Err(format!("unsupported \\output command `\\{other}`")),
|
||||
},
|
||||
token => return Err(format!("unexpected token {token:?}")),
|
||||
@@ -465,6 +491,14 @@ fn execute(ops: &[Op], context: &OutputContext, shipped: &mut usize) -> Result<(
|
||||
};
|
||||
execute(if taken { then_ops } else { else_ops }, context, shipped)?;
|
||||
}
|
||||
Op::IfOdd {
|
||||
value,
|
||||
then_ops,
|
||||
else_ops,
|
||||
} => {
|
||||
let odd = value.resolve(context).rem_euclid(2) == 1;
|
||||
execute(if odd { then_ops } else { else_ops }, context, shipped)?;
|
||||
}
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
@@ -540,6 +574,16 @@ mod tests {
|
||||
assert_eq!(program.shipout_count(&forced).unwrap(), 1);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn ifodd_ships_even_page_numbers_only() {
|
||||
let program = OutputProgram::parse(r"\ifodd\pageno\shipout\box255\else\relax\fi").unwrap();
|
||||
let mut context = context(0);
|
||||
context.pageno = 1;
|
||||
assert_eq!(program.shipout_count(&context).unwrap(), 1);
|
||||
context.pageno = 2;
|
||||
assert_eq!(program.shipout_count(&context).unwrap(), 0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn unsupported_commands_and_unbalanced_conditionals_are_errors() {
|
||||
assert!(OutputProgram::parse(r"\vbox{}").is_err());
|
||||
|
||||
@@ -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`). 349 workspace tests are green and no oracle
|
||||
PDF opt-in with `?engine=route-d`). 351 workspace tests are green and no oracle
|
||||
fixture is ignored.
|
||||
|
||||
Known gaps, in dependency order:
|
||||
@@ -268,7 +268,7 @@ dimension assignments from the source. Insertion classes are placed by the
|
||||
paged builder with their limits and held-over material; floats and checkpoint
|
||||
replay still fall back to the scrolling builder, which stays the default until
|
||||
it has a paged equivalent. Next: port those paths and paper margins, then extend the `\output`
|
||||
interpreter past the shipout/ifdim/ifnum subset.
|
||||
interpreter past the shipout/ifdim/ifnum/ifodd subset.
|
||||
|
||||
Acceptance: 10 page fixtures (article text, footnotes, floats, forced breaks);
|
||||
page counts identical and first/last baselines within 1pt of pdfLaTeX.
|
||||
@@ -411,7 +411,7 @@ Acceptance: corpus green or explicitly listed; CI documented.
|
||||
|
||||
| goal | phases | deliverable |
|
||||
| --- | --- | --- |
|
||||
| G1 (current) | P0, P1, P2 | TeX-exact paragraphs, vertical list, page builder, interpreted `\output` (shipout/ifdim/ifnum subset landed) |
|
||||
| G1 (current) | P0, P1, P2 | TeX-exact paragraphs, vertical list, page builder, interpreted `\output` (shipout/ifdim/ifnum/ifodd subset landed) |
|
||||
| G2 | P3, P4 | tables and math at L2/L3 |
|
||||
| G3 | P5 | Computer Modern fonts, NFSS, pixel parity for text/math |
|
||||
| G4 | P6 | class execution (article, journal) |
|
||||
|
||||
+5
-5
@@ -116,7 +116,7 @@ and justification.
|
||||
| --- | --- | --- |
|
||||
| M0 | vertical list, page builder, checkpoint, page hash, edit demo | edit on page 2 rebuilds only page 2 |
|
||||
| M1 | TeX box/glue/penalty + paragraph builder (`\par`, `\hsize`, `\parindent`) | **partial**: item stream, CMR10 metrics, TeX Live en-US hyphenation, TeX demerits and tolerance passes, `\hangindent`/`\parshape`, `\parfillskip`, sentence spacing, `\spaceskip`/`\xspaceskip`, `\looseness`, `\baselineskip`/`\lineskip`/`\parskip` interline glue, pdfLaTeX oracle matrix 90-240pt plus register, geometry, `\sfcode` and vertical-glue fixtures; generic fil glue and `\prevgraf` next |
|
||||
| M2 | page builder + `\output`, `\vsize`, `\topskip`, footnotes, floats | **partial**: `\vsize` page goal, `\topskip`, forced penalties, `Insertion` reserve, running `Mark`s, `OutputRoutine` hook, top/bottom `Float` placement; `page::PageBuilder` scores candidate breakpoints with TeX page badness, glue setting, `\topskip`/`\maxdepth`, and `Engine::layout_paged` uses it for documents whose units are single vertical items, while the scrolling builder remains the default; `\output` is interpreted for a `\shipout`/`\ifdim`/`\ifnum` subset; `\pageno`, `\outputpenalty` and `\deadcycles` are readable registers and `PageFragment::penalty` carries the break penalty |
|
||||
| M2 | page builder + `\output`, `\vsize`, `\topskip`, footnotes, floats | **partial**: `\vsize` page goal, `\topskip`, forced penalties, `Insertion` reserve, running `Mark`s, `OutputRoutine` hook, top/bottom `Float` placement; `page::PageBuilder` scores candidate breakpoints with TeX page badness, glue setting, `\topskip`/`\maxdepth`, and `Engine::layout_paged` uses it for documents whose units are single vertical items, while the scrolling builder remains the default; `\output` is interpreted for a `\shipout`/`\ifdim`/`\ifnum`/`\ifodd` subset; `\pageno`, `\outputpenalty` and `\deadcycles` are readable registers and `PageFragment::penalty` carries the break penalty |
|
||||
| M3 | `\halign`, `\omit`, `\span`, `\multispan`, booktabs/longtable | **partial**: source parsing, natural column widths, spans, rule rows, 10pt display-list painting and row-level page splitting; no booktabs/longtable parity yet |
|
||||
| M4 | math lists, scripts, fractions, radicals, accents, delimiters | **partial**: token parser, atom boxes with CMR10 metrics, delimiter scaling, accents and a display-list painter; no CMEX size variants or TeX math spacing classes yet |
|
||||
| M5 | NFSS/TFM metrics, CM/Latin Modern | same line/page breaks as reference |
|
||||
@@ -324,7 +324,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 eight unit tests, and 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` and `\ifnum` over the page registers, now including `\pageno`, `\outputpenalty` and `\deadcycles`), dropping pages the routine does not ship. Floats 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 eight unit tests, and 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` and `\ifodd` over the page registers, now including `\pageno`, `\outputpenalty` and `\deadcycles`), dropping pages the routine does not ship. Floats 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.
|
||||
|
||||
@@ -332,7 +332,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 231 unit tests plus seven route-D integration tests and thirteen oracle fixtures. Workspace verification: `cargo fmt --all -- --check`; `cargo test --workspace --offline` runs 349 tests (231 route-D unit, 7 route-D integration, 13 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 233 unit tests plus seven route-D integration tests and thirteen oracle fixtures. Workspace verification: `cargo fmt --all -- --check`; `cargo test --workspace --offline` runs 351 tests (233 route-D unit, 7 route-D integration, 13 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
|
||||
|
||||
@@ -371,11 +371,11 @@ deliberately open rather than approximated:
|
||||
stretch/shrink, `\topskip`, `\maxdepth`) and `Engine::layout_paged` runs it
|
||||
for simple documents, but floats and incremental replay need a paged
|
||||
equivalent before it can become the default; paper margins remain open, and
|
||||
the `\output` interpreter only covers the shipout/ifdim/ifnum subset (explicit
|
||||
the `\output` interpreter only covers the shipout/ifdim/ifnum/ifodd subset (explicit
|
||||
`\hoffset`/`\voffset` offsets are applied by the PDF writer).
|
||||
- **M5**: `cmr10.tfm` is parsed at runtime with widths, glyph heights/depths and kern pairs. only used text faces embed Liberation Serif/Mono as Type0/Identity-H; each face is subset to the glyphs actually used (composite components included, glyph IDs retained); FontFile2 and ToUnicode streams use Flate compression; the ToUnicode CMap follows the used characters; ff/fi/fl/ffi/ffl ligatures come from TFM, and CMR10 italic corrections are applied at line ends; full NFSS family switching is not implemented.
|
||||
- **M6**: `\output`, `\insert`, mark/float output policies, class-file execution and
|
||||
math limit policies are only partially modeled; `OutputRoutine::wants_break` can force a page break between units, and insertion material is stacked by class from the page bottom; `Document::output_routine` is interpreted per page by `output::OutputProgram` for the shipout/ifdim/ifnum subset (with `\pageno`, `\outputpenalty`, `\deadcycles`), while `OutputRoutine` remains the Rust hook.
|
||||
math limit policies are only partially modeled; `OutputRoutine::wants_break` can force a page break between units, and insertion material is stacked by class from the page bottom; `Document::output_routine` is interpreted per page by `output::OutputProgram` for the shipout/ifdim/ifnum/ifodd subset (with `\pageno`, `\outputpenalty`, `\deadcycles`), while `OutputRoutine` remains the Rust hook.
|
||||
- Page hashes cover rendered items/insertions/marks/floats, not source-dependency
|
||||
metadata, so replaying an earlier page cannot change its hash merely by
|
||||
re-attaching source hashes.
|
||||
|
||||
Reference in new issue
Block a user