Justify route-D lines and compare ink bands with pdfTeX

This commit is contained in:
gloamxun committed 2026-10-22 19:45:31 +08:00
1 parent 93330a85ef
commit 4414f27438
4 files changed
+250 -7

No files matched your search

+2 -2
View File
@@ -466,7 +466,7 @@ from the font's MATH assembly parts. `\\left...\\right` target sizing follows
the assignable TeX parameters `\\delimiterfactor` (default 901) and
`\\delimitershortfall` (default 5pt), including local and global assignments.
Route-D integration can also be checked against a real TeX page: `cargo test -p texrra-tex-core --test route_d` includes `route_d_page_matches_pdftex_raster_geometry`, which renders the route-D PDF and a pdfTeX Letter page at the same scaled-point geometry, rasterizes both with `pdftoppm`, and compares ink line count plus left, right, and bottom edges. It is skipped when `pdflatex`/`pdftoppm` are unavailable.
Route-D integration can also be checked against a real TeX page: `cargo test -p texrra-tex-core --test route_d` includes `route_d_page_matches_pdftex_raster_geometry`, which renders the route-D PDF and a pdfTeX Letter page at the same scaled-point geometry, rasterizes both with `pdftoppm`, and compares ink line count plus left, right, and bottom edges. It is skipped when `pdflatex`/`pdftoppm` are unavailable. `route_d_multiline_bands_track_pdftex` extends that check to a wrapped paragraph: the pixel rows that carry ink form one band per TeX line, and every band top, bottom, left edge and (except for the last line, whose width follows the break point) right edge must land within a couple of pixels of the pdfTeX page.
Route-D float placement mirrors TeX fractions:
@@ -580,7 +580,7 @@ default until the new core reaches layout parity. See `docs/TEX_CORE.md`.
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, and the PDF `/W` array reports the same advances, so extracted text keeps word boundaries. 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::insertion_classes` caps each insertion class to a page fraction and defers overflow to the next page; `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.
SVG. Route-D paragraphs are laid out with CMR10 advances, kerns and ligatures; runs of two or three hyphens become en/em dashes, 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. 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::insertion_classes` caps each insertion class to a page fraction and defers overflow to the next page; `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
document and returns the same page list plus `changedPages` and
+64 -1
View File
@@ -282,7 +282,8 @@ pub fn layout_items(items: &[HorizontalItem], style: &ParagraphStyle) -> Paragra
ranges.reverse();
let mut lines = Vec::with_capacity(ranges.len());
let mut max_width = 0;
for (start, end) in ranges {
let line_count = ranges.len();
for (line_index, (start, end)) in ranges.into_iter().enumerate() {
let mut line: Vec<HorizontalItem> = Vec::new();
for (index, item) in items[start..end].iter().enumerate() {
match item {
@@ -317,6 +318,68 @@ pub fn layout_items(items: &[HorizontalItem], style: &ParagraphStyle) -> Paragra
) {
line.pop();
}
// Bake the justification into the line: TeX distributes the
// difference between the natural width and the measure across the
// glue, so the shipped line (and therefore the PDF) is flush.
let target = (style.line_width - style.left_skip - style.right_skip).max(1)
- if line_index == 0 { style.par_indent } else { 0 };
let (mut natural, mut stretch, mut shrink) = (0_i64, 0_i64, 0_i64);
for item in &line {
match item {
HorizontalItem::Box(box_item) => natural += box_item.width,
HorizontalItem::Glue {
width,
stretch: stretch_amount,
shrink: shrink_amount,
} => {
natural += *width;
stretch += *stretch_amount;
shrink += *shrink_amount;
}
HorizontalItem::Penalty { width, .. } => natural += *width,
HorizontalItem::Discretionary { .. } => {}
}
}
let is_last = line_index + 1 == line_count;
if !is_last {
let delta = target - natural;
if delta > 0 && stretch > 0 {
let mut remaining = delta;
for item in &mut line {
if let HorizontalItem::Glue {
width,
stretch: stretch_amount,
..
} = item
&& *stretch_amount > 0
{
let share = delta * *stretch_amount / stretch;
*width += share;
remaining -= share;
}
}
if remaining != 0
&& let Some(HorizontalItem::Glue { width, .. }) = line
.iter_mut()
.rev()
.find(|item| matches!(item, HorizontalItem::Glue { .. }))
{
*width += remaining;
}
} else if delta < 0 && shrink > 0 {
for item in &mut line {
if let HorizontalItem::Glue {
width,
shrink: shrink_amount,
..
} = item
&& *shrink_amount > 0
{
*width += delta * *shrink_amount / shrink;
}
}
}
}
let width: i64 = line
.iter()
.map(|item| match item {
+174
View File
@@ -485,3 +485,177 @@ fn route_d_text_matches_pdftex_extraction() {
let _ = std::fs::remove_dir_all(&dir);
assert_eq!(route, control);
}
/// Compare the vertical ink bands of a wrapped paragraph against pdfTeX. Band
/// boundaries are the pixel rows that actually contain glyphs, so this checks
/// baseline placement rather than just the count of text lines.
#[test]
fn route_d_multiline_bands_track_pdftex() {
use std::process::Command;
fn has(command: &str, version_arg: &str) -> bool {
Command::new(command)
.arg(version_arg)
.stdout(std::process::Stdio::null())
.stderr(std::process::Stdio::null())
.status()
.is_ok_and(|status| status.success())
}
if !has("pdflatex", "--version") || !has("pdftoppm", "-v") {
return;
}
fn bands(path: &std::path::Path) -> Vec<(usize, usize, usize, usize)> {
let bytes = std::fs::read(path).expect("read PGM");
assert_eq!(&bytes[..2], b"P5", "expected binary PGM");
let mut fields = Vec::new();
let mut cursor = 2;
while fields.len() < 3 {
while cursor < bytes.len() && bytes[cursor].is_ascii_whitespace() {
cursor += 1;
}
let start = cursor;
while cursor < bytes.len() && bytes[cursor].is_ascii_digit() {
cursor += 1;
}
fields.push(
std::str::from_utf8(&bytes[start..cursor])
.expect("PGM number")
.parse::<usize>()
.expect("PGM number"),
);
}
while cursor < bytes.len() && bytes[cursor].is_ascii_whitespace() {
cursor += 1;
}
let (width, height, _) = (fields[0], fields[1], fields[2]);
let pixels = &bytes[cursor..];
assert_eq!(pixels.len(), width * height, "PGM payload size");
let mut found: Vec<(usize, usize, usize, usize)> = Vec::new();
for y in 0..height {
let inked: Vec<usize> = (0..width).filter(|x| pixels[y * width + x] < 160).collect();
if inked.is_empty() {
continue;
}
let (row_left, row_right) = (inked[0], inked[inked.len() - 1]);
match found.last_mut() {
Some((_, end, left, right)) if y <= *end + 1 => {
*end = y;
*left = (*left).min(row_left);
*right = (*right).max(row_right);
}
_ => found.push((y, y, row_left, row_right)),
}
}
found
}
let text = "The quick brown fox jumps over the lazy dog while a second sentence keeps wrapping across several lines so that the baseline grid can be compared with a real TeX paragraph built from exactly the same words and the same measure.";
let style = ParagraphStyle {
line_width: 360 * 65_536,
left_skip: 0,
right_skip: 0,
centered: false,
right_aligned: false,
par_indent: 0,
line_height: 12 * 65_536,
char_width: 10 * 65_536,
space_width: 4 * 65_536,
space_stretch: 6 * 65_536,
space_shrink: 2 * 65_536,
};
let document = Document::new(
700 * 65_536,
vec![Unit::paragraph_with_style(1, text, style)],
);
let engine = Engine::layout(&document);
let pages: Vec<_> = engine
.pages()
.iter()
.map(|page| page.display_list())
.collect();
let route_pdf = display_lists_to_pdf(&pages, 792);
let root = std::env::temp_dir().join(format!("texrra-bands-{}", std::process::id()));
let _ = std::fs::remove_dir_all(&root);
std::fs::create_dir_all(&root).expect("create band dir");
let route_pdf_path = root.join("route.pdf");
std::fs::write(&route_pdf_path, route_pdf).expect("write route PDF");
let classic = format!(
r"\documentclass[10pt]{{article}}
\pagestyle{{empty}}
\hoffset=-1in
\voffset=-1in
\oddsidemargin=0pt
\topmargin=0pt
\headheight=0pt
\headsep=0pt
\pdfpagewidth=612bp
\pdfpageheight=792bp
\textwidth=360pt
\textheight=700pt
\topskip=10pt
\parindent=0pt
\begin{{document}}
{text}
\end{{document}}
"
);
let classic_path = root.join("classic.tex");
std::fs::write(&classic_path, classic).expect("write classic TeX");
let status = Command::new("pdflatex")
.args(["-interaction=nonstopmode", "-halt-on-error"])
.arg(&classic_path)
.current_dir(&root)
.stdout(std::process::Stdio::null())
.stderr(std::process::Stdio::null())
.status()
.expect("pdflatex");
assert!(status.success(), "pdflatex failed");
for pdf in [&route_pdf_path, &root.join("classic.pdf")] {
let status = Command::new("pdftoppm")
.args(["-r", "72", "-gray", "-singlefile"])
.arg(pdf)
.arg(pdf.with_extension(""))
.status()
.expect("pdftoppm");
assert!(status.success(), "pdftoppm failed for {}", pdf.display());
}
let route = bands(&root.join("route.pgm"));
let classic = bands(&root.join("classic.pgm"));
assert_eq!(
route.len(),
classic.len(),
"line bands: route={route:?} classic={classic:?}"
);
let last = route.len().saturating_sub(1);
for (index, (route_band, classic_band)) in route.iter().zip(&classic).enumerate() {
assert!(
(route_band.0 as i64 - classic_band.0 as i64).abs() <= 2,
"band {index} top: route={route_band:?} classic={classic_band:?}"
);
assert!(
(route_band.1 as i64 - classic_band.1 as i64).abs() <= 2,
"band {index} bottom: route={route_band:?} classic={classic_band:?}"
);
assert!(
(route_band.2 as i64 - classic_band.2 as i64).abs() <= 2,
"band {index} left: route={route_band:?} classic={classic_band:?}"
);
if index != last {
// Every line but the last is justified to the measure in both
// engines. The final line keeps its natural width and therefore
// reflects where TeX chose its last break, which the simplified
// demerits model does not yet reproduce exactly.
assert!(
(route_band.3 as i64 - classic_band.3 as i64).abs() <= 3,
"band {index} right: route={route_band:?} classic={classic_band:?}"
);
}
}
let _ = std::fs::remove_dir_all(&root);
}
+10 -4
View File
@@ -54,12 +54,18 @@ class execution are still ahead.
`tftopl`, plus the fontdimen space/stretch/shrink values;
- an item-stream Knuth-Plass-style dynamic program over character boxes, glue and penalty breakpoints that minimizes badness from
glue stretch/shrink, allows overfull lines with an explicit overfull penalty,
applies `par_indent` to the first line, and emits justified glue;
applies `par_indent` to the first line, and bakes the justification into the
glue widths of every non-final line;
- `Paragraph { lines, height, width }` and a paragraph-backed `Unit`.
M1 still does not hyphenate, process
`\discretionary`, use real TFM metrics or compare against pdfTeX. Those are the
next paragraph milestones.
M1 reads real CMR10 TFM metrics (advances, height/depth, italic correction,
kern pairs, ff/fi/fl/ffi/ffl ligatures and the fontdimen glue parameters),
hyphenates with the plain-TeX en-US patterns, and has pdfTeX fixtures for line
breaking. The demerits/tolerance model is still simplified: the final line keeps
its natural width and the last break can differ from TeX when a hyphenated break
would be slightly cheaper. `route_d_multiline_bands_track_pdftex` compares the
rasterized ink bands of a wrapped paragraph with pdfTeX, so baseline placement
and justification are covered for the lines both engines break the same way.
## Target architecture