447 lines
16 KiB
Rust
447 lines
16 KiB
Rust
//! Actual native paragraph input/state -> node lists -> measured lines.
|
|
#[path = "support/font_world.rs"]
|
|
mod font_world;
|
|
use font_world::FontFiles;
|
|
use std::{fs, process::Command};
|
|
use texrra_tex_core::execution::*;
|
|
const SETUP: &str = "\\catcode123=1 \\catcode125=2 \\catcode35=6\n\\defaulthyphenchar=45 \\font\\p=cmr10 \\p \\hsize=100pt \\parindent=10pt \\baselineskip=12pt \\parfillskip=0pt plus1fil \\pretolerance=100 \\tolerance=200 \\hbadness=10000 \\linepenalty=10 \\hyphenpenalty=50 \\exhyphenpenalty=50 \\adjdemerits=10000 \\doublehyphendemerits=10000 \\finalhyphendemerits=5000 \\lefthyphenmin=2 \\righthyphenmin=3\n";
|
|
fn run(body: &str) -> Execution {
|
|
Executor::new(
|
|
State::initex().with_etex(),
|
|
Limits {
|
|
steps: 1_000_000,
|
|
..Limits::default()
|
|
},
|
|
)
|
|
.run(
|
|
SourceFile {
|
|
name: "paragraph.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 line_text(p: &NativeParagraph) -> Vec<String> {
|
|
p.lines
|
|
.iter()
|
|
.map(|line| font_world::painted_text(&line.lines[0]))
|
|
.collect()
|
|
}
|
|
fn normalize(s: &str) -> String {
|
|
s.replace('ff', "ff")
|
|
.replace('fi', "fi")
|
|
.replace('fl', "fl")
|
|
.replace('ffi', "ffi")
|
|
.replace('ffl', "ffl")
|
|
}
|
|
|
|
#[test]
|
|
fn native_parameters_have_scopes_and_par_end_timing() {
|
|
let e = run(
|
|
r"\hsize=80pt\parindent=3pt {Alpha beta gamma delta epsilon zeta eta theta.\hsize=120pt\par}\noindent Alpha beta gamma delta epsilon zeta eta theta.\par",
|
|
);
|
|
let p = paragraphs(&e);
|
|
assert_eq!(p.len(), 2);
|
|
assert_eq!(p[0].parameters[&Parameter::Hsize].width(), 120 * 65536);
|
|
assert_eq!(p[1].parameters[&Parameter::Hsize].width(), 80 * 65536);
|
|
assert!(matches!(p[0].nodes.first(),Some(TextNode::Indent(n)) if *n==3*65536));
|
|
assert!(!matches!(p[1].nodes.first(), Some(TextNode::Indent(_))));
|
|
assert!(p[1].lines.len() > p[0].lines.len());
|
|
let doc = e.document().unwrap();
|
|
assert!(doc.units.iter().all(|u| u.paragraph_style.is_none()));
|
|
let copy: Execution = serde_json::from_str(&serde_json::to_string(&e).unwrap()).unwrap();
|
|
assert_eq!(e, copy);
|
|
}
|
|
|
|
#[test]
|
|
fn space_and_baseline_parameters_are_consumed_at_their_actual_stage() {
|
|
let e = run(
|
|
r"\spaceskip=2pt plus1pt minus.5pt A B\spaceskip=8pt plus2pt{} C\par \baselineskip=20pt\lineskip=3pt\lineskiplimit=1pt\parskip=4pt Alpha beta gamma delta epsilon zeta eta theta iota kappa lambda mu.\par",
|
|
);
|
|
let p = paragraphs(&e);
|
|
let glues: Vec<_> = p[0]
|
|
.nodes
|
|
.iter()
|
|
.filter_map(|n| {
|
|
if let TextNode::Glue(g) | TextNode::NamedGlue(g, _) = n {
|
|
Some(g.width)
|
|
} else {
|
|
None
|
|
}
|
|
})
|
|
.collect();
|
|
assert_eq!(glues, [2 * 65536, 8 * 65536]);
|
|
assert_eq!(p[1].parskip.width, 4 * 65536);
|
|
assert_eq!(
|
|
p[1].parameters[&Parameter::Baselineskip].width(),
|
|
20 * 65536
|
|
);
|
|
let doc = e.document().unwrap();
|
|
assert!(doc.units[1].items.iter().any(|n|matches!(n,texrra_tex_core::VerticalItem::StretchGlue(g) if g.width==(4*65536*800+401)/803)));
|
|
let e = run(r"\xspaceskip=9pt A\spacefactor=3000{} B\par");
|
|
let p = paragraphs(&e);
|
|
assert!(
|
|
p[0].nodes
|
|
.iter()
|
|
.any(|n| matches!(n,TextNode::Glue(g) | TextNode::NamedGlue(g, _) if g.width==9*65536))
|
|
);
|
|
}
|
|
|
|
#[test]
|
|
fn initex_font_and_unsupported_material_are_not_silently_substituted() {
|
|
assert_eq!(State::initex().text_font(), FontId::NULL);
|
|
let e=Executor::new(State::initex(),Limits::default()).run(SourceFile{name:"font.tex".into(),data:r"\catcode123=1 \catcode125=2 {\font\a=cmr10 \a}\defaulthyphenchar=45 \font\b=cmr10 \b\end".into()},&mut FontFiles).unwrap();
|
|
// Font resources outlive a local selector; a repeated font load reuses it.
|
|
assert_eq!(
|
|
e.state.fonts().font(e.state.text_font()).unwrap().name(),
|
|
"cmr10"
|
|
);
|
|
assert_eq!(e.state.font_integers(e.state.text_font()).hyphen, 0);
|
|
let e = Executor::new(State::initex(), Limits::default())
|
|
.run(
|
|
SourceFile {
|
|
name: "null.tex".into(),
|
|
data: ("A").as_bytes().to_vec(),
|
|
},
|
|
&mut FontFiles,
|
|
)
|
|
.unwrap();
|
|
assert!(
|
|
e.events
|
|
.iter()
|
|
.any(|e| matches!(e,Event::MissingGlyph(m) if m.font==FontId::NULL&&m.slot==b'A'))
|
|
);
|
|
let sized = Executor::default()
|
|
.run(
|
|
SourceFile {
|
|
name: "sized.tex".into(),
|
|
data: br"\font\x=cmr10 at12pt \x \setbox0=\hbox{A}\end".to_vec(),
|
|
},
|
|
&mut FontFiles,
|
|
)
|
|
.unwrap();
|
|
assert_eq!(
|
|
sized
|
|
.state
|
|
.fonts()
|
|
.font(sized.state.text_font())
|
|
.unwrap()
|
|
.size_sp(),
|
|
12 * 65536
|
|
);
|
|
assert_eq!(sized.state.box_register(0).unwrap().width, 589825);
|
|
for body in [
|
|
r"\font\x=missingfont ",
|
|
r"\leftskip=0pt minus1fil A\par",
|
|
r"\spacefactor=0",
|
|
r"\errorcontextlines=2147483648",
|
|
] {
|
|
assert!(
|
|
Executor::default()
|
|
.run(
|
|
SourceFile {
|
|
name: "bad.tex".into(),
|
|
data: body.as_bytes().to_vec(),
|
|
},
|
|
&mut FontFiles
|
|
)
|
|
.is_err(),
|
|
"{body}"
|
|
);
|
|
}
|
|
}
|
|
|
|
#[test]
|
|
fn paragraph_passes_mode_scopes_and_badness_have_observable_effects() {
|
|
let body = r"\hyphenation{hy-phen-a-tion para-graph con-struc-tion}\hsize=55pt \tolerance=10000 paragraph construction hyphenation paragraph construction hyphenation\par";
|
|
let early = run(&format!(r"\pretolerance=10000 {body}"));
|
|
let hyphenated = run(&format!(r"\pretolerance=-1 {body}"));
|
|
assert_eq!(paragraphs(&early)[0].pass, 0);
|
|
assert_eq!(paragraphs(&hyphenated)[0].pass, 1);
|
|
assert_ne!(
|
|
line_text(paragraphs(&early)[0]),
|
|
line_text(paragraphs(&hyphenated)[0])
|
|
);
|
|
let e = run(
|
|
r"\hangindent=7pt\par\message{\the\hangindent}\ifvmode\message{VERTICAL}\fi\noindent A\ifhmode\message{HORIZONTAL}\fi{\hsize=80pt\advance\hsize by2pt\pretolerance=20\multiply\pretolerance by3\spaceskip=2pt plus1fil\message{\the\hsize/\the\pretolerance/\the\spaceskip}\global\tolerance=321}\par\message{\the\hsize/\the\pretolerance/\the\tolerance}",
|
|
);
|
|
let messages: Vec<_> = e
|
|
.events
|
|
.iter()
|
|
.filter_map(|e| {
|
|
if let Event::Message { text, .. } = e {
|
|
Some(text.as_str())
|
|
} else {
|
|
None
|
|
}
|
|
})
|
|
.collect();
|
|
assert_eq!(
|
|
messages,
|
|
[
|
|
"0.0pt",
|
|
"VERTICAL",
|
|
"HORIZONTAL",
|
|
"82.0pt/60/2.0pt plus 1.0fil",
|
|
"100.0pt/100/321"
|
|
]
|
|
);
|
|
assert_eq!(e.paragraph_mode, ParagraphMode::Vertical);
|
|
assert!(e.reads.contains(&Dependency::ParagraphMode));
|
|
#[derive(Default)]
|
|
struct Host(Vec<String>);
|
|
impl SourceProvider for Host {
|
|
font_world::font_resources!();
|
|
fn read(&mut self, _: &str, _: &str) -> Result<SourceFile, String> {
|
|
Err("no files".into())
|
|
}
|
|
fn observe_message(&mut self, text: &str) -> Result<(), String> {
|
|
self.0.push(text.into());
|
|
Ok(())
|
|
}
|
|
}
|
|
let mut host = Host::default();
|
|
Executor::default()
|
|
.run(
|
|
SourceFile {
|
|
name: "warning.tex".into(),
|
|
data: (r"\hsize=30pt\hbadness=0 Longword longword longword.\par")
|
|
.as_bytes()
|
|
.to_vec(),
|
|
},
|
|
&mut host,
|
|
)
|
|
.unwrap();
|
|
assert!(host.0.iter().any(|s| s.contains("badness")));
|
|
let mut host = Host::default();
|
|
Executor::default()
|
|
.run(
|
|
SourceFile {
|
|
name: "quiet.tex".into(),
|
|
data: (r"\hsize=100pt\hbadness=10000 A.\par").as_bytes().to_vec(),
|
|
},
|
|
&mut host,
|
|
)
|
|
.unwrap();
|
|
assert!(host.0.is_empty());
|
|
let mut host = Host::default();
|
|
Executor::default()
|
|
.run(
|
|
SourceFile {
|
|
name: "overfull.tex".into(),
|
|
data: (r"\hsize=10pt\hbadness=100000 Longword.\par")
|
|
.as_bytes()
|
|
.to_vec(),
|
|
},
|
|
&mut host,
|
|
)
|
|
.unwrap();
|
|
assert!(
|
|
host.0.iter().any(|s| s.contains("1000000")),
|
|
"hbadness must not suppress overfull boxes"
|
|
);
|
|
assert!(
|
|
Executor::default()
|
|
.run(
|
|
SourceFile {
|
|
name: "overflow.tex".into(),
|
|
data: (r"\spaceskip=1pt plus16000pt A\spacefactor=32767{} B")
|
|
.as_bytes()
|
|
.to_vec(),
|
|
},
|
|
&mut FontFiles
|
|
)
|
|
.unwrap_err()
|
|
.message
|
|
.contains("overflow")
|
|
);
|
|
}
|
|
|
|
#[test]
|
|
fn node_breaks_match_real_initex_paragraph_lines() {
|
|
let body = "Alpha beta gamma delta epsilon zeta eta theta iota kappa lambda mu nu xi omicron.";
|
|
let dir = std::env::temp_dir().join(format!("texrra-paragraph-oracle-{}", std::process::id()));
|
|
fs::create_dir_all(&dir).unwrap();
|
|
let mut variants: Vec<(String, String)> = vec![
|
|
"",
|
|
r"\hsize=80pt ",
|
|
r"\leftskip=5pt \rightskip=3pt ",
|
|
r"\hangindent=10pt \hangafter=1 ",
|
|
r"\noindent ",
|
|
r"\parindent=20pt ",
|
|
r"\tolerance=10000 ",
|
|
r"\pretolerance=-1 \emergencystretch=3pt ",
|
|
]
|
|
.into_iter()
|
|
.map(|p| (p.into(), body.into()))
|
|
.collect();
|
|
for width in [60, 80, 100, 120, 140, 160] {
|
|
for pretol in [-1, 0, 100, 10000] {
|
|
for tolerance in [0, 200, 10000] {
|
|
variants.push((
|
|
format!(r"\hsize={width}pt \pretolerance={pretol} \tolerance={tolerance} "),
|
|
body.into(),
|
|
));
|
|
}
|
|
}
|
|
}
|
|
for looseness in [-2, -1, 1, 2] {
|
|
variants.push((
|
|
format!(r"\pretolerance=-1 \tolerance=10000 \looseness={looseness} "),
|
|
body.into(),
|
|
));
|
|
}
|
|
for penalty in [-100, 0, 100, 10000] {
|
|
variants.push((
|
|
format!(r"\linepenalty={penalty} \tolerance=10000 "),
|
|
body.into(),
|
|
));
|
|
}
|
|
for width in [55, 65, 75, 85, 100, 120] {
|
|
for pretol in [-1, 100, 10000] {
|
|
variants.push((format!(r"\hyphenation{{hy-phen-a-tion para-graph con-struc-tion}}\hsize={width}pt \pretolerance={pretol} \tolerance=10000 "),"paragraph construction hyphenation paragraph construction hyphenation".into()));
|
|
}
|
|
}
|
|
variants.push((
|
|
r"\hsize=100pt ".into(),
|
|
"office affine finally fluff efficient AVATAR.".into(),
|
|
));
|
|
variants.push((
|
|
r"\hsize=70pt \exhyphenpenalty=-100 ".into(),
|
|
"Alpha-beta gamma-delta epsilon-zeta.".into(),
|
|
));
|
|
for params in [
|
|
r"\hangindent=-10pt \hangafter=-2 ",
|
|
r"\baselineskip=6pt \lineskip=3pt \lineskiplimit=1pt ",
|
|
r"\spaceskip=4pt plus2pt minus1pt ",
|
|
r"\leftskip=0pt plus1fil ",
|
|
] {
|
|
variants.push((params.into(), body.into()));
|
|
}
|
|
for text in [
|
|
r"Alpha\kern2pt{} beta gamma delta epsilon zeta eta theta.",
|
|
r"Alpha\penalty-10000 beta gamma delta epsilon zeta eta theta.",
|
|
r"Alpha beta\hskip3pt plus2pt gamma delta epsilon zeta eta theta.",
|
|
r"Alpha beta- gamma delta epsilon zeta eta theta.",
|
|
r"Alpha con\-struction gamma delta epsilon zeta eta theta.",
|
|
r"Alpha\spacefactor=3000{} beta gamma delta epsilon zeta eta theta.",
|
|
] {
|
|
variants.push((r"\hsize=80pt ".into(), text.into()));
|
|
}
|
|
variants.push((
|
|
r"\hsize=100pt ".into(),
|
|
r"office f{}i f\relax i f\count0=1 i ff{}i.".into(),
|
|
));
|
|
for (index, (params, body)) in variants.iter().enumerate() {
|
|
let e = run(&format!("{params}{body}\\par"));
|
|
let p = paragraphs(&e);
|
|
fs::write(dir.join("probe.tex"),format!("{SETUP}\\showboxbreadth=10000 \\showboxdepth=10 \\tracingonline=1\n\\setbox0=\\vbox{{{params}{body}\\par}}\\showbox0\\end\n")).unwrap();
|
|
let output = match Command::new("pdftex")
|
|
.args(["-ini", "-etex", "-interaction=nonstopmode", "probe.tex"])
|
|
.current_dir(&dir)
|
|
.output()
|
|
{
|
|
Ok(o) => o,
|
|
Err(e) if e.kind() == std::io::ErrorKind::NotFound => {
|
|
eprintln!("pdftex unavailable: paragraph oracle skipped");
|
|
fs::remove_dir_all(dir).unwrap();
|
|
return;
|
|
}
|
|
Err(e) => panic!("{e}"),
|
|
};
|
|
let log = fs::read_to_string(dir.join("probe.log")).unwrap();
|
|
assert!(
|
|
log.contains("! OK."),
|
|
"{}",
|
|
String::from_utf8_lossy(&output.stdout)
|
|
);
|
|
let mut lines = Vec::<String>::new();
|
|
let mut sizes = Vec::new();
|
|
let mut gaps = Vec::new();
|
|
for line in log.split("> \\box0=").nth(1).unwrap().lines() {
|
|
if let Some(size) = line.strip_prefix(".\\hbox(") {
|
|
lines.push(String::new());
|
|
let (hd, w) = size.split_once(")x").unwrap();
|
|
let (h, d) = hd.split_once('+').unwrap();
|
|
let w = w.split([',', ' ']).next().unwrap();
|
|
let sp = |n: &str| (n.parse::<f64>().unwrap() * 65536.0).round() as i64;
|
|
sizes.push((sp(h), sp(d), sp(w)));
|
|
} else if let Some(g) = line
|
|
.strip_prefix(".\\glue(\\baselineskip) ")
|
|
.or_else(|| line.strip_prefix(".\\glue(\\lineskip) "))
|
|
{
|
|
gaps.push(
|
|
(g.split_whitespace().next().unwrap().parse::<f64>().unwrap() * 65536.0).round()
|
|
as i64,
|
|
);
|
|
} else if let Some(c) = line.strip_prefix("..\\p ")
|
|
&& let Some(last) = lines.last_mut()
|
|
{
|
|
let glyph = c.split(" (ligature").next().unwrap();
|
|
last.push_str(&match glyph {
|
|
"^^K" => "ff",
|
|
"^^L" => "fi",
|
|
"^^M" => "fl",
|
|
"^^N" => "ffi",
|
|
"^^O" => "ffl",
|
|
_ => glyph,
|
|
});
|
|
}
|
|
}
|
|
assert_eq!(
|
|
line_text(p[0])
|
|
.iter()
|
|
.map(|s| normalize(s))
|
|
.collect::<Vec<_>>(),
|
|
lines,
|
|
"paragraph case {index}: {params}\n{log}"
|
|
);
|
|
let doc = e.document().unwrap();
|
|
let native_gaps: Vec<_> = doc.units[0]
|
|
.items
|
|
.iter()
|
|
.filter_map(|i| {
|
|
if let texrra_tex_core::VerticalItem::StretchGlue(g) = i {
|
|
Some(g.width)
|
|
} else {
|
|
None
|
|
}
|
|
})
|
|
.collect();
|
|
let native_gaps = &native_gaps[1..]; // root parskip precedes the first line
|
|
assert_eq!(native_gaps.len(), gaps.len());
|
|
for (native, reference) in native_gaps.iter().copied().zip(gaps) {
|
|
assert!(
|
|
(native - (reference * 800 + 401) / 803).abs() <= 1,
|
|
"interline glue case {index}"
|
|
);
|
|
}
|
|
for (line, (h, d, w)) in p[0].lines.iter().zip(sizes) {
|
|
assert!(
|
|
(line.line_baselines[0] - h).abs() <= 1
|
|
&& (line.depth - d).abs() <= 1
|
|
&& (line.width - w).abs() <= 1,
|
|
"line box dimensions case {index}"
|
|
);
|
|
}
|
|
}
|
|
eprintln!(
|
|
"{} native paragraph line-break INITEX cases passed",
|
|
variants.len()
|
|
);
|
|
fs::remove_dir_all(dir).unwrap();
|
|
}
|