//! 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, } #[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, 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 = 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 { 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 { 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.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" ) } /// 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(¶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; }); } /// `\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; }); } } /// `\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(¶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); } /// `\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(¶graph_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 = 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(¶graph_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(¶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(&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(¶graph_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(¶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)]; }); } /// `\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(¶graphs, 0); assert_eq!(ours.len(), reference.len(), "newpage page count"); assert_eq!(ours, reference, "newpage page text"); } #[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_respect_stretchy_vertical_glue_like_pdftex() { let paragraphs: Vec = (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 ¶graphs { 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; let engine = Engine::layout_paged(&document).expect("paged layout"); let ours: Vec = 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 = (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(¶graphs, 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 = (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(¶graphs, 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 = (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); } } /// 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 = (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; let engine = Engine::layout_paged(&document).expect("top floats are page-buildable"); let ours: Vec = 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); } } /// `\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 = (0..80) .map(|index| format!("p{index} alpha beta gamma")) .collect(); let notes: Vec = (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}"), ¬e_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; let engine = Engine::layout_paged(&document).expect("insertions are page-buildable"); let ours: Vec = 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, "", |_| {}); }