Compare route-D page breaks with pdfLaTeX

This commit is contained in:
gloamxun committed 2026-10-23 03:40:08 +08:00
1 parent c5b3493998
commit 6c3636c7c5
3 files changed
+198 -3

No files matched your search

+193 -1
View File
@@ -10,7 +10,7 @@ use std::process::Command;
use std::sync::atomic::{AtomicU64, Ordering};
use texrra_tex_core::paragraph::{HorizontalItem, ParagraphStyle};
use texrra_tex_core::{Unit, VerticalItem};
use texrra_tex_core::{Document, Engine, Unit, VerticalItem};
/// Scaled points per TeX point.
const PT: i64 = 65_536;
@@ -212,6 +212,95 @@ fn route_d_lines_with(
lines
}
/// Keep only characters that survive both extractors: pdfTeX splits words at
/// line ends with a hyphen, which this strips as well.
fn alnum(text: &str) -> String {
text.chars()
.filter(|character| character.is_ascii_alphanumeric())
.collect()
}
/// Compile `source` with pdfLaTeX and return the alphanumeric text of each page.
fn pdftex_pages(source: &str) -> Option<Vec<String>> {
let dir = temp_dir("pdftex-pages");
fs::write(dir.join("main.tex"), source).expect("write fixture");
let latex = Command::new("pdflatex")
.args(["-interaction=nonstopmode", "-halt-on-error", "main.tex"])
.current_dir(&dir)
.output();
let latex = match latex {
Ok(output) => output,
Err(error) if tool_missing(&error) => return None,
Err(error) => panic!("run pdflatex: {error}"),
};
assert!(
latex.status.success(),
"pdflatex failed: {}",
String::from_utf8_lossy(&latex.stdout)
);
let text = Command::new("pdftotext")
.arg(dir.join("main.pdf"))
.arg("-")
.output();
let text = match text {
Ok(output) => output,
Err(error) if tool_missing(&error) => return None,
Err(error) => panic!("run pdftotext: {error}"),
};
let text = String::from_utf8_lossy(&text.stdout);
Some(
text.split('\u{c}')
.map(alnum)
.filter(|page| !page.is_empty())
.collect(),
)
}
fn page_alnum_text(page: &texrra_tex_core::Page) -> String {
let mut text = String::new();
for item in &page.items {
let VerticalItem::Paragraph(paragraph) = item else {
continue;
};
for line in &paragraph.lines {
for item in line {
if let HorizontalItem::Box(box_) = item
&& let Some(character) = box_.character
&& character.is_ascii_alphanumeric()
{
text.push(character);
}
}
}
}
text
}
/// Lay `paragraphs` out with the route-D scrolling builder using article
/// metrics that match the pdfTeX fixtures (`\hsize` 345pt, `\topskip` 12pt,
/// `\vsize` 550pt, `\parskip` 0).
fn route_pages_text(paragraphs: &[String], par_skip: i64) -> Vec<String> {
let mut units = Vec::new();
for (index, text) in paragraphs.iter().enumerate() {
let style = ParagraphStyle {
line_width: 345 * PT,
par_indent: 15 * PT,
line_height: 12 * PT,
..ParagraphStyle::default()
};
units.push(Unit::paragraph_with_style(index as u64 + 1, text, style));
}
let mut document = Document::new(550 * PT, units);
document.top_skip = 12 * PT;
document.par_skip = par_skip * PT;
document.text_float_sep = 0;
Engine::layout(&document)
.pages()
.iter()
.map(page_alnum_text)
.collect()
}
fn assert_lines_match(label: &str, ours: &[Line], reference: &[Line]) {
assert_eq!(
ours.len(),
@@ -390,6 +479,109 @@ fn explicit_sfcode_matches_pdftex() {
});
}
#[test]
fn pages_break_like_pdftex_for_single_line_paragraphs() {
let paragraphs: Vec<String> = (0..100)
.map(|index| format!("p{index} alpha beta gamma"))
.collect();
let body: String = paragraphs
.iter()
.map(|paragraph| format!("{paragraph}\\par\n"))
.collect();
let source = format!(
"\\documentclass[10pt]{{article}}\n\
\\pdfpagewidth=612bp \\pdfpageheight=792bp\n\
\\pagestyle{{empty}}\n\
\\begin{{document}}\n\
\\hsize=345pt \\parindent=15pt \\parskip=0pt \\topskip=12pt \\vsize=550pt\n\
{body}\\end{{document}}\n"
);
let Some(reference) = pdftex_pages(&source) else {
eprintln!("skipping: pdflatex/pdftotext are not installed");
return;
};
let ours = route_pages_text(&paragraphs, 0);
assert_eq!(
ours.len(),
reference.len(),
"route-D produced {} pages, pdfLaTeX {}",
ours.len(),
reference.len()
);
for (index, (ours, reference)) in ours.iter().zip(&reference).enumerate() {
assert_eq!(ours, reference, "text on page {}", index + 1);
}
}
#[test]
fn pages_break_like_pdftex_with_paragraph_spacing() {
let paragraphs: Vec<String> = (0..90)
.map(|index| format!("p{index} alpha beta gamma"))
.collect();
let body: String = paragraphs
.iter()
.map(|paragraph| format!("{paragraph}\\par\n"))
.collect();
let source = format!(
"\\documentclass[10pt]{{article}}\n\
\\pdfpagewidth=612bp \\pdfpageheight=792bp\n\
\\pagestyle{{empty}}\n\
\\begin{{document}}\n\
\\hsize=345pt \\parindent=15pt \\parskip=6pt \\topskip=12pt \\vsize=550pt\n\
{body}\\end{{document}}\n"
);
let Some(reference) = pdftex_pages(&source) else {
eprintln!("skipping: pdflatex/pdftotext are not installed");
return;
};
let ours = route_pages_text(&paragraphs, 6);
assert_eq!(
ours.len(),
reference.len(),
"route-D produced {} pages, pdfLaTeX {}",
ours.len(),
reference.len()
);
for (index, (ours, reference)) in ours.iter().zip(&reference).enumerate() {
assert_eq!(ours, reference, "text on page {}", index + 1);
}
}
#[test]
fn pages_split_paragraphs_like_pdftex() {
let sentence = "alpha beta gamma delta epsilon zeta eta theta iota kappa. ";
let paragraphs: Vec<String> = (0..20)
.map(|index| format!("p{index} {}", sentence.repeat(3)))
.collect();
let body: String = paragraphs
.iter()
.map(|paragraph| format!("{paragraph}\\par\n"))
.collect();
let source = format!(
"\\documentclass[10pt]{{article}}\n\
\\pdfpagewidth=612bp \\pdfpageheight=792bp\n\
\\pagestyle{{empty}}\n\
\\begin{{document}}\n\
\\hsize=345pt \\parindent=15pt \\parskip=0pt \\topskip=12pt \\vsize=550pt\n\
{body}\\end{{document}}\n"
);
let Some(reference) = pdftex_pages(&source) else {
eprintln!("skipping: pdflatex/pdftotext are not installed");
return;
};
let ours = route_pages_text(&paragraphs, 0);
assert_eq!(
ours.len(),
reference.len(),
"route-D produced {} pages, pdfLaTeX {}",
ours.len(),
reference.len()
);
for (index, (ours, reference)) in ours.iter().zip(&reference).enumerate() {
assert_eq!(ours, reference, "text on page {}", index + 1);
}
}
#[test]
fn paragraph_breaks_match_pdftex_at_150pt() {
compare_fixture(WORDS, 150);
+3
View File
@@ -279,6 +279,9 @@ interpreter past the shipout/ifdim/ifnum/ifodd/ifcase subset.
Acceptance: 10 page fixtures (article text, footnotes, floats, forced breaks);
page counts identical and first/last baselines within 1pt of pdfLaTeX.
Progress: three page fixtures are wired (single-line paragraphs, `\parskip=6pt`
spacing, and multi-line paragraphs split across pages); each asserts the same
page count and the same per-page text as pdfLaTeX.
### P3 — `\halign` / `\valign` (L2)
+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 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`, `\ifodd` and `\ifcase` 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`, `\ifodd` and `\ifcase` 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. 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 244 unit tests plus seven route-D integration tests and thirteen oracle fixtures. Workspace verification: `cargo fmt --all -- --check`; `cargo test --workspace --offline` runs 362 tests (244 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 244 unit tests plus seven route-D integration tests and sixteen oracle fixtures. Workspace verification: `cargo fmt --all -- --check`; `cargo test --workspace --offline` runs 365 tests (244 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.
### M0 incremental demo