Files
texrra-engine/crates/texrra-tex-core/tests/oracle.rs
T
gloamxun 8ac2e828df Honour club and widow penalties on paragraph lines
Route-D expanded a paragraph into one node per line without TeX's
\clubpenalty/\widowpenalty, so a page break could orphan the first line or
widow the last. Insert the penalties between line nodes (150 by default, read
from the source registers) and make the page builder reject any penalty of
10000 or more as a breakpoint. Forced -10000 values now break exactly where
pdfLaTeX does; two page oracle fixtures compare per-page text, and unit tests
cover the node order and the forbidden breakpoint.
2026-10-26 22:14:01 +08:00

1642 lines
56 KiB
Rust

//! Oracle tests: compare route-D layout with a real pdfLaTeX run.
//!
//! The harness compiles a small document with `pdflatex`, extracts word boxes
//! with `pdftotext -bbox`, and compares them with the boxes route-D produced.
//! Tests skip (and say so) when the TeX tools are not installed.
use std::fs;
use std::path::PathBuf;
use std::process::Command;
use std::sync::atomic::{AtomicU64, Ordering};
use texrra_tex_core::paragraph::{HorizontalItem, ParagraphStyle};
use texrra_tex_core::{Document, Engine, FloatPlacement, Unit, VerticalItem, layout_paragraph};
/// Scaled points per TeX point.
const PT: i64 = 65_536;
/// pdfTeX writes PDF units (`bp`); TeX points are slightly larger.
const BP_TO_PT: f64 = 72.27 / 72.0;
#[derive(Clone, Debug)]
struct Word {
text: String,
/// Offset from the start of its line, in TeX points.
x: f64,
/// Absolute left edge on the page, in TeX points.
#[allow(dead_code)]
abs_x: f64,
/// Absolute top edge on the page, in TeX points.
#[allow(dead_code)]
abs_y: f64,
}
#[derive(Clone, Debug)]
struct Line {
words: Vec<Word>,
/// Absolute x of the line's first word in TeX points (page origin).
#[allow(dead_code)]
start: f64,
}
fn temp_dir(tag: &str) -> PathBuf {
static COUNTER: AtomicU64 = AtomicU64::new(0);
let dir = std::env::temp_dir().join(format!(
"texrra-oracle-{}-{}-{tag}",
std::process::id(),
COUNTER.fetch_add(1, Ordering::Relaxed)
));
let _ = fs::remove_dir_all(&dir);
fs::create_dir_all(&dir).expect("create temp dir");
dir
}
fn tool_missing(error: &std::io::Error) -> bool {
error.kind() == std::io::ErrorKind::NotFound
}
/// Run pdfLaTeX on `source` and return its per-line words, or `None` when the
/// host has no TeX installation.
fn pdftex_lines(source: &str) -> Option<Vec<Line>> {
let dir = temp_dir("pdftex");
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!("could not run pdflatex: {error}"),
};
assert!(
latex.status.success(),
"pdflatex rejected the fixture:\n{}",
String::from_utf8_lossy(&latex.stdout)
);
let text = Command::new("pdftotext")
.args(["-bbox", "main.pdf", "words.xhtml"])
.current_dir(&dir)
.output();
let text = match text {
Ok(output) => output,
Err(error) if tool_missing(&error) => return None,
Err(error) => panic!("could not run pdftotext: {error}"),
};
assert!(text.status.success(), "pdftotext failed");
let xhtml = fs::read_to_string(dir.join("words.xhtml")).expect("read bbox output");
let _ = fs::remove_dir_all(&dir);
Some(parse_bbox(&xhtml))
}
fn attr(tag: &str, name: &str) -> f64 {
let needle = format!("{name}=\"");
let start = tag
.find(&needle)
.unwrap_or_else(|| panic!("no {name} in {tag}"))
+ needle.len();
let end = tag[start..].find('"').expect("attribute end") + start;
tag[start..end].parse().expect("numeric attribute")
}
fn unescape(text: &str) -> String {
text.replace("&amp;", "&")
.replace("&lt;", "<")
.replace("&gt;", ">")
.replace("&quot;", "\"")
.replace("&apos;", "'")
}
fn parse_bbox(xhtml: &str) -> Vec<Line> {
let mut words: Vec<(f64, f64, String)> = Vec::new();
let mut rest = xhtml;
while let Some(start) = rest.find("<word ") {
let tag_end = start + rest[start..].find('>').expect("word tag end");
let close = tag_end + rest[tag_end..].find("</word>").expect("word close");
let tag = &rest[start..=tag_end];
let text = unescape(&rest[tag_end + 1..close]);
words.push((attr(tag, "xMin"), attr(tag, "yMin"), text));
rest = &rest[close + "</word>".len()..];
}
// pdftotext does not always emit words in reading order: wide justified
// gaps and hyphenated lines can interleave words from different baselines.
// Sort by baseline, then by x, before grouping into lines.
words.sort_by(|a, b| {
a.1.partial_cmp(&b.1)
.expect("bbox y is finite")
.then(a.0.partial_cmp(&b.0).expect("bbox x is finite"))
});
let mut lines: Vec<Line> = Vec::new();
let mut current_y = f64::NAN;
for (x_min, y_min, text) in words {
if lines.is_empty() || (y_min - current_y).abs() > 2.0 {
lines.push(Line {
words: Vec::new(),
start: 0.0,
});
current_y = y_min;
}
lines.last_mut().expect("line").words.push(Word {
text,
x: x_min,
abs_x: x_min * BP_TO_PT,
abs_y: y_min * BP_TO_PT,
});
}
for line in &mut lines {
let origin = line.words.first().map(|word| word.x).unwrap_or(0.0);
line.start = origin * BP_TO_PT;
for word in &mut line.words {
word.x = (word.x - origin) * BP_TO_PT;
}
}
lines
}
/// Flatten pdfLaTeX word boxes into absolute page positions.
fn tex_word_positions(source: &str) -> Option<Vec<(String, f64, f64)>> {
let lines = pdftex_lines(source)?;
Some(
lines
.into_iter()
.flat_map(|line| line.words)
.map(|word| (word.text, word.abs_x, word.abs_y))
.collect(),
)
}
/// Lay out a paragraph after applying paragraph-register overrides.
fn route_d_lines_with(
text: &str,
width_pt: f64,
configure: impl FnOnce(&mut ParagraphStyle),
) -> Vec<Line> {
let width = (width_pt * PT as f64).round() as i64;
let mut style = ParagraphStyle {
line_width: width,
left_skip: 0,
right_skip: 0,
centered: false,
right_aligned: false,
looseness: 0,
par_indent: 0,
line_height: 12 * PT,
..ParagraphStyle::default()
};
configure(&mut style);
let unit = Unit::paragraph_with_style(0, text, style);
let paragraph = match unit.items.first() {
Some(VerticalItem::Paragraph(paragraph)) => paragraph,
other => panic!("expected a paragraph unit, got {other:?}"),
};
let mut lines = Vec::new();
for (line_number, line) in paragraph.lines.iter().enumerate() {
let indent = paragraph
.line_indents
.get(line_number)
.copied()
.unwrap_or(0);
let mut x = (paragraph.left_skip + indent) as f64 / PT as f64;
let mut words: Vec<Word> = Vec::new();
let mut word = String::new();
let mut word_x = 0.0;
for item in line {
match item {
HorizontalItem::Box(box_) => {
if let Some(character) = box_.character {
if word.is_empty() {
word_x = x;
}
word.push(character);
}
x += box_.width as f64 / PT as f64;
}
HorizontalItem::Glue { width, .. } => {
if !word.is_empty() {
words.push(Word {
text: std::mem::take(&mut word),
x: word_x,
abs_x: 0.0,
abs_y: 0.0,
});
}
x += *width as f64 / PT as f64;
}
HorizontalItem::Penalty { .. } | HorizontalItem::Discretionary { .. } => {}
}
}
if !word.is_empty() {
words.push(Word {
text: word,
x: word_x,
abs_x: 0.0,
abs_y: 0.0,
});
}
let start = words.first().map(|word| word.x).unwrap_or(0.0);
if let Some(origin) = words.first().map(|word| word.x) {
for word in &mut words {
word.x -= origin;
}
}
lines.push(Line { words, start });
}
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> {
route_pages_text_with(paragraphs, par_skip, 550, 12)
}
fn route_pages_text_with(
paragraphs: &[String],
par_skip: i64,
page_goal_pt: i64,
top_skip_pt: i64,
) -> Vec<String> {
route_pages_text_with_penalties(paragraphs, par_skip, page_goal_pt, top_skip_pt, 150, 150)
}
fn route_document_with_penalties(
paragraphs: &[String],
par_skip: i64,
page_goal_pt: i64,
top_skip_pt: i64,
club_penalty: i64,
widow_penalty: i64,
) -> Document {
let mut units = Vec::new();
let mut page_breaks = Vec::new();
for text in paragraphs {
if text.trim() == "\\newpage" || text.trim() == "\\clearpage" {
page_breaks.push(units.len());
continue;
}
let style = ParagraphStyle {
line_width: 345 * PT,
par_indent: 15 * PT,
line_height: 12 * PT,
..ParagraphStyle::default()
};
units.push(Unit::paragraph_with_style(
units.len() as u64 + 1,
text,
style,
));
}
let mut document = Document::new(page_goal_pt * PT, units);
document.page_breaks = page_breaks;
document.top_skip = top_skip_pt * PT;
document.par_skip = par_skip * PT;
document.club_penalty = club_penalty;
document.widow_penalty = widow_penalty;
document.text_float_sep = 0;
// LaTeX's default \maxdepth keeps descents out of the page height.
document.max_depth = 5 * PT;
document
}
fn route_pages_text_with_penalties(
paragraphs: &[String],
par_skip: i64,
page_goal_pt: i64,
top_skip_pt: i64,
club_penalty: i64,
widow_penalty: i64,
) -> Vec<String> {
let document = route_document_with_penalties(
paragraphs,
par_skip,
page_goal_pt,
top_skip_pt,
club_penalty,
widow_penalty,
);
Engine::layout(&document)
.pages()
.iter()
.map(page_alnum_text)
.collect()
}
/// Lay out through the TeX page builder (`document_nodes`), the path route-D
/// previews and PDFs use; club/widow penalties are inserted between lines.
fn route_paged_text_with_penalties(
paragraphs: &[String],
par_skip: i64,
page_goal_pt: i64,
top_skip_pt: i64,
club_penalty: i64,
widow_penalty: i64,
) -> Vec<String> {
let document = route_document_with_penalties(
paragraphs,
par_skip,
page_goal_pt,
top_skip_pt,
club_penalty,
widow_penalty,
);
Engine::layout_paged(&document)
.expect("paged layout")
.pages()
.iter()
.map(page_alnum_text)
.collect()
}
fn assert_lines_match(label: &str, ours: &[Line], reference: &[Line]) {
assert_eq!(
ours.len(),
reference.len(),
"{label}: route-D produced {} lines, pdfLaTeX {}",
ours.len(),
reference.len()
);
for (index, (ours, reference)) in ours.iter().zip(reference).enumerate() {
let our_words: Vec<&str> = ours.words.iter().map(|word| word.text.as_str()).collect();
let their_words: Vec<&str> = reference
.words
.iter()
.map(|word| word.text.as_str())
.collect();
assert_eq!(
our_words,
their_words,
"{label}: words on line {}",
index + 1
);
for (offset, (our, their)) in ours.words.iter().zip(&reference.words).enumerate() {
let drift = (our.x - their.x).abs();
assert!(
drift <= 0.05,
"{label}: line {} word {} ({}) drifted {drift:.4}pt",
index + 1,
offset + 1,
our.text
);
}
}
}
fn paragraph_fixture_with(text: &str, width_pt: u32, prefix: &str) -> String {
format!(
"\\documentclass[10pt]{{article}}\n\
\\pdfpagewidth=612bp \\pdfpageheight=792bp\n\
\\pagestyle{{empty}}\n\
\\begin{{document}}\n\
\\hsize={width_pt}pt \\parindent=0pt {prefix}\\noindent {text}\\par\n\
\\end{{document}}\n"
)
}
/// Like `paragraph_fixture_with`, but leaves the first-line indent active so
/// `\parindent` fixtures can exercise it.
fn indented_paragraph_fixture(text: &str, width_pt: u32, prefix: &str) -> String {
format!(
"\\documentclass[10pt]{{article}}\n\
\\pdfpagewidth=612bp \\pdfpageheight=792bp\n\
\\pagestyle{{empty}}\n\
\\begin{{document}}\n\
\\hsize={width_pt}pt \\parindent=0pt {prefix}{text}\\par\n\
\\end{{document}}\n"
)
}
const WORDS: &str = "alpha beta gamma delta epsilon zeta eta theta iota kappa lambda mu";
fn compare_fixture(text: &str, width_pt: u32) {
compare_fixture_with(text, width_pt, "", |_| {});
}
fn compare_fixture_with(
text: &str,
width_pt: u32,
tex_prefix: &str,
configure: impl FnOnce(&mut ParagraphStyle),
) {
let Some(reference) = pdftex_lines(&paragraph_fixture_with(text, width_pt, tex_prefix)) else {
eprintln!("skipping: pdflatex/pdftotext are not installed");
return;
};
let ours = route_d_lines_with(text, f64::from(width_pt), configure);
assert_lines_match(&format!("{width_pt}pt {tex_prefix}"), &ours, &reference);
}
/// `\pretolerance` lets pass 0 accept very loose lines and stops the breaker
/// before hyphenation is enabled.
#[test]
fn pretolerance_skips_hyphenation_like_tex() {
compare_fixture_with(WORDS, 120, "\\pretolerance=10000 ", |style| {
style.pretolerance = 10_000;
});
}
/// `\tolerance=10000` accepts arbitrarily bad underfull lines in the
/// tolerance pass, so the breaker must consider very loose breaks.
#[test]
fn tolerance_10000_matches_pdftex() {
for width in [100, 120, 150, 180, 200, 240] {
compare_fixture_with(WORDS, width, "\\tolerance=10000 ", |style| {
style.tolerance = 10_000;
});
}
}
/// A narrow measure exercises TeX's `\pretolerance` pass: loose one-word
/// lines are feasible there, so the breaker must not hyphenate them itself.
#[test]
fn narrow_measure_pretolerance_matches_pdftex() {
let text = "hyphenation demonstrates discretionary representation according extraordinary understanding";
for width in [70, 85] {
compare_fixture_with(
text,
width,
"\\pretolerance=10000 \\tolerance=200 ",
|style| {
style.pretolerance = 10_000;
style.tolerance = 200;
},
);
}
}
/// `\hyphenpenalty=10000` makes hyphenation illegal, so the final pass keeps
/// overfull lines instead.
#[test]
fn hyphen_penalty_inhibits_hyphenation() {
compare_fixture_with(WORDS, 120, "\\hyphenpenalty=10000 ", |style| {
style.hyphen_penalty = 10_000;
});
}
/// `\raggedright` leaves an infinite `fil` in `\rightskip`, so lines stop at
/// their natural widths instead of stretching to the measure.
#[test]
fn ragged_right_matches_pdftex() {
compare_fixture_with(WORDS, 150, "\\raggedright ", |style| {
style.ragged_right = true;
});
}
/// `\leftskip` plus `\rightskip` narrow the measure exactly like pdfLaTeX,
/// so the line breaks and relative word positions must match.
#[test]
fn left_skip_and_right_skip_match_pdftex() {
compare_fixture_with(
WORDS,
150,
"\\leftskip=20pt \\rightskip=30pt\\relax ",
|style| {
style.left_skip = 20 * PT;
style.right_skip = 30 * PT;
},
);
}
/// `\hangindent`/`\hangafter` shift the affected lines and narrow their
/// measure exactly like pdfLaTeX.
#[test]
fn hang_indent_shifts_lines_like_tex() {
let width = 120;
let Some(reference) = pdftex_lines(&paragraph_fixture_with(
WORDS,
width,
"\\hangindent=20pt\\hangafter=1\\relax ",
)) else {
eprintln!("skipping: pdflatex/pdftotext are not installed");
return;
};
let ours = route_d_lines_with(WORDS, f64::from(width), |style| {
style.hang_indent = 20 * PT;
style.hang_after = 1;
});
assert_lines_match("hangindent 120pt", &ours, &reference);
assert!(ours.len() >= 3, "fixture must span at least three lines");
for index in 1..ours.len() {
let our_step = ours[index].start - ours[index - 1].start;
let tex_step = reference[index].start - reference[index - 1].start;
assert!(
(our_step - tex_step).abs() <= 0.1,
"line {} moved {our_step:.3}pt, pdfLaTeX {tex_step:.3}pt",
index + 1
);
}
assert!(
ours[1].start - ours[0].start > 18.0,
"the second line must start 20pt further right"
);
}
/// A paragraph whose `\parfillskip` has no `fil` must justify its final
/// line, so every line matches pdfLaTeX.
#[test]
fn parfillskip_without_fil_justifies_the_last_line() {
let width = 120;
let Some(reference) = pdftex_lines(&paragraph_fixture_with(WORDS, width, "\\parfillskip=0pt "))
else {
eprintln!("skipping: pdflatex/pdftotext are not installed");
return;
};
let ours = route_d_lines_with(WORDS, f64::from(width), |style| {
style.par_fillskip_fil = false;
});
assert_lines_match("parfillskip 120pt", &ours, &reference);
}
/// `\parindent` only narrows the first line; the break positions must match
/// pdfLaTeX with the indent active.
#[test]
fn par_indent_matches_pdftex() {
let width = 120;
let Some(reference) = pdftex_lines(&indented_paragraph_fixture(
WORDS,
width,
"\\parindent=30pt ",
)) else {
eprintln!("skipping: pdflatex/pdftotext are not installed");
return;
};
let ours = route_d_lines_with(WORDS, f64::from(width), |style| {
style.par_indent = 30 * PT;
});
assert_lines_match("parindent 120pt", &ours, &reference);
assert!(ours.len() >= 3, "fixture must span at least three lines");
}
/// `\parshape` gives each line its own indent and measure, repeating the last
/// pair once the list is exhausted.
#[test]
fn par_shape_matches_pdftex() {
let width = 150;
let text = format!("{WORDS} {WORDS}");
let prefix = "\\parshape=3 0pt 120pt 20pt 100pt 40pt 80pt ";
let Some(reference) = pdftex_lines(&paragraph_fixture_with(&text, width, prefix)) else {
eprintln!("skipping: pdflatex/pdftotext are not installed");
return;
};
let ours = route_d_lines_with(&text, f64::from(width), |style| {
style.par_shape = vec![(0, 120 * PT), (20 * PT, 100 * PT), (40 * PT, 80 * PT)];
});
assert_lines_match("parshape 150pt", &ours, &reference);
assert!(ours.len() >= 5, "fixture must span at least five lines");
let steps: Vec<f64> = ours
.windows(2)
.map(|pair| pair[1].start - pair[0].start)
.collect();
assert!(
(steps[0] - 20.0).abs() <= 0.1,
"second line starts at {}",
steps[0]
);
assert!(
(steps[1] - 20.0).abs() <= 0.1,
"third line starts at {}",
steps[1]
);
assert!(
steps[2].abs() <= 0.1,
"later lines repeat the last indent: {}",
steps[2]
);
}
/// TeX `\\looseness` asks for a different final line count when such a
/// break is feasible within `\\tolerance`; pdfLaTeX is the reference. When
/// the requested count is infeasible TeX still prints a different (alternative
/// optimum) paragraph; route-D keeps the ordinary optimum there, which is
/// covered by the unit tests rather than this oracle.
#[test]
fn looseness_matches_pdftex() {
let width = 120;
let text = "alpha beta gamma delta epsilon zeta eta theta iota kappa \
lambda mu nu xi omicron pi rho sigma tau upsilon phi chi psi omega";
for looseness in [0_i64, 1] {
let prefix = format!("\\tolerance=10000 \\pretolerance=10000 \\looseness={looseness} ");
let Some(reference) = pdftex_lines(&paragraph_fixture_with(text, width, &prefix)) else {
eprintln!("skipping: pdflatex/pdftotext are not installed");
return;
};
let ours = route_d_lines_with(text, f64::from(width), |style| {
style.tolerance = 10_000;
style.pretolerance = 10_000;
style.looseness = looseness;
});
assert_eq!(
ours.len(),
reference.len(),
"looseness {looseness} line count"
);
assert_lines_match(&format!("looseness {looseness}"), &ours, &reference);
}
}
/// Hyphenation inserts discretionary breaks; line endings and the resulting
/// fragment words must match pdfLaTeX.
#[test]
fn hyphenated_breaks_match_pdftex() {
let text = "hyphenation demonstrates discretionary hyphenation whenever extraordinarily \
unpronounceable words appear in a paragraph";
for width in [80_u32, 100, 120] {
let Some(reference) = pdftex_lines(&paragraph_fixture_with(text, width, "")) else {
eprintln!("skipping: pdflatex/pdftotext are not installed");
return;
};
let ours = route_d_lines_with(text, f64::from(width), |_| {});
assert_lines_match(&format!("hyphenation {width}pt"), &ours, &reference);
}
}
/// `\\doublehyphendemerits` and `\\finalhyphendemerits` change which
/// breaks pdfLaTeX picks; both settings must reproduce its lines.
#[test]
fn hyphen_demerits_change_breaks_like_pdftex() {
let text = "hyphenation demonstrates discretionary representation according \
extraordinary understanding";
for width in [70_u32, 85] {
for demerits in [0_i64, 10_000] {
let prefix = format!(
"\\doublehyphendemerits={demerits} \\finalhyphendemerits={} ",
demerits / 2
);
let Some(reference) = pdftex_lines(&paragraph_fixture_with(text, width, &prefix))
else {
eprintln!("skipping: pdflatex/pdftotext are not installed");
return;
};
let ours = route_d_lines_with(text, f64::from(width), |style| {
style.double_hyphen_demerits = demerits;
style.final_hyphen_demerits = demerits / 2;
});
assert_lines_match(
&format!("hyphen demerits {demerits} at {width}pt"),
&ours,
&reference,
);
}
}
}
/// Sentence punctuation changes the space factor, so the interword glue and
/// the resulting line breaks must match pdfLaTeX.
#[test]
fn sentence_spacing_matches_pdftex_at_150pt() {
let width = 150;
let text = "alpha. beta gamma, delta; epsilon: zeta eta theta iota kappa lambda mu";
let Some(reference) = pdftex_lines(&paragraph_fixture_with(text, width, "")) else {
eprintln!("skipping: pdflatex/pdftotext are not installed");
return;
};
let ours = route_d_lines_with(text, f64::from(width), |_| {});
assert_lines_match("sentence spacing 150pt", &ours, &reference);
}
#[test]
fn spaceskip_matches_pdftex() {
let prefix = "\\spaceskip=6pt plus 1pt minus 0.5pt\\relax ";
compare_fixture_with(WORDS, 150, prefix, |style| {
style.space_skip = Some((6 * 65_536, 65_536, 32_768));
});
}
#[test]
fn xspaceskip_matches_pdftex() {
let text = "alpha. beta gamma, delta; epsilon: zeta eta theta iota kappa lambda mu";
let prefix = "\\spaceskip=6pt plus 1pt minus 0.5pt\\relax \
\\xspaceskip=8pt plus 4pt minus 2pt\\relax ";
compare_fixture_with(text, 150, prefix, |style| {
style.space_skip = Some((6 * 65_536, 65_536, 32_768));
style.xspace_skip = Some((8 * 65_536, 4 * 65_536, 2 * 65_536));
});
}
#[test]
fn explicit_sfcode_matches_pdftex() {
let width = 150;
let text = "alpha. beta gamma, delta; epsilon: zeta eta theta iota kappa lambda mu";
// `\sfcode`.=1000` makes the period behave like an ordinary character for
// the following interword glue, so the sentence space shrinks.
let prefix = "\\sfcode`.=1000\\relax ";
compare_fixture_with(text, width, prefix, |style| {
style.space_factor_codes = vec![('.', 1000)];
});
}
/// `\newpage` forces the next paragraph onto a fresh page; page texts and
/// page count must match pdfLaTeX.
#[test]
fn newpage_matches_pdftex_page_breaks() {
let paragraphs = vec![
"alpha beta gamma delta".to_string(),
"\\newpage".to_string(),
"epsilon zeta eta theta".to_string(),
];
let body = "alpha beta gamma delta\n\n\\newpage\n\nepsilon zeta eta theta\\par\n";
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(), "newpage page count");
assert_eq!(ours, reference, "newpage page text");
}
#[test]
fn club_penalty_forces_a_break_after_the_first_line() {
let text = format!("{WORDS} {WORDS} {WORDS}");
let source = format!(
"\\documentclass[10pt]{{article}}\n\
\\pdfpagewidth=612bp \\pdfpageheight=792bp\n\
\\pagestyle{{empty}}\n\
\\begin{{document}}\n\
\\hsize=345pt \\parindent=15pt \\topskip=12pt \\vsize=550pt \\clubpenalty=-10000 \\widowpenalty=0\n\
{text}\\par\n\\end{{document}}\n"
);
let Some(reference) = pdftex_pages(&source) else {
eprintln!("skipping: pdflatex/pdftotext are not installed");
return;
};
let ours = route_paged_text_with_penalties(&[text], 0, 550, 12, -10_000, 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 widow_penalty_forces_a_break_before_the_last_line() {
let text = format!("{WORDS} {WORDS} {WORDS}");
let source = format!(
"\\documentclass[10pt]{{article}}\n\
\\pdfpagewidth=612bp \\pdfpageheight=792bp\n\
\\pagestyle{{empty}}\n\
\\begin{{document}}\n\
\\hsize=345pt \\parindent=15pt \\topskip=12pt \\vsize=550pt \\clubpenalty=0 \\widowpenalty=-10000\n\
{text}\\par\n\\end{{document}}\n"
);
let Some(reference) = pdftex_pages(&source) else {
eprintln!("skipping: pdflatex/pdftotext are not installed");
return;
};
let ours = route_paged_text_with_penalties(&[text], 0, 550, 12, 0, -10_000);
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_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_respect_stretchy_vertical_glue_like_pdftex() {
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\\vskip 20pt plus 40pt minus 5pt\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 mut units = Vec::new();
for text in &paragraphs {
let style = ParagraphStyle {
line_width: 345 * PT,
par_indent: 15 * PT,
line_height: 12 * PT,
..ParagraphStyle::default()
};
let mut unit = Unit::paragraph_with_style(units.len() as u64 + 1, text, style);
if !units.is_empty() {
unit.space_before = 20 * PT;
unit.space_stretch = 40 * PT;
unit.space_shrink = 5 * PT;
}
units.push(unit);
}
let mut document = Document::new(550 * PT, units);
document.top_skip = 12 * PT;
document.text_float_sep = 0;
document.max_depth = 5 * PT;
let engine = Engine::layout_paged(&document).expect("paged layout");
let ours: Vec<String> = engine.pages().iter().map(page_alnum_text).collect();
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_on_a_shorter_page() {
let paragraphs: Vec<String> = (0..80)
.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\
\\textheight=300pt\n\
\\begin{{document}}\n\
\\hsize=345pt \\parindent=15pt \\parskip=0pt \\topskip=12pt\n\
{body}\\end{{document}}\n"
);
let Some(reference) = pdftex_pages(&source) else {
eprintln!("skipping: pdflatex/pdftotext are not installed");
return;
};
assert!(reference.len() > 2, "fixture should span pages");
let ours = route_pages_text_with(&paragraphs, 0, 300, 12);
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_a_taller_topskip() {
let paragraphs: Vec<String> = (0..80)
.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=30pt \\vsize=550pt\n\
{body}\\end{{document}}\n"
);
let Some(reference) = pdftex_pages(&source) else {
eprintln!("skipping: pdflatex/pdftotext are not installed");
return;
};
assert!(reference.len() > 1, "fixture should span pages");
let ours = route_pages_text_with(&paragraphs, 0, 550, 30);
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);
}
}
/// A `[t]` float deferred to the next page top reserves its height plus
/// `\textfloatsep`; body breaks must stay in step with pdfLaTeX.
#[test]
fn top_floats_reserve_page_space_like_pdftex() {
let paragraphs: Vec<String> = (0..80)
.map(|index| format!("p{index} alpha beta gamma"))
.collect();
let float_at = 9_usize;
let mut body = String::new();
for (index, paragraph) in paragraphs.iter().enumerate() {
body.push_str(paragraph);
body.push_str("\\par\n");
if index == float_at {
body.push_str("\\begin{figure}[t]\\rule{100pt}{50pt}\\end{figure}\n");
}
}
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 style = ParagraphStyle {
line_width: 345 * PT,
par_indent: 15 * PT,
line_height: 12 * PT,
..ParagraphStyle::default()
};
let mut units = Vec::new();
let mut next_id = 1_u64;
for (index, paragraph) in paragraphs.iter().enumerate() {
units.push(Unit::paragraph_with_style(
next_id,
paragraph.clone(),
style.clone(),
));
next_id += 1;
if index == float_at {
units.push(Unit::float(next_id, FloatPlacement::Top, 100 * PT, 50 * PT));
next_id += 1;
}
}
let mut document = Document::new(550 * PT, units);
document.top_skip = 12 * PT;
document.text_float_sep = 20 * PT;
// LaTeX's default \maxdepth keeps 5pt of descent out of the page height.
document.max_depth = 5 * PT;
let engine = Engine::layout_paged(&document).expect("top floats are page-buildable");
let ours: Vec<String> = engine.pages().iter().map(page_alnum_text).collect();
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, "body text on page {}", index + 1);
}
}
/// A `[b]` float reserves its height plus `\textfloatsep` at the page bottom;
/// the body must stop earlier on exactly the pages pdfLaTeX chooses.
fn bottom_float_pages(float_at: usize) {
let paragraphs: Vec<String> = (0..80)
.map(|index| format!("p{index} alpha beta gamma"))
.collect();
let mut body = String::new();
for (index, paragraph) in paragraphs.iter().enumerate() {
body.push_str(paragraph);
body.push_str("\\par\n");
if index == float_at {
body.push_str("\\begin{figure}[b]\\rule{100pt}{60pt}\\end{figure}\n");
}
}
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 style = ParagraphStyle {
line_width: 345 * PT,
par_indent: 15 * PT,
line_height: 12 * PT,
..ParagraphStyle::default()
};
let mut units = Vec::new();
let mut next_id = 1_u64;
for (index, paragraph) in paragraphs.iter().enumerate() {
units.push(Unit::paragraph_with_style(
next_id,
paragraph.clone(),
style.clone(),
));
next_id += 1;
if index == float_at {
units.push(Unit::float(
next_id,
FloatPlacement::Bottom,
100 * PT,
60 * PT,
));
next_id += 1;
}
}
let mut document = Document::new(550 * PT, units);
document.top_skip = 12 * PT;
document.text_float_sep = 20 * PT;
document.max_depth = 5 * PT;
let engine = Engine::layout_paged(&document).expect("bottom floats are page-buildable");
let ours: Vec<String> = engine.pages().iter().map(page_alnum_text).collect();
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, "body text on page {}", index + 1);
}
}
#[test]
fn bottom_floats_reserve_page_space_like_pdftex() {
bottom_float_pages(2);
}
#[test]
fn late_bottom_floats_defer_like_pdftex() {
bottom_float_pages(40);
}
/// `\footnotetext` raises insertion material that is reserved at the page
/// bottom. With slack on each page, the body breaks and per-page body text
/// must stay in step with pdfLaTeX even though the note text is not compared.
#[test]
fn footnotes_reserve_page_space_like_pdftex() {
let paragraphs: Vec<String> = (0..80)
.map(|index| format!("p{index} alpha beta gamma"))
.collect();
let notes: Vec<usize> = (0..8).map(|index| index * 10 + 9).collect();
let mut body = String::new();
for (index, paragraph) in paragraphs.iter().enumerate() {
body.push_str(paragraph);
body.push_str("\\par\n");
if let Some(number) = notes.iter().position(|at| *at == index) {
body.push_str(&format!("\\footnotetext{{note number {number}}}\n"));
}
}
let source = format!(
"\\documentclass[10pt]{{article}}\n\
\\pdfpagewidth=612bp \\pdfpageheight=792bp\n\
\\pagestyle{{empty}}\n\
\\renewcommand{{\\thefootnote}}{{}}\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 style = ParagraphStyle {
line_width: 345 * PT,
par_indent: 15 * PT,
line_height: 12 * PT,
..ParagraphStyle::default()
};
let note_style = ParagraphStyle {
line_width: 345 * PT,
par_indent: 0,
line_height: 11 * PT,
..ParagraphStyle::default()
};
let mut units = Vec::new();
let mut next_id = 1_u64;
for (index, paragraph) in paragraphs.iter().enumerate() {
units.push(Unit::paragraph_with_style(
next_id,
paragraph.clone(),
style.clone(),
));
next_id += 1;
if let Some(number) = notes.iter().position(|at| *at == index) {
let note = layout_paragraph(&format!("note number {number}"), &note_style);
units.push(Unit::insertion(
next_id,
0,
note.height,
vec![VerticalItem::Paragraph(note)],
));
next_id += 1;
}
}
let mut document = Document::new(550 * PT, units);
document.top_skip = 12 * PT;
document.text_float_sep = 0;
document.insertion_skip = 12 * PT;
document.max_depth = 5 * PT;
let engine = Engine::layout_paged(&document).expect("insertions are page-buildable");
let ours: Vec<String> = engine.pages().iter().map(page_alnum_text).collect();
assert_eq!(
ours.len(),
reference.len(),
"route-D produced {} pages, pdfLaTeX {}",
ours.len(),
reference.len()
);
for (index, (ours, page)) in ours.iter().zip(&reference).enumerate() {
// pdftotext puts each note at the bottom of its page; dropping the
// note text leaves the body words route-D also reports.
let expected = (0..notes.len()).fold(page.clone(), |text, number| {
text.replace(&format!("notenumber{number}"), "")
});
assert_eq!(ours, &expected, "body text on page {}", index + 1);
}
}
#[test]
fn paragraph_breaks_match_pdftex_at_150pt() {
compare_fixture(WORDS, 150);
}
/// The same text at a wider measure; TeX produces four lines here (7, 8, 9
/// and 1 words), which exercises the pass-1 solution rather than the fallback.
#[test]
fn paragraph_breaks_match_pdftex_at_180pt() {
compare_fixture(WORDS, 180);
}
/// Several measures in one run: 90/100/110/120pt exercise hyphenated and
/// overfull breaks, 130/150/160pt need TeX's final-pass overfull box, and
/// 180/200/220/240pt are ordinary tolerance solutions.
#[test]
fn paragraph_breaks_match_pdftex_across_measures() {
for width in [90u32, 100, 110, 120, 130, 150, 160, 180, 200, 220, 240] {
compare_fixture(WORDS, width);
}
}
/// `\emergencystretch` gives the final pass extra stretch, so TeX can avoid
/// an overfull line and break the paragraph into more lines.
#[test]
fn emergencystretch_matches_pdftex() {
compare_fixture_with(WORDS, 150, "\\emergencystretch=10pt ", |style| {
style.emergencystretch = 10 * 65_536;
});
}
/// `\leftskip` narrows the measure and shifts every line, so line starts and
/// breaks must match pdfLaTeX.
#[test]
fn leftskip_matches_pdftex() {
compare_fixture_with(WORDS, 150, "\\leftskip=20pt ", |style| {
style.left_skip = 20 * 65_536;
});
}
#[test]
fn hfill_matches_pdftex() {
compare_fixture_with("alpha \\hfill beta", 150, "", |_| {});
}
#[test]
fn hfill_and_hfil_match_pdftex() {
compare_fixture_with("alpha \\hfil beta \\hfill gamma", 150, "", |_| {});
}
#[test]
fn tabular_word_positions_match_pdftex() {
let source = r"\documentclass[10pt]{article}
\pagestyle{empty}
\begin{document}
\noindent\begin{tabular}{lcr}
Alpha & Beta & Gamma \\
Delta & Epsilon & Zeta
\end{tabular}
\end{document}
";
let Some(tex) = tex_word_positions(source) else {
eprintln!("skipping: pdflatex/pdftotext are not installed");
return;
};
let tex_word = |word: &str| {
tex.iter()
.find(|(text, _, _)| text == word)
.map(|(_, x, y)| (*x, *y))
.unwrap_or_else(|| panic!("pdfLaTeX produced no `{word}`"))
};
let unit = Unit::halign_from_source_with_template(
1,
"lcr",
"Alpha & Beta & Gamma \\\\ Delta & Epsilon & Zeta",
12,
);
let document = Document::new(700 * PT, vec![unit]);
let engine = Engine::layout(&document);
let page = engine.pages().first().expect("one page");
let display = page.display_list();
let ours = |word: &str| {
display
.items
.iter()
.find_map(|item| match item {
texrra_tex_core::render::DisplayItem::Text { text, x, y, .. } if text == word => {
Some((*x as f64 / PT as f64, *y as f64 / PT as f64))
}
_ => None,
})
.unwrap_or_else(|| panic!("route-D produced no `{word}`"))
};
let words = ["Alpha", "Beta", "Gamma", "Delta", "Epsilon", "Zeta"];
let (origin_x, origin_y) = ours("Alpha");
let (tex_x, tex_y) = tex_word("Alpha");
let mut max_dx = 0.0_f64;
let mut max_dy = 0.0_f64;
for word in words {
let (x, y) = ours(word);
let (reference_x, reference_y) = tex_word(word);
let dx = (x - origin_x) - (reference_x - tex_x);
let dy = (y - origin_y) - (reference_y - tex_y);
max_dx = max_dx.max(dx.abs());
max_dy = max_dy.max(dy.abs());
}
eprintln!("tabular maximum offsets: ({max_dx:.2}, {max_dy:.2}) pt");
assert!(
max_dx <= 2.0 && max_dy <= 2.0,
"tabular words are off by up to ({max_dx:.2}, {max_dy:.2}) pt"
);
}
#[test]
fn pmatrix_word_positions_match_pdftex() {
let source = r"\documentclass[10pt]{article}
\usepackage{amsmath}
\pagestyle{empty}
\begin{document}
\[ \begin{pmatrix} a & b \\ c & d \end{pmatrix} \]
\end{document}
";
let Some(tex) = tex_word_positions(source) else {
eprintln!("skipping: pdflatex/pdftotext are not installed");
return;
};
let tex = |letter: &str| {
tex.iter()
.find(|(text, _, _)| text == letter)
.map(|(_, x, y)| (*x, *y))
.unwrap_or_else(|| panic!("pdfLaTeX produced no `{letter}`"))
};
let atom = texrra_tex_core::math::parse_math(r"\begin{pmatrix} a & b \\ c & d \end{pmatrix}");
let font = texrra_tex_core::cmr10::Cmr10Metrics::default();
let unit = Unit::math(1, atom, &font);
let document = Document::new(700 * PT, vec![unit]);
let engine = Engine::layout(&document);
let page = engine.pages().first().expect("one page");
let display = page.display_list();
let ours = |letter: &str| {
display
.items
.iter()
.find_map(|item| match item {
texrra_tex_core::render::DisplayItem::Text { text, x, y, .. } if text == letter => {
Some((*x as f64 / PT as f64, *y as f64 / PT as f64))
}
_ => None,
})
.unwrap_or_else(|| panic!("route-D produced no `{letter}`"))
};
let (origin_x, origin_y) = ours("a");
let (tex_x, tex_y) = tex("a");
let mut max_dx = 0.0_f64;
let mut max_dy = 0.0_f64;
for letter in ["b", "c", "d"] {
let (x, y) = ours(letter);
let (reference_x, reference_y) = tex(letter);
let dx = (x - origin_x) - (reference_x - tex_x);
let dy = (y - origin_y) - (reference_y - tex_y);
max_dx = max_dx.max(dx.abs());
max_dy = max_dy.max(dy.abs());
}
eprintln!("pmatrix maximum offsets: ({max_dx:.2}, {max_dy:.2}) pt");
assert!(
max_dx <= 1.0 && max_dy <= 1.0,
"pmatrix words are off by up to ({max_dx:.2}, {max_dy:.2}) pt"
);
}
#[test]
fn cases_row_spacing_matches_pdftex() {
let source = r"\documentclass[10pt]{article}
\usepackage{amsmath}
\pagestyle{empty}
\begin{document}
\[ \begin{cases} a & x>0 \\ b & y<0 \end{cases} \]
\end{document}
";
let Some(tex) = tex_word_positions(source) else {
eprintln!("skipping: pdflatex/pdftotext are not installed");
return;
};
let tex = |word: &str| {
tex.iter()
.find(|(text, _, _)| text == word || text.starts_with(word))
.map(|(_, x, y)| (*x, *y))
.unwrap_or_else(|| panic!("pdfLaTeX produced no `{word}`"))
};
let atom = texrra_tex_core::math::parse_math(r"\begin{cases} a & x>0 \\ b & y<0 \end{cases}");
let font = texrra_tex_core::cmr10::Cmr10Metrics::default();
let unit = Unit::math(1, atom, &font);
let document = Document::new(700 * PT, vec![unit]);
let engine = Engine::layout(&document);
let page = engine.pages().first().expect("one page");
let display = page.display_list();
let ours = |letter: &str| {
display
.items
.iter()
.find_map(|item| match item {
texrra_tex_core::render::DisplayItem::Text { text, x, y, .. } if text == letter => {
Some((*x as f64 / PT as f64, *y as f64 / PT as f64))
}
_ => None,
})
.unwrap_or_else(|| panic!("route-D produced no `{letter}`"))
};
let (origin_x, origin_y) = ours("a");
let (tex_x, tex_y) = tex("a");
for word in ["b", "x"] {
let (x, y) = ours(word);
let (reference_x, reference_y) = tex(word);
let dx = (x - origin_x) - (reference_x - tex_x);
let dy = (y - origin_y) - (reference_y - tex_y);
assert!(
dx.abs() <= 1.5 && dy.abs() <= 1.5,
"`{word}` is off by ({dx:.2}, {dy:.2}) pt"
);
}
}
#[test]
fn display_limits_sit_above_and_below_their_base() {
for base in ["M", "A", "g", "W"] {
let source = format!(
"\\documentclass[10pt]{{article}}\n\\pagestyle{{empty}}\n\\begin{{document}}\n\\[ \\mathop{{{base}}}_{{i}}^{{n}} \\]\n\\end{{document}}\n"
);
let Some(tex) = tex_word_positions(&source) else {
eprintln!("skipping: pdflatex/pdftotext are not installed");
return;
};
let tex = |letter: &str| {
tex.iter()
.find(|(text, _, _)| text == letter)
.map(|(_, x, y)| (*x, *y))
.unwrap_or_else(|| panic!("pdfLaTeX produced no `{letter}`"))
};
let atom = texrra_tex_core::math::parse_math(&format!("\\mathop{{{base}}}_{{i}}^{{n}}"));
let font = texrra_tex_core::cmr10::Cmr10Metrics::default();
let unit = Unit::math(1, atom, &font);
let document = Document::new(700 * PT, vec![unit]);
let engine = Engine::layout(&document);
let page = engine.pages().first().expect("one page");
let display = page.display_list();
let ours = |letter: &str| {
display
.items
.iter()
.find_map(|item| match item {
texrra_tex_core::render::DisplayItem::Text { text, x, y, .. }
if text == letter =>
{
Some((*x as f64 / PT as f64, *y as f64 / PT as f64))
}
_ => None,
})
.unwrap_or_else(|| panic!("route-D produced no `{letter}`"))
};
let (origin_x, _origin_y) = ours(base);
let (tex_x, _tex_y) = tex(base);
let mut reference_gap = 0.0;
let mut our_gap = 0.0;
for letter in ["i", "n"] {
let (x, y) = ours(letter);
let (reference_x, reference_y) = tex(letter);
let dx = (x - origin_x) - (reference_x - tex_x);
assert!(
dx.abs() <= 1.2,
"limits over `{base}`: `{letter}` is off by {dx:.2} pt horizontally"
);
// poppler 26 reports a word's box as the font extent, whose ascent
// depends on the type size, so the absolute `yMin` of a 7pt limit
// cannot be compared with the 10pt base. The subscript and
// superscript share a size, so their baseline distance is a valid
// anchor-free reference.
if letter == "i" {
reference_gap = reference_y;
our_gap = y;
} else {
reference_gap -= reference_y;
our_gap -= y;
}
}
assert!(
(our_gap - reference_gap).abs() <= 0.2,
"limits over `{base}`: limit gap is off by {:.2} pt",
our_gap - reference_gap
);
let (_, base_y) = ours(base);
let (_, subscript_y) = ours("i");
let (_, superscript_y) = ours("n");
assert!(
subscript_y > base_y && superscript_y < base_y,
"limits over `{base}` must straddle the operator baseline"
);
}
}