//! Actual post-line-break penalties, vertical lists and page ownership vs INITEX. #[path = "support/font_world.rs"] mod font_world; use font_world::FontFiles; use std::{fs, path::PathBuf, process::Command}; use texrra_tex_core::execution::*; use texrra_tex_core::{Engine, HorizontalItem, VerticalItem}; const PT: i64 = 65536; const SETUP: &str = r"\catcode123=1 \catcode125=2 \catcode35=6 \defaulthyphenchar=45 \font\p=cmr10 \p \hsize=100pt \baselineskip=12pt \parfillskip=0pt plus1fil \boxmaxdepth=100pt \hbadness=10000 \vbadness=10000 \lefthyphenmin=2 \righthyphenmin=3 "; fn run(body: &str) -> Execution { Executor::new(State::initex().with_etex(), Limits::default()) .run( SourceFile { name: "interline.tex".into(), data: (format!("{SETUP}{body}\\end\n")).as_bytes().to_vec(), }, &mut FontFiles, ) .unwrap() } fn paragraphs(e: &Execution) -> Vec<&NativeParagraph> { e.events .iter() .filter_map(|e| { if let Event::BuiltParagraph(p) = e { Some(p.as_ref()) } else { None } }) .collect() } fn root(e: &Execution) -> Vec { e.events .iter() .filter_map(|e| { if let Event::VerticalMaterial(v) = e { Some(v.clone()) } else { None } }) .flatten() .collect() } fn penalties(nodes: &[NativeVerticalNode]) -> Vec { nodes .iter() .filter_map(|n| { if let NativeVerticalNode::Penalty(p) = n { Some(*p) } else { None } }) .collect() } fn forced(n: usize) -> String { (0..n) .map(|i| char::from(b'A' + i as u8).to_string()) .collect::>() .join(r"\penalty-10000 ") } fn directory(name: &str) -> PathBuf { let p = std::env::temp_dir().join(format!("texrra-interline-{name}-{}", std::process::id())); fs::create_dir_all(&p).unwrap(); p } fn tex_log(dir: &PathBuf, source: &str) -> Option { fs::write( dir.join("probe.tex"), format!("{SETUP}\\showboxbreadth=10000 \\showboxdepth=5 \\tracingonline=1 {source}\\end\n"), ) .unwrap(); match Command::new("pdftex") .args(["-ini", "-etex", "-interaction=nonstopmode", "probe.tex"]) .current_dir(dir) .output() { Ok(o) => { let s = fs::read_to_string(dir.join("probe.log")).unwrap(); assert!( s.contains("! OK."), "{}\n{s}", String::from_utf8_lossy(&o.stdout) ); Some(s) } Err(e) if e.kind() == std::io::ErrorKind::NotFound => { eprintln!("pdftex unavailable: interline oracle skipped"); None } Err(e) => panic!("{e}"), } } #[test] fn post_line_penalties_are_summed_before_glue_and_frozen_at_par_end() { let e = run( r"\interlinepenalty=7 \clubpenalty=100 \widowpenalty=200 \brokenpenalty=300 A\penalty-10000 B\par \interlinepenalty=0 \clubpenalty=0 \widowpenalty=0 A\penalty-10000 B\penalty-10000 C\par", ); let p = paragraphs(&e); assert_eq!(p[0].interline_penalties, [307]); assert_eq!(p[0].discretionary_breaks, [false, false]); assert_eq!(p[1].interline_penalties, [0, 0]); let nodes = root(&e); assert_eq!(penalties(&nodes), [307]); let i = nodes .iter() .position(|n| matches!(n, NativeVerticalNode::Penalty(307))) .unwrap(); assert!(matches!(nodes[i - 1], NativeVerticalNode::Line(..))); assert!(matches!( nodes[i + 1], NativeVerticalNode::NamedGlue(_, Parameter::Baselineskip | Parameter::Lineskip) )); let e = run( r"\clubpenalty=10 {\clubpenalty=20 A\penalty-10000 B\clubpenalty=30\par}\clubpenalty=99 A\penalty-10000 B\par", ); let p = paragraphs(&e); assert_eq!(p[0].interline_penalties, [30]); assert_eq!(p[1].interline_penalties, [99]); let e = run( r"\clubpenalty=10{\global\clubpenalty=20{\clubpenalty=30\globaldefs=1\clubpenalty=40}}\advance\clubpenalty by2 \multiply\clubpenalty by3 \divide\clubpenalty by2 A\penalty-10000 B\par", ); assert_eq!(paragraphs(&e)[0].interline_penalties, [63]); assert!( e.reads .contains(&Dependency::Parameter(Parameter::Clubpenalty)) ); let copy: Execution = serde_json::from_str(&serde_json::to_string(&e).unwrap()).unwrap(); assert_eq!(copy, e); for p in [ Parameter::Interlinepenalty, Parameter::Clubpenalty, Parameter::Widowpenalty, Parameter::Brokenpenalty, ] { assert_eq!(State::initex().parameter(p), ParameterValue::Integer(0)); } } #[test] fn stored_and_copied_boxes_keep_penalties_without_executing_page_breaks_inside() { let e = run( r"\interlinepenalty=-10000 \setbox0=\vbox{A\penalty-10000 B\penalty-10000 C\par}\interlinepenalty=0 \copy0\copy0", ); let b = e.state.box_register(0).unwrap(); let BoxContent::Vertical(v) = &b.content else { panic!() }; assert_eq!(penalties(v), [-10000, -10000]); assert_eq!( root(&e) .iter() .filter(|n| matches!(n, NativeVerticalNode::Box(_))) .count(), 2 ); assert_eq!( Engine::layout_paged(&e.document().unwrap()) .unwrap() .pages() .len(), 1 ); let result = Executor::default().run( SourceFile { name: "overflow.tex".into(), data: (r"\interlinepenalty=2147483647 \clubpenalty=1 A\penalty-10000 B\par") .as_bytes() .to_vec(), }, &mut FontFiles, ); assert!(result.unwrap_err().message.contains("penalty sum overflow")); } #[derive(Debug, PartialEq)] enum Mark { Line, Glue(i64), Penalty(i32), Kern(i64), } fn native_marks(v: &[NativeVerticalNode]) -> Vec { v.iter() .map(|n| match n { NativeVerticalNode::Line(..) => Mark::Line, NativeVerticalNode::Glue(g) | NativeVerticalNode::NamedGlue(g, _) => { Mark::Glue(g.width as i64) } NativeVerticalNode::Penalty(n) => Mark::Penalty(*n), NativeVerticalNode::Kern(n) => Mark::Kern(*n as i64), _ => panic!("unexpected list item {n:?}"), }) .collect() } fn reference_marks(log: &str) -> Vec { log.split("> \\box0=") .nth(1) .unwrap() .lines() .filter_map(|s| { if s.starts_with(".\\hbox(") { return Some(Mark::Line); } if let Some(n) = s.strip_prefix(".\\penalty ") { return Some(Mark::Penalty(n.parse().unwrap())); } if let Some(n) = s .strip_prefix(".\\glue(") .and_then(|s| s.split_once(") ").map(|(_, v)| v)) { return Some(Mark::Glue( (n.split_whitespace().next().unwrap().parse::().unwrap() * PT as f64) .round() as i64, )); } s.strip_prefix(".\\kern ") .map(|n| Mark::Kern((n.parse::().unwrap() * PT as f64).round() as i64)) }) .collect() } #[test] fn vertical_lists_and_discretionary_breaks_match_real_initex() { let dir = directory("vlist"); let mut cases = Vec::new(); for n in [1, 2, 3, 5] { for (i, c, w, b) in [ (0, 0, 0, 0), (11, 101, 103, 107), (-7, -20, 35, -5), (10000, 150, 150, 100), (-10000, 20000, 20000, 100), (0, 150, -150, -50), (0, 10000, 10000, 0), ] { cases.push(format!(r"\interlinepenalty={i} \clubpenalty={c} \widowpenalty={w} \brokenpenalty={b} {}\par",forced(n))); } } for width in [35, 45, 60, 80] { for b in [-10000, 0, 100, 10000] { for text in [ r"con\-struction para\-graph hy\-phenation con\-struction", r"construction paragraph hyphenation construction", r"Alpha-beta gamma-delta epsilon-zeta", ] { cases.push(format!(r"\hsize={width}pt \pretolerance=-1 \tolerance=10000 \hyphenation{{con-struc-tion para-graph hy-phen-a-tion}}\interlinepenalty=7 \clubpenalty=11 \widowpenalty=13 \brokenpenalty={b} {text}\par")); } } } cases.extend([ r"\clubpenalty=10 {\clubpenalty=20 A\penalty-10000 B}\par".into(), r"\clubpenalty=10 A\penalty-10000 B\clubpenalty=30\par".into(), r"\interlinepenalty=-5 \clubpenalty=5 A\penalty-10000 B\penalty-10000 C\par".into(), r"\interlinepenalty=7 \baselineskip=5pt \lineskip=3pt \lineskiplimit=2pt A\penalty-10000 B\penalty-10000 C\par".into(), ]); for name in [ "interlinepenalty", "clubpenalty", "widowpenalty", "brokenpenalty", ] { let text = r"\hsize=35pt con\-struction"; cases.extend([ format!(r"\{name}=17{{\{name}=29 {text}}}\par"), format!(r"\{name}=17{{\{name}=29 {text}\par}}"), format!(r"\{name}=17{{\global\{name}=29 {text}\par}}"), format!(r"\{name}=17{{\globaldefs=1\{name}=29 {text}\par}}"), format!(r"\{name}=17 {text}\{name}=29\par"), ]); } let mut disc_count = 0; for (i, body) in cases.iter().enumerate() { let e = run(&format!(r"\setbox0=\vbox{{{body}}}")); let p = paragraphs(&e); disc_count += p .iter() .flat_map(|p| &p.discretionary_breaks) .filter(|b| **b) .count(); let BoxContent::Vertical(v) = &e.state.box_register(0).unwrap().content else { panic!() }; let Some(log) = tex_log(&dir, &format!(r"\setbox0=\vbox{{{body}}}\showbox0")) else { fs::remove_dir_all(dir).unwrap(); return; }; let a = native_marks(v); let b = reference_marks(&log); assert_eq!(a.len(), b.len(), "case {i}: {body}\n{a:?}\n{b:?}\n{log}"); for (a, b) in a.iter().zip(&b) { match (a, b) { (Mark::Glue(a), Mark::Glue(b)) | (Mark::Kern(a), Mark::Kern(b)) => { assert!((a - b).abs() <= 1, "case {i}: {body}\n{a:?} != {b:?}") } _ => assert_eq!(a, b, "case {i}: {body}\n{log}"), } } } assert!(disc_count > 20, "must actually select discretionary breaks"); eprintln!( "{} real INITEX interline vlist cases passed ({disc_count} selected discretionary breaks)", cases.len() ); fs::remove_dir_all(dir).unwrap(); } fn bp(n: i64) -> i64 { (n * 800 + 401) / 803 } fn item_text(items: &[HorizontalItem]) -> String { font_world::painted_text(items) } fn native_pages(e: &Execution, goal: i64) -> Vec> { let mut d = e.document().unwrap(); d.page_goal = bp(goal * PT); d.top_skip = bp(10 * PT); d.max_depth = bp(4 * PT); Engine::layout_paged(&d) .unwrap() .pages() .iter() .map(|p| { p.items .iter() .filter_map(|i| { if let VerticalItem::Paragraph(p) = i { let text = p.lines.iter().map(|row| item_text(row)).collect::(); if !text.is_empty() { return Some(text); } } None }) .collect::>() }) .collect() } fn reference_pages(log: &str) -> Vec> { log.split("> \\box255=") .skip(1) .map(|section| { let mut lines = Vec::::new(); for s in section.lines().take_while(|s| !s.starts_with("! OK.")) { if s.starts_with(".\\hbox(") { lines.push(String::new()); } if let Some(c) = s.strip_prefix("..\\p ") && let Some(line) = lines.last_mut() { line.push_str(c); } } lines .into_iter() .filter(|s| !s.is_empty()) .collect::>() }) .filter(|p| !p.is_empty()) .collect() } #[test] fn actual_interline_penalties_change_page_ownership_like_real_initex() { let dir = directory("pages"); let mut cases = 0; let mut signatures = std::collections::BTreeSet::new(); for goal in [30, 42, 54] { for prefix in ["", r"\hbox{Z}\vskip5pt plus10pt "] { for (i, c, w, b) in [ (0, 0, 0, 0), (0, 10000, 0, 0), (0, 0, 10000, 0), (0, 10000, 10000, 0), (10000, 0, 0, 0), (-10000, 0, 0, 0), (100, 150, 150, 100), (0, -500, 500, 0), ] { let body = format!( r"{prefix}\interlinepenalty={i} \clubpenalty={c} \widowpenalty={w} \brokenpenalty={b} {}\par", forced(6) ); let native = native_pages(&run(&body), goal); let Some(log) = tex_log( &dir, &format!( r"\vsize={goal}pt \topskip=10pt \maxdepth=4pt \output={{\showbox255\shipout\box255}}{body}" ), ) else { fs::remove_dir_all(dir).unwrap(); return; }; let reference = reference_pages(&log); assert_eq!( native, reference, "page case {cases}: goal={goal}, {body}\n{log}" ); signatures.insert(format!("{native:?}")); cases += 1; } } } for goal in [30, 42, 54, 66] { for broken in [-10000, 0, 100, 10000] { let body = format!( r"\hsize=35pt \pretolerance=-1 \tolerance=10000 \hyphenation{{con-struc-tion para-graph hy-phen-a-tion}}\brokenpenalty={broken} con\-struction para\-graph hy\-phenation con\-struction\par" ); let e = run(&body); assert!(paragraphs(&e)[0].discretionary_breaks.iter().any(|b| *b)); let native = native_pages(&e, goal); let Some(log) = tex_log( &dir, &format!( r"\vsize={goal}pt \topskip=10pt \maxdepth=4pt \output={{\showbox255\shipout\box255}}{body}" ), ) else { fs::remove_dir_all(dir).unwrap(); return; }; assert_eq!( native, reference_pages(&log), "broken page case {cases}: goal={goal}, {body}\n{log}" ); cases += 1; } } assert!( signatures.len() > 5, "penalty changes must alter actual page ownership" ); eprintln!("{cases} real INITEX page-ownership cases passed"); fs::remove_dir_all(dir).unwrap(); }