//! 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, 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, /// 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> { 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 { let mut lines: Vec = Vec::new(); let mut current_y = f64::NAN; let mut rest = xhtml; while let Some(start) = rest.find("').expect("word tag end"); let close = tag_end + rest[tag_end..].find("").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 + "".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 { 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 = 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 } /// 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> { 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 ¶graph.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 { 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(), 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" ) } 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; }); } /// `\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; }); } /// `\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); } /// 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(¶graph_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)]; }); } #[test] fn pages_break_like_pdftex_for_single_line_paragraphs() { let paragraphs: Vec = (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(¶graphs, 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 = (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(¶graphs, 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 = (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(¶graphs, 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); } /// 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; }); }