373 lines
12 KiB
Rust
373 lines
12 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::{Unit, VerticalItem};
|
|
|
|
/// 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,
|
|
}
|
|
|
|
#[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("&", "&")
|
|
.replace("<", "<")
|
|
.replace(">", ">")
|
|
.replace(""", "\"")
|
|
.replace("'", "'")
|
|
}
|
|
|
|
fn parse_bbox(xhtml: &str) -> Vec<Line> {
|
|
let mut lines: Vec<Line> = Vec::new();
|
|
let mut current_y = f64::NAN;
|
|
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]);
|
|
let x_min = attr(tag, "xMin");
|
|
let y_min = attr(tag, "yMin");
|
|
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 });
|
|
rest = &rest[close + "</word>".len()..];
|
|
}
|
|
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
|
|
}
|
|
|
|
/// 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,
|
|
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,
|
|
});
|
|
}
|
|
x += *width as f64 / PT as f64;
|
|
}
|
|
HorizontalItem::Penalty { .. } | HorizontalItem::Discretionary { .. } => {}
|
|
}
|
|
}
|
|
if !word.is_empty() {
|
|
words.push(Word {
|
|
text: word,
|
|
x: word_x,
|
|
});
|
|
}
|
|
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
|
|
}
|
|
|
|
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(text: &str, width_pt: u32) -> String {
|
|
paragraph_fixture_with(text, width_pt, "")
|
|
}
|
|
|
|
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"
|
|
)
|
|
}
|
|
|
|
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(¶graph_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;
|
|
});
|
|
}
|
|
|
|
/// `\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;
|
|
});
|
|
}
|
|
|
|
/// `\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(¶graph_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(¶graph_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);
|
|
}
|
|
|
|
#[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: 100/120pt exercise hyphenated and overfull
|
|
/// breaks, 150pt needs TeX's final-pass overfull box, and 180/200/240pt are
|
|
/// ordinary tolerance solutions.
|
|
#[test]
|
|
fn paragraph_breaks_match_pdftex_across_measures() {
|
|
for width in [100u32, 120, 150, 180, 200, 240] {
|
|
compare_fixture(WORDS, width);
|
|
}
|
|
}
|