274 lines
8.8 KiB
Rust
274 lines
8.8 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>,
|
|
}
|
|
|
|
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() });
|
|
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);
|
|
for word in &mut line.words {
|
|
word.x = (word.x - origin) * BP_TO_PT;
|
|
}
|
|
}
|
|
lines
|
|
}
|
|
|
|
/// Lay out one paragraph with route-D and return its per-line words.
|
|
fn route_d_lines(text: &str, width_pt: f64) -> Vec<Line> {
|
|
let width = (width_pt * PT as f64).round() as i64;
|
|
let 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()
|
|
};
|
|
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 in ¶graph.lines {
|
|
let mut x = paragraph.left_skip 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,
|
|
});
|
|
}
|
|
if let Some(origin) = words.first().map(|word| word.x) {
|
|
for word in &mut words {
|
|
word.x -= origin;
|
|
}
|
|
}
|
|
lines.push(Line { words });
|
|
}
|
|
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 {
|
|
format!(
|
|
"\\documentclass[10pt]{{article}}\n\
|
|
\\pdfpagewidth=612bp \\pdfpageheight=792bp\n\
|
|
\\pagestyle{{empty}}\n\
|
|
\\begin{{document}}\n\
|
|
\\hsize={width_pt}pt \\parindent=0pt \\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) {
|
|
let Some(reference) = pdftex_lines(¶graph_fixture(text, width_pt)) else {
|
|
eprintln!("skipping: pdflatex/pdftotext are not installed");
|
|
return;
|
|
};
|
|
let ours = route_d_lines(text, f64::from(width_pt));
|
|
assert_lines_match(&format!("{width_pt}pt"), &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);
|
|
}
|
|
}
|