//! End-to-end route-D smoke test: layout, display lists, PDF bytes, and an //! incremental paragraph edit. use texrra_tex_core::{ Document, Engine, ParagraphFont, ParagraphStyle, Unit, VerticalItem, cmr10::Cmr10Metrics, pdf::{ PageOrigin, display_lists_to_pdf, display_lists_to_pdf_with_cm_type1, display_lists_to_pdf_with_origin, }, }; /// Paragraph style in TeX scaled points, driven by the CMR10 font metrics. fn body_style() -> ParagraphStyle { let font = Cmr10Metrics::default(); ParagraphStyle { line_expansion: 0, font_size: 10 * 65_536, line_width: 480 * 65_536, left_skip: 0, right_skip: 0, centered: false, right_aligned: false, looseness: 0, ragged_right: false, hang_indent: 0, hang_after: 1, par_shape: Vec::new(), par_fillskip: 0, par_fillskip_stretch: 0, par_fillskip_fil: true, frenchspacing: false, space_factor_codes: Vec::new(), baselineskip: 12 * 65_536, lineskip: 65_536, lineskiplimit: 0, par_indent: 0, emergencystretch: 0, pretolerance: 100, tolerance: 200, hyphen_penalty: 50, ex_hyphen_penalty: 50, double_hyphen_demerits: 10_000, final_hyphen_demerits: 5_000, line_penalty: 10, adj_demerits: 10_000, hyphenation_exceptions: Vec::new(), line_height: 12 * 65_536, char_width: font.width('x'), space_width: font.space(), space_stretch: font.stretch(), space_shrink: font.shrink(), space_skip: None, xspace_skip: None, } } fn paragraph(id: u64, marker: &str) -> Unit { let text = format!("{} {}", marker, "alpha beta gamma delta ".repeat(80)); Unit::paragraph_with_style(id, text, body_style()) } #[test] fn accented_text_keeps_type1_ascii_and_falls_back_per_glyph() { let mut document = Document::new( 1, vec![Unit::paragraph_with_style( 1, "caf\u{e9}".to_string(), body_style(), )], ); document.page_goal = 200 * 65_536; let engine = Engine::layout_paged(&document).expect("paged layout"); let lists: Vec<_> = engine .pages() .iter() .map(|page| page.display_list()) .collect(); let pdf = display_lists_to_pdf_with_cm_type1( &lists, 300 * 65_536, 300 * 65_536, PageOrigin::default(), ); let text = String::from_utf8_lossy(&pdf); assert!(text.contains("/BaseFont /CMR10"), "{text}"); assert!(text.contains("/Subtype /Type0"), "{text}"); } #[test] fn route_d_article_exports_pdf_and_reflows_only_the_edited_page() { let mut document = Document::new( 1, vec![ paragraph(1, "ONE"), paragraph(2, "TWO"), paragraph(3, "THREE"), ], ); // One full paragraph is exactly one page, so the test is about the // incremental checkpoint boundary rather than page overflow. document.page_goal = document .units .iter() .find_map(|unit| match &unit.items[0] { VerticalItem::Paragraph(paragraph) => Some(paragraph.height), _ => None, }) .expect("paragraph units"); let mut engine = Engine::layout(&document); assert!(engine.pages().len() >= 3, "expected one page per paragraph"); let lists: Vec<_> = engine .pages() .iter() .map(|page| page.display_list()) .collect(); let pdf = display_lists_to_pdf(&lists, 792); assert!(pdf.starts_with(b"%PDF-")); assert!(pdf.windows(7).any(|window| window == b"/Count ")); assert!(pdf.ends_with( b"%%EOF " )); engine.edit(&document, 2, "TWO short beta gamma delta".to_string()); assert!( engine.changed_pages().contains(&1), "middle page should be rebuilt, got {:?}", engine.changed_pages() ); assert_eq!(engine.pages().len(), 3); } /// Compare the rasterized route-D page against a real pdfTeX page at the same /// page geometry. Glyph outlines differ (Liberation vs Computer Modern), so the /// check is limited to page-level ink geometry: one text line, the same ink /// columns start, and a matching vertical band. The test is skipped when the /// host has no pdfTeX/poppler tooling. #[test] fn route_d_page_matches_pdftex_raster_geometry() { use std::process::Command; fn has(command: &str, version_arg: &str) -> bool { Command::new(command) .arg(version_arg) .stdout(std::process::Stdio::null()) .stderr(std::process::Stdio::null()) .status() .is_ok_and(|status| status.success()) } if !has("pdflatex", "--version") || !has("pdftoppm", "-v") { return; } fn rasterize(pdf: &std::path::Path, output: &std::path::Path) { let status = Command::new("pdftoppm") .args(["-r", "72", "-gray", "-singlefile"]) .arg(pdf) .arg(output.with_extension("")) .status() .expect("pdftoppm"); assert!(status.success(), "pdftoppm failed for {}", pdf.display()); } fn ink_bbox(path: &std::path::Path) -> (usize, usize, usize, usize, usize, usize) { let bytes = std::fs::read(path).expect("read PGM"); assert_eq!(&bytes[..2], b"P5", "expected binary PGM"); let mut fields = Vec::new(); let mut cursor = 2; while fields.len() < 3 { while cursor < bytes.len() && bytes[cursor].is_ascii_whitespace() { cursor += 1; } let start = cursor; while cursor < bytes.len() && bytes[cursor].is_ascii_digit() { cursor += 1; } fields.push( std::str::from_utf8(&bytes[start..cursor]) .expect("PGM number") .parse::() .expect("PGM number"), ); } while cursor < bytes.len() && bytes[cursor].is_ascii_whitespace() { cursor += 1; } let (width, height, _) = (fields[0], fields[1], fields[2]); let pixels = &bytes[cursor..]; assert_eq!(pixels.len(), width * height, "PGM payload size"); let (mut x0, mut y0, mut x1, mut y1, mut rows) = (usize::MAX, usize::MAX, 0usize, 0usize, 0usize); for y in 0..height { let mut row_has_ink = false; for x in 0..width { if pixels[y * width + x] < 160 { row_has_ink = true; x0 = x0.min(x); y0 = y0.min(y); x1 = x1.max(x); y1 = y1.max(y); } } if row_has_ink { rows += 1; } } (x0, y0, x1, y1, rows, width) } let root = std::env::temp_dir().join(format!("texrra-raster-{}", std::process::id())); let _ = std::fs::remove_dir_all(&root); std::fs::create_dir_all(&root).expect("create raster dir"); let style = ParagraphStyle { line_expansion: 0, font_size: 10 * 65_536, line_width: 480 * 65_536, left_skip: 0, right_skip: 0, centered: false, right_aligned: false, looseness: 0, ragged_right: false, hang_indent: 0, hang_after: 1, par_shape: Vec::new(), par_fillskip: 0, par_fillskip_stretch: 0, par_fillskip_fil: true, frenchspacing: false, space_factor_codes: Vec::new(), baselineskip: 12 * 65_536, lineskip: 65_536, lineskiplimit: 0, par_indent: 0, emergencystretch: 0, pretolerance: 100, tolerance: 200, hyphen_penalty: 50, ex_hyphen_penalty: 50, double_hyphen_demerits: 10_000, final_hyphen_demerits: 5_000, line_penalty: 10, adj_demerits: 10_000, hyphenation_exceptions: Vec::new(), line_height: 12 * 65_536, char_width: 10 * 65_536, space_width: 4 * 65_536, space_stretch: 6 * 65_536, space_shrink: 2 * 65_536, space_skip: None, xspace_skip: None, }; let document = Document::new( 700 * 65_536, vec![Unit::paragraph_with_style(1, "Hello route-D", style)], ); let engine = Engine::layout(&document); let pages: Vec<_> = engine .pages() .iter() .map(|page| page.display_list()) .collect(); let route_pdf = display_lists_to_pdf(&pages, 792); let route_pdf_path = root.join("route.pdf"); std::fs::write(&route_pdf_path, route_pdf).expect("write route PDF"); let classic = r"\documentclass[10pt]{article} \pagestyle{empty} \hoffset=-1in \voffset=-1in \oddsidemargin=0pt \topmargin=0pt \headheight=0pt \headsep=0pt \pdfpagewidth=612bp \pdfpageheight=792bp \textwidth=480pt \textheight=700pt \topskip=10pt \parindent=0pt \begin{document} Hello route-D \end{document} "; let classic_path = root.join("classic.tex"); std::fs::write(&classic_path, classic).expect("write classic TeX"); let status = Command::new("pdflatex") .args(["-interaction=nonstopmode", "-halt-on-error"]) .arg(&classic_path) .current_dir(&root) .stdout(std::process::Stdio::null()) .stderr(std::process::Stdio::null()) .status() .expect("pdflatex"); assert!(status.success(), "pdflatex failed"); let route_pgm = root.join("route.pgm"); let classic_pgm = root.join("classic.pgm"); rasterize(&route_pdf_path, &route_pgm); rasterize(&root.join("classic.pdf"), &classic_pgm); let route = ink_bbox(&route_pgm); let classic = ink_bbox(&classic_pgm); // The engines use different fonts (Liberation vs Computer Modern) and the // page builder does not yet place the first baseline with topskip, so a // constant vertical offset and one raster row of glyph height difference // are expected. The horizontal block and the ink shape must still agree. assert!( (route.4 as i64 - classic.4 as i64).abs() <= 2, "ink row count: route={route:?} classic={classic:?}" ); assert!( (route.1 as i64 - classic.1 as i64).abs() <= 3, "ink top edge: route={route:?} classic={classic:?}" ); assert!( route.2 <= classic.2 && route.2 + 10 >= classic.2, "ink left edge: route={route:?} classic={classic:?}" ); assert!( (route.3 as i64 - classic.3 as i64).abs() <= 4, "ink bottom edge: route={route:?} classic={classic:?}" ); let _ = std::fs::remove_dir_all(&root); } /// Compare two route-D pages against a two-page pdfTeX document. This extends /// the single-page geometry check to page boundaries and repeated page /// furniture: each page should contain one line at the same vertical band. #[test] fn route_d_two_pages_match_pdftex_raster_geometry() { use std::process::Command; fn has(command: &str, version_arg: &str) -> bool { Command::new(command) .arg(version_arg) .stdout(std::process::Stdio::null()) .stderr(std::process::Stdio::null()) .status() .is_ok_and(|status| status.success()) } if !has("pdflatex", "--version") || !has("pdftoppm", "-v") { return; } fn ink_bbox(path: &std::path::Path) -> (usize, usize, usize, usize, usize, usize) { let bytes = std::fs::read(path).expect("read PGM"); assert_eq!(&bytes[..2], b"P5", "expected binary PGM"); let mut fields = Vec::new(); let mut cursor = 2; while fields.len() < 3 { while cursor < bytes.len() && bytes[cursor].is_ascii_whitespace() { cursor += 1; } let start = cursor; while cursor < bytes.len() && bytes[cursor].is_ascii_digit() { cursor += 1; } fields.push( std::str::from_utf8(&bytes[start..cursor]) .expect("PGM number") .parse::() .expect("PGM number"), ); } while cursor < bytes.len() && bytes[cursor].is_ascii_whitespace() { cursor += 1; } let (width, height, _) = (fields[0], fields[1], fields[2]); let pixels = &bytes[cursor..]; let (mut x0, mut y0, mut x1, mut y1, mut rows) = (usize::MAX, usize::MAX, 0usize, 0usize, 0usize); for y in 0..height { let mut row_has_ink = false; for x in 0..width { if pixels[y * width + x] < 160 { row_has_ink = true; x0 = x0.min(x); y0 = y0.min(y); x1 = x1.max(x); y1 = y1.max(y); } } if row_has_ink { rows += 1; } } (x0, y0, x1, y1, rows, width) } let root = std::env::temp_dir().join(format!("texrra-raster-two-{}", std::process::id())); let _ = std::fs::remove_dir_all(&root); std::fs::create_dir_all(&root).expect("create raster dir"); let style = ParagraphStyle { line_expansion: 0, font_size: 10 * 65_536, line_width: 480 * 65_536, left_skip: 0, right_skip: 0, centered: false, right_aligned: false, looseness: 0, ragged_right: false, hang_indent: 0, hang_after: 1, par_shape: Vec::new(), par_fillskip: 0, par_fillskip_stretch: 0, par_fillskip_fil: true, frenchspacing: false, space_factor_codes: Vec::new(), baselineskip: 12 * 65_536, lineskip: 65_536, lineskiplimit: 0, par_indent: 0, emergencystretch: 0, pretolerance: 100, tolerance: 200, hyphen_penalty: 50, ex_hyphen_penalty: 50, double_hyphen_demerits: 10_000, final_hyphen_demerits: 5_000, line_penalty: 10, adj_demerits: 10_000, hyphenation_exceptions: Vec::new(), line_height: 12 * 65_536, char_width: 10 * 65_536, space_width: 4 * 65_536, space_stretch: 6 * 65_536, space_shrink: 2 * 65_536, space_skip: None, xspace_skip: None, }; let document = Document::new( 20 * 65_536, vec![ Unit::paragraph_with_style(1, "First page text", style.clone()), Unit::paragraph_with_style(2, "Second page text", style.clone()), ], ); let engine = Engine::layout(&document); assert_eq!(engine.pages().len(), 2, "expected two route-D pages"); let pages: Vec<_> = engine .pages() .iter() .map(|page| page.display_list()) .collect(); let route_pdf_path = root.join("route.pdf"); std::fs::write(&route_pdf_path, display_lists_to_pdf(&pages, 792)).expect("write route PDF"); let classic = r"\documentclass[10pt]{article} \pagestyle{empty} \hoffset=-1in \voffset=-1in \oddsidemargin=0pt \topmargin=0pt \headheight=0pt \headsep=0pt \pdfpagewidth=612bp \pdfpageheight=792bp \textwidth=480pt \textheight=15pt \topskip=10pt \baselineskip=12pt \parindent=0pt \parskip=0pt \begin{document} \vsize=15pt First page text\par Second page text\par \end{document} "; let classic_path = root.join("classic.tex"); std::fs::write(&classic_path, classic).expect("write classic TeX"); let status = Command::new("pdflatex") .args(["-interaction=nonstopmode", "-halt-on-error"]) .arg(&classic_path) .current_dir(&root) .stdout(std::process::Stdio::null()) .stderr(std::process::Stdio::null()) .status() .expect("pdflatex"); assert!(status.success(), "pdflatex failed"); for (pdf, prefix) in [ (route_pdf_path.clone(), "route"), (root.join("classic.pdf"), "classic"), ] { let status = Command::new("pdftoppm") .args(["-r", "72", "-gray"]) .arg(&pdf) .arg(root.join(prefix)) .status() .expect("pdftoppm"); assert!(status.success(), "pdftoppm failed for {}", pdf.display()); } for page in 1..=2 { let route = ink_bbox(&root.join(format!("route-{page}.pgm"))); let classic = ink_bbox(&root.join(format!("classic-{page}.pgm"))); assert!( (route.4 as i64 - classic.4 as i64).abs() <= 2, "page {page} ink row count: route={route:?} classic={classic:?}" ); assert!( (route.1 as i64 - classic.1 as i64).abs() <= 3, "page {page} ink top edge: route={route:?} classic={classic:?}" ); assert!( (route.2 as i64 - classic.2 as i64).abs() <= 2, "page {page} ink left edge: route={route:?} classic={classic:?}" ); assert!( (route.3 as i64 - classic.3 as i64).abs() <= 4, "page {page} ink bottom edge: route={route:?} classic={classic:?}" ); } let _ = std::fs::remove_dir_all(&root); } #[test] fn accented_text_round_trips_through_pdf_extraction() { use std::process::Command; if Command::new("pdftotext") .arg("-v") .stdout(std::process::Stdio::null()) .stderr(std::process::Stdio::null()) .status() .is_err() { return; } let document = Document::new( 60, vec![Unit::paragraph_with_style( 1, "caf\u{e9} na\u{ef}ve r\u{e9}sum\u{e9}", body_style(), )], ); let engine = Engine::layout(&document); let lists: Vec<_> = engine .pages() .iter() .map(|page| page.display_list()) .collect(); let pdf = display_lists_to_pdf(&lists, 792); let path = std::env::temp_dir().join(format!("texrra-accents-{}.pdf", std::process::id())); std::fs::write(&path, &pdf).expect("write PDF"); let output = Command::new("pdftotext") .arg(&path) .arg("-") .output() .expect("pdftotext"); let _ = std::fs::remove_file(&path); let text = String::from_utf8_lossy(&output.stdout); assert!( text.contains("caf\u{e9} na\u{ef}ve r\u{e9}sum\u{e9}"), "got {text:?}" ); } #[test] fn greek_text_round_trips_through_pdf_fallback() { use std::process::Command; if Command::new("pdftotext") .arg("-v") .stdout(std::process::Stdio::null()) .stderr(std::process::Stdio::null()) .status() .is_err() { return; } let body = "\u{3b1}\u{3b2}\u{3b3} \u{3bc}\u{3ad}\u{3b3}\u{3b1} \u{3a9}"; let document = Document::new(65, vec![Unit::paragraph_with_style(1, body, body_style())]); let engine = Engine::layout(&document); let lists: Vec<_> = engine .pages() .iter() .map(|page| page.display_list()) .collect(); let pdf = display_lists_to_pdf_with_cm_type1( &lists, 612 * 65_536, 792 * 65_536, PageOrigin::default(), ); let path = std::env::temp_dir().join(format!("texrra-greek-{}.pdf", std::process::id())); std::fs::write(&path, &pdf).expect("write PDF"); let output = Command::new("pdftotext") .arg(&path) .arg("-") .output() .expect("pdftotext"); let _ = std::fs::remove_file(&path); let text = String::from_utf8_lossy(&output.stdout) .split_whitespace() .collect::>() .join(" "); assert!(text.contains(body), "got {text:?}"); } #[test] fn computer_modern_outlines_keep_extracted_text() { use std::process::Command; if Command::new("pdftotext") .arg("-v") .stdout(std::process::Stdio::null()) .stderr(std::process::Stdio::null()) .status() .is_err() { return; } let body = "The quick brown fox jumps over the lazy dog"; let document = Document::new(62, vec![Unit::paragraph_with_style(1, body, body_style())]); let engine = Engine::layout(&document); let lists: Vec<_> = engine .pages() .iter() .map(|page| page.display_list()) .collect(); let pdf = display_lists_to_pdf_with_cm_type1( &lists, 612 * 65_536, 792 * 65_536, PageOrigin::default(), ); let path = std::env::temp_dir().join(format!("texrra-cm-type1-{}.pdf", std::process::id())); std::fs::write(&path, &pdf).expect("write PDF"); let output = Command::new("pdftotext") .arg(&path) .arg("-") .output() .expect("pdftotext"); let _ = std::fs::remove_file(&path); let text = String::from_utf8_lossy(&output.stdout) .split_whitespace() .collect::>() .join(" "); assert!( text.contains("The quick brown fox jumps over the lazy dog"), "got {text:?}" ); } #[test] fn route_d_text_matches_pdftex_extraction() { use std::process::Command; fn available(command: &str, arg: &str) -> bool { Command::new(command) .arg(arg) .stdout(std::process::Stdio::null()) .stderr(std::process::Stdio::null()) .status() .is_ok_and(|status| status.success()) } if !available("pdflatex", "--version") || !available("pdftotext", "-v") { return; } fn extract(pdf: &std::path::Path) -> String { let output = Command::new("pdftotext") .arg(pdf) .arg("-") .output() .expect("pdftotext"); String::from_utf8_lossy(&output.stdout) .split_whitespace() .collect::>() .join(" ") } let body = "The quick brown fox jumps over the lazy dog. Pack my box with five dozen liquor jugs."; let document = Document::new(61, vec![Unit::paragraph_with_style(1, body, body_style())]); let engine = Engine::layout(&document); let lists: Vec<_> = engine .pages() .iter() .map(|page| page.display_list()) .collect(); let route_pdf = std::env::temp_dir().join(format!("texrra-words-{}.pdf", std::process::id())); std::fs::write(&route_pdf, display_lists_to_pdf(&lists, 792)).expect("write route PDF"); let dir = std::env::temp_dir().join(format!("texrra-pdftex-{}", std::process::id())); let _ = std::fs::remove_dir_all(&dir); std::fs::create_dir_all(&dir).expect("temp dir"); let tex = dir.join("control.tex"); let source = [ "\\documentclass[10pt]{article}", "\\pagestyle{empty}", "\\begin{document}", "\\noindent ", body, "\\end{document}", ] .concat(); std::fs::write(&tex, source).expect("write tex"); let status = Command::new("pdflatex") .current_dir(&dir) .args(["-interaction=nonstopmode", "control.tex"]) .status() .expect("pdflatex"); assert!(status.success(), "pdflatex failed"); let route = extract(&route_pdf); let control = extract(&dir.join("control.pdf")); let _ = std::fs::remove_file(&route_pdf); let _ = std::fs::remove_dir_all(&dir); assert_eq!(route, control); } /// Compare the vertical ink bands of a wrapped paragraph against pdfTeX. Band /// boundaries are the pixel rows that actually contain glyphs, so this checks /// baseline placement rather than just the count of text lines. #[test] fn route_d_multiline_bands_track_pdftex() { use std::process::Command; fn has(command: &str, version_arg: &str) -> bool { Command::new(command) .arg(version_arg) .stdout(std::process::Stdio::null()) .stderr(std::process::Stdio::null()) .status() .is_ok_and(|status| status.success()) } if !has("pdflatex", "--version") || !has("pdftoppm", "-v") { return; } fn bands(path: &std::path::Path) -> Vec<(usize, usize, usize, usize)> { let bytes = std::fs::read(path).expect("read PGM"); assert_eq!(&bytes[..2], b"P5", "expected binary PGM"); let mut fields = Vec::new(); let mut cursor = 2; while fields.len() < 3 { while cursor < bytes.len() && bytes[cursor].is_ascii_whitespace() { cursor += 1; } let start = cursor; while cursor < bytes.len() && bytes[cursor].is_ascii_digit() { cursor += 1; } fields.push( std::str::from_utf8(&bytes[start..cursor]) .expect("PGM number") .parse::() .expect("PGM number"), ); } while cursor < bytes.len() && bytes[cursor].is_ascii_whitespace() { cursor += 1; } let (width, height, _) = (fields[0], fields[1], fields[2]); let pixels = &bytes[cursor..]; assert_eq!(pixels.len(), width * height, "PGM payload size"); let mut found: Vec<(usize, usize, usize, usize)> = Vec::new(); for y in 0..height { let inked: Vec = (0..width).filter(|x| pixels[y * width + x] < 160).collect(); if inked.is_empty() { continue; } let (row_left, row_right) = (inked[0], inked[inked.len() - 1]); match found.last_mut() { Some((_, end, left, right)) if y <= *end + 1 => { *end = y; *left = (*left).min(row_left); *right = (*right).max(row_right); } _ => found.push((y, y, row_left, row_right)), } } found } // The 150pt fixture is the one whose line breaks the oracle already // verifies word for word against pdfLaTeX, so ink bands can be compared // without a break-model difference in the way. let text = "alpha beta gamma delta epsilon zeta eta theta iota kappa lambda mu"; let style = ParagraphStyle { line_expansion: 0, font_size: 10 * 65_536, line_width: 150 * 65_536, left_skip: 0, right_skip: 0, centered: false, right_aligned: false, looseness: 0, ragged_right: false, hang_indent: 0, hang_after: 1, par_shape: Vec::new(), par_fillskip: 0, par_fillskip_stretch: 0, par_fillskip_fil: true, frenchspacing: false, space_factor_codes: Vec::new(), baselineskip: 12 * 65_536, lineskip: 65_536, lineskiplimit: 0, par_indent: 0, emergencystretch: 0, pretolerance: 100, tolerance: 200, hyphen_penalty: 50, ex_hyphen_penalty: 50, double_hyphen_demerits: 10_000, final_hyphen_demerits: 5_000, line_penalty: 10, adj_demerits: 10_000, hyphenation_exceptions: Vec::new(), line_height: 12 * 65_536, char_width: 10 * 65_536, space_width: 4 * 65_536, space_stretch: 6 * 65_536, space_shrink: 2 * 65_536, space_skip: None, xspace_skip: None, }; let document = Document::new( 700 * 65_536, vec![Unit::paragraph_with_style_and_face( 1, text, style, ParagraphFont::Roman, )], ); let engine = Engine::layout(&document); let pages: Vec<_> = engine .pages() .iter() .map(|page| page.display_list()) .collect(); let route_pdf = display_lists_to_pdf(&pages, 792); let root = std::env::temp_dir().join(format!("texrra-bands-{}", std::process::id())); let _ = std::fs::remove_dir_all(&root); std::fs::create_dir_all(&root).expect("create band dir"); let route_pdf_path = root.join("route.pdf"); std::fs::write(&route_pdf_path, route_pdf).expect("write route PDF"); let classic = format!( r"\documentclass[10pt]{{article}} \pagestyle{{empty}} \hoffset=-1in \voffset=-1in \oddsidemargin=0pt \topmargin=0pt \headheight=0pt \headsep=0pt \pdfpagewidth=612bp \pdfpageheight=792bp \textwidth=150pt \textheight=700pt \topskip=10pt \parindent=0pt \begin{{document}} {text} \end{{document}} " ); let classic_path = root.join("classic.tex"); std::fs::write(&classic_path, classic).expect("write classic TeX"); let status = Command::new("pdflatex") .args(["-interaction=nonstopmode", "-halt-on-error"]) .arg(&classic_path) .current_dir(&root) .stdout(std::process::Stdio::null()) .stderr(std::process::Stdio::null()) .status() .expect("pdflatex"); assert!(status.success(), "pdflatex failed"); for pdf in [&route_pdf_path, &root.join("classic.pdf")] { let status = Command::new("pdftoppm") .args(["-r", "72", "-gray", "-singlefile"]) .arg(pdf) .arg(pdf.with_extension("")) .status() .expect("pdftoppm"); assert!(status.success(), "pdftoppm failed for {}", pdf.display()); } let route = bands(&root.join("route.pgm")); let classic = bands(&root.join("classic.pgm")); assert_eq!( route.len(), classic.len(), "line bands: route={route:?} classic={classic:?}" ); let last = route.len().saturating_sub(1); // pdfTeX starts the first baseline at topskip while the paragraph painter // starts it at the glyph ascent. Align both rasters on the first ink band so // this test measures line spacing and justification rather than that known // page-placement difference. let shift = classic.first().map_or(0i64, |band| band.0 as i64) - route.first().map_or(0i64, |band| band.0 as i64); for (index, (route_band, classic_band)) in route.iter().zip(&classic).enumerate() { assert!( ((route_band.0 as i64 + shift) - classic_band.0 as i64).abs() <= 2, "band {index} top: route={route_band:?} classic={classic_band:?}" ); assert!( ((route_band.1 as i64 + shift) - classic_band.1 as i64).abs() <= 2, "band {index} bottom: route={route_band:?} classic={classic_band:?}" ); assert!( (route_band.2 as i64 - classic_band.2 as i64).abs() <= 2, "band {index} left: route={route_band:?} classic={classic_band:?}" ); if index != last { // Every line but the last is justified to the measure in both // engines. The final line keeps its natural width and therefore // reflects where TeX chose its last break, which the simplified // demerits model does not yet reproduce exactly. assert!( (route_band.3 as i64 - classic_band.3 as i64).abs() <= 3, "band {index} right: route={route_band:?} classic={classic_band:?}" ); } } let _ = std::fs::remove_dir_all(&root); } /// TeX `\hoffset`/`\voffset` translate the page body without moving the sheet. #[test] fn page_origin_offsets_move_the_page_body() { use std::path::Path; use std::process::Command; fn has(command: &str, version_arg: &str) -> bool { Command::new(command) .arg(version_arg) .stdout(std::process::Stdio::null()) .stderr(std::process::Stdio::null()) .status() .is_ok_and(|status| status.success()) } if !has("pdftotext", "-v") { return; } fn word_xy(pdf: &Path, out: &Path) -> (f64, f64) { let status = Command::new("pdftotext") .arg("-bbox") .arg(pdf) .arg(out) .status() .expect("pdftotext"); assert!(status.success(), "pdftotext failed for {}", pdf.display()); let xml = std::fs::read_to_string(out).expect("read bbox xml"); let rest = &xml[xml.find("xMin=").expect("xMin")..]; let number = |key: &str| -> f64 { let at = rest.find(key).expect(key) + key.len(); let tail = &rest[at..]; let end = tail.find('"').expect("quote"); tail[..end].parse().expect("bbox number") }; (number("xMin=\""), number("yMin=\"")) } let document = Document::new( 600 * 65_536, vec![Unit::paragraph_with_style_and_face( 0, "Origin", body_style(), ParagraphFont::Roman, )], ); let engine = Engine::layout(&document); let mut list = engine.pages()[0].display_list(); list.width = list.width.max(612 * 65_536); list.height = list.height.max(792 * 65_536); let pages = std::slice::from_ref(&list); let root = std::env::temp_dir().join(format!("texrra-origin-{}", std::process::id())); let _ = std::fs::remove_dir_all(&root); std::fs::create_dir_all(&root).expect("create origin dir"); let plain = root.join("plain.pdf"); let moved = root.join("moved.pdf"); std::fs::write(&plain, display_lists_to_pdf(pages, 792 * 65_536)).expect("write plain pdf"); std::fs::write( &moved, display_lists_to_pdf_with_origin( pages, 792 * 65_536, PageOrigin { h_offset: 10 * 65_536, v_offset: 20 * 65_536, }, ), ) .expect("write moved pdf"); let (plain_x, plain_y) = word_xy(&plain, &root.join("plain.html")); let (moved_x, moved_y) = word_xy(&moved, &root.join("moved.html")); assert!( (moved_x - plain_x - 10.0).abs() < 0.6, "hoffset moved x by {}", moved_x - plain_x ); assert!( (moved_y - plain_y - 20.0).abs() < 0.6, "voffset moved y by {}", moved_y - plain_y ); }