Advance native LaTeX execution and preview
This commit is contained in:
1 parent
91f9d76b16
commit
2741546ca8
414 files changed
+99872
-933
No files matched your search
@@ -0,0 +1,495 @@
|
||||
//! Native math integration: stored geometry, optical fonts, PDF/SVG parity.
|
||||
use std::fs;
|
||||
use std::process::Command;
|
||||
use texrra_tex_core::cmr10::Cmr10Metrics;
|
||||
use texrra_tex_core::math::{MathAtom, parse_math};
|
||||
use texrra_tex_core::math_font::MathFontId;
|
||||
use texrra_tex_core::paragraph::{HorizontalItem, InlineSegment, ParagraphFont, ParagraphStyle};
|
||||
use texrra_tex_core::pdf::{PageOrigin, display_lists_to_pdf_with_cm_type1};
|
||||
use texrra_tex_core::render::DisplayItem;
|
||||
use texrra_tex_core::{Document, Engine, Unit, VerticalItem};
|
||||
|
||||
const PT: i64 = 65_536;
|
||||
|
||||
#[test]
|
||||
fn structural_display_edits_replay_the_preceding_paragraph_dependency() {
|
||||
let style = ParagraphStyle {
|
||||
line_height: 12 * PT,
|
||||
line_width: 200 * PT,
|
||||
..ParagraphStyle::default()
|
||||
};
|
||||
let mut document = Document::new(
|
||||
30 * PT,
|
||||
vec![
|
||||
Unit::paragraph_with_style(1, "Ag", style.clone()),
|
||||
Unit::vskip(2, 15 * PT),
|
||||
Unit::paragraph_with_style(3, "Z", style.clone()),
|
||||
],
|
||||
);
|
||||
document.page_breaks = vec![2];
|
||||
let mut engine = Engine::layout_paged(&document).unwrap();
|
||||
assert_eq!(engine.pages().len(), 2);
|
||||
let old_first = engine.pages()[0].hash;
|
||||
document.units[2] = Unit::math(3, parse_math("x"), &Cmr10Metrics::Math);
|
||||
engine.relayout_from(&document, 2);
|
||||
let full = Engine::layout_paged(&document).unwrap();
|
||||
assert_eq!(engine.pages(), full.pages());
|
||||
assert_ne!(
|
||||
engine.pages()[0].hash,
|
||||
old_first,
|
||||
"display finalizes the preceding paragraph on page one"
|
||||
);
|
||||
document.units[2] = Unit::paragraph_with_style(3, "Z", style);
|
||||
engine.relayout_from(&document, 2);
|
||||
assert_eq!(
|
||||
engine.pages(),
|
||||
Engine::layout_paged(&document).unwrap().pages()
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn paragraph_display_and_resume_baselines_match_tex_vertical_lists() {
|
||||
for (face, tex_font) in [
|
||||
(ParagraphFont::Roman, "cmr10"),
|
||||
(ParagraphFont::TimesRoman, "ptmr8t"),
|
||||
] {
|
||||
for text in ["A", "Ag", "Ag Ag Ag"] {
|
||||
for formula in ["x", r"\frac{x_i^2}{y_j}"] {
|
||||
let dir = std::env::temp_dir().join(format!(
|
||||
"texrra-vlist-{}-{tex_font}-{}-{}",
|
||||
std::process::id(),
|
||||
text.len(),
|
||||
formula.len()
|
||||
));
|
||||
fs::create_dir_all(&dir).unwrap();
|
||||
// Core's prepared math boxes use bp coordinates. Convert the
|
||||
// independent TeX math box at the same boundary before testing
|
||||
// the vlist, keeping this test separate from unit conversion.
|
||||
let source = format!(
|
||||
r"\def\frac#1#2{{{{#1\over#2}}}}\font\body={tex_font} at 10pt
|
||||
\setbox1=\hbox{{$\displaystyle {formula}$}}
|
||||
\ht1=\dimexpr\ht1*800/803\relax
|
||||
\dp1=\dimexpr\dp1*800/803\relax
|
||||
\setbox0=\vbox{{\hsize=30pt\parindent=0pt\baselineskip=12pt\lineskip=1pt\lineskiplimit=0pt
|
||||
\body {text}\par\penalty10000\vskip-2pt\vskip7pt\box1
|
||||
\body Z\par}}
|
||||
\immediate\write16{{VLIST:\number\ht0:\number\dp0}}
|
||||
\bye"
|
||||
);
|
||||
fs::write(dir.join("probe.tex"), source).unwrap();
|
||||
let output = match Command::new("pdftex")
|
||||
.args(["-interaction=nonstopmode", "-halt-on-error", "probe.tex"])
|
||||
.current_dir(&dir)
|
||||
.output()
|
||||
{
|
||||
Ok(output) => output,
|
||||
Err(error) if error.kind() == std::io::ErrorKind::NotFound => {
|
||||
eprintln!("pdftex absent: vlist oracle skipped");
|
||||
return;
|
||||
}
|
||||
Err(error) => panic!("{error}"),
|
||||
};
|
||||
assert!(
|
||||
output.status.success(),
|
||||
"{}",
|
||||
String::from_utf8_lossy(&output.stdout)
|
||||
);
|
||||
let log = String::from_utf8_lossy(&output.stdout);
|
||||
let dimensions: Vec<i64> = log
|
||||
.lines()
|
||||
.find_map(|line| line.strip_prefix("VLIST:"))
|
||||
.unwrap()
|
||||
.split(':')
|
||||
.map(|n| n.parse().unwrap())
|
||||
.collect();
|
||||
let style = ParagraphStyle {
|
||||
line_width: 30 * PT,
|
||||
line_height: 12 * PT,
|
||||
..ParagraphStyle::default()
|
||||
};
|
||||
let before = Unit::paragraph_with_style_and_face(1, text, style.clone(), face);
|
||||
let mut math = Unit::math(2, parse_math(formula), &Cmr10Metrics::Math);
|
||||
math.space_before = 7 * PT;
|
||||
let after = Unit::paragraph_with_style_and_face(3, "Z", style, face);
|
||||
let document = Document::new(
|
||||
500 * PT,
|
||||
vec![before, Unit::vskip(15, -2 * PT), math, after],
|
||||
)
|
||||
.with_top_skip(0);
|
||||
let engine = Engine::layout_paged(&document).unwrap();
|
||||
let list = engine.pages()[0].display_list();
|
||||
let baseline = list
|
||||
.items
|
||||
.iter()
|
||||
.find_map(|item| match item {
|
||||
DisplayItem::Text { text, y, .. } if text == "Z" => Some(*y),
|
||||
_ => None,
|
||||
})
|
||||
.unwrap();
|
||||
assert!(
|
||||
(baseline - dimensions[0]).abs() <= 4,
|
||||
"{tex_font} {text} {formula}: baseline {baseline}, TeX {}",
|
||||
dimensions[0]
|
||||
);
|
||||
fs::remove_dir_all(dir).unwrap();
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn page_glue_setting_moves_the_native_display_with_its_measured_box() {
|
||||
let mut math = Unit::math(2, parse_math("x"), &Cmr10Metrics::Math);
|
||||
math.space_before = 10 * PT;
|
||||
math.space_stretch = 100 * PT;
|
||||
let mut document = Document::new(
|
||||
100 * PT,
|
||||
vec![
|
||||
Unit::rule(1, 100 * PT, 10 * PT),
|
||||
math,
|
||||
Unit::rule(3, 100 * PT, 10 * PT),
|
||||
],
|
||||
)
|
||||
.with_top_skip(0);
|
||||
document.ragged_bottom = false;
|
||||
document.page_breaks = vec![2];
|
||||
let engine = Engine::layout_paged(&document).unwrap();
|
||||
let list = engine.pages()[0].display_list();
|
||||
let baseline = list
|
||||
.items
|
||||
.iter()
|
||||
.find_map(|item| match item {
|
||||
DisplayItem::MathGlyph {
|
||||
character: 'x', y, ..
|
||||
} => Some(*y),
|
||||
_ => None,
|
||||
})
|
||||
.unwrap();
|
||||
assert!(
|
||||
(baseline - 100 * PT).abs() <= 1,
|
||||
"baseline {baseline} did not follow stretched page glue"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn display_paints_the_stored_geometry_without_reinterpreting_the_ast() {
|
||||
let mut unit = Unit::math(1, parse_math(r"\frac{x_i^2}{y_j}"), &Cmr10Metrics::Math);
|
||||
let VerticalItem::Math {
|
||||
atom,
|
||||
geometry,
|
||||
width,
|
||||
height,
|
||||
depth,
|
||||
} = &mut unit.items[0]
|
||||
else {
|
||||
panic!()
|
||||
};
|
||||
let geometry = geometry.as_ref().expect("native fraction");
|
||||
assert!((*width - geometry.metrics.width * 800 / 803).abs() <= 1);
|
||||
assert_eq!(*height, geometry.metrics.height * 800 / 803);
|
||||
assert_eq!(*depth, geometry.metrics.depth * 800 / 803);
|
||||
*atom = MathAtom::Symbol('中'); // The painter must not run layout on this.
|
||||
let engine = Engine::layout(&Document::new(700 * PT, vec![unit]));
|
||||
let list = engine.pages()[0].display_list();
|
||||
assert!(
|
||||
list.items
|
||||
.iter()
|
||||
.any(|i| matches!(i, DisplayItem::MathGlyph { character: 'x', .. }))
|
||||
);
|
||||
assert!(!list.items.iter().any(|i| matches!(
|
||||
i,
|
||||
DisplayItem::MathGlyph {
|
||||
character: '中',
|
||||
..
|
||||
}
|
||||
)));
|
||||
assert!(list.to_svg().contains("data-font=\"CMMI7\""));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn inline_paints_stored_text_style_and_keeps_optical_master_when_scaled() {
|
||||
let mut unit = Unit::paragraph_with_style_and_segments(
|
||||
1,
|
||||
String::new(),
|
||||
ParagraphStyle {
|
||||
line_width: 400 * PT,
|
||||
font_size: 12 * PT,
|
||||
..ParagraphStyle::default()
|
||||
},
|
||||
vec![
|
||||
InlineSegment::Text(ParagraphFont::Roman, "Before ".into()),
|
||||
InlineSegment::Math(parse_math(r"x_i^{N^2}")),
|
||||
],
|
||||
);
|
||||
let VerticalItem::Paragraph(paragraph) = &mut unit.items[0] else {
|
||||
panic!()
|
||||
};
|
||||
let math = paragraph
|
||||
.lines
|
||||
.iter_mut()
|
||||
.flatten()
|
||||
.find_map(|item| match item {
|
||||
HorizontalItem::Box(b) if b.math.is_some() => Some(b),
|
||||
_ => None,
|
||||
})
|
||||
.expect("inline math box");
|
||||
assert!(math.math_geometry.is_some());
|
||||
math.math = Some(Box::new(MathAtom::Symbol('中')));
|
||||
let engine = Engine::layout(&Document::new(700 * PT, vec![unit]));
|
||||
let list = engine.pages()[0].display_list();
|
||||
assert!(list.items.iter().any(|item| matches!(item,
|
||||
DisplayItem::MathGlyph { character: 'i', face: MathFontId(4), size, .. } if *size > 7 * PT)));
|
||||
assert!(list.items.iter().any(|item| matches!(
|
||||
item,
|
||||
DisplayItem::MathGlyph {
|
||||
character: '2',
|
||||
face: MathFontId(2),
|
||||
..
|
||||
}
|
||||
)));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn pdf_uses_both_operator_slots_and_real_optical_programs_with_unicode() {
|
||||
let source = r"\sum_{i=1}^N + {\textstyle\sum_{j=1}^N} + x_{i_j}^{N^2}";
|
||||
let unit = Unit::math(1, parse_math(source), &Cmr10Metrics::Math);
|
||||
let engine = Engine::layout(&Document::new(700 * PT, vec![unit]));
|
||||
let list = engine.pages()[0].display_list();
|
||||
assert!(list.items.iter().any(|i| matches!(
|
||||
i,
|
||||
DisplayItem::MathGlyph {
|
||||
slot: 88,
|
||||
face: MathFontId(9),
|
||||
..
|
||||
}
|
||||
)));
|
||||
assert!(list.items.iter().any(|i| matches!(
|
||||
i,
|
||||
DisplayItem::MathGlyph {
|
||||
slot: 80,
|
||||
face: MathFontId(9),
|
||||
..
|
||||
}
|
||||
)));
|
||||
let pdf =
|
||||
display_lists_to_pdf_with_cm_type1(&[list], 612 * PT, 792 * PT, PageOrigin::default());
|
||||
let text = String::from_utf8_lossy(&pdf);
|
||||
for font in ["CMMI7", "CMMI5", "CMR5", "CMEX10"] {
|
||||
assert!(
|
||||
text.contains(&format!("/BaseFont /{font}")),
|
||||
"missing {font}"
|
||||
);
|
||||
}
|
||||
assert!(text.contains("<50> <2211>"));
|
||||
assert!(text.contains("<58> <2211>"));
|
||||
let dir = std::env::temp_dir().join(format!("texrra-native-math-{}", std::process::id()));
|
||||
fs::create_dir_all(&dir).unwrap();
|
||||
fs::write(dir.join("math.pdf"), pdf).unwrap();
|
||||
match Command::new("pdftotext")
|
||||
.args(["-layout", "math.pdf", "math.txt"])
|
||||
.current_dir(&dir)
|
||||
.output()
|
||||
{
|
||||
Ok(output) => {
|
||||
assert!(
|
||||
output.status.success(),
|
||||
"{}",
|
||||
String::from_utf8_lossy(&output.stderr)
|
||||
);
|
||||
let extracted = fs::read_to_string(dir.join("math.txt")).unwrap();
|
||||
assert!(extracted.matches('∑').count() >= 2, "{extracted}");
|
||||
}
|
||||
Err(error) if error.kind() == std::io::ErrorKind::NotFound => {
|
||||
eprintln!("pdftotext absent; byte-level font checks still ran")
|
||||
}
|
||||
Err(error) => panic!("{error}"),
|
||||
}
|
||||
fs::remove_dir_all(dir).unwrap();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn replayed_math_edit_matches_full_layout() {
|
||||
let unit = Unit::math(1, parse_math(r"\frac{x_i}{y_j}"), &Cmr10Metrics::Math);
|
||||
let mut document = Document::new(700 * PT, vec![unit]);
|
||||
let mut engine = Engine::layout_paged(&document).expect("paged math layout");
|
||||
let before = engine.pages()[0].display_list();
|
||||
engine.relayout_from(&document, 0);
|
||||
assert_eq!(before, engine.pages()[0].display_list());
|
||||
assert!(engine.changed_pages().is_empty());
|
||||
document.units[0] = Unit::math(1, parse_math(r"\frac{z_i^2}{y_j}"), &Cmr10Metrics::Math);
|
||||
engine.relayout_from(&document, 0);
|
||||
let full = Engine::layout_paged(&document).unwrap();
|
||||
assert_eq!(
|
||||
engine.pages()[0].display_list(),
|
||||
full.pages()[0].display_list()
|
||||
);
|
||||
assert!(!engine.changed_pages().is_empty());
|
||||
}
|
||||
|
||||
fn gray_pixels(path: &std::path::Path) -> Vec<u8> {
|
||||
let bytes = fs::read(path).unwrap();
|
||||
let mut at = 0;
|
||||
let mut tokens = Vec::new();
|
||||
while tokens.len() < 4 {
|
||||
while bytes[at].is_ascii_whitespace() {
|
||||
at += 1;
|
||||
}
|
||||
if bytes[at] == b'#' {
|
||||
while bytes[at] != b'\n' {
|
||||
at += 1;
|
||||
}
|
||||
continue;
|
||||
}
|
||||
let start = at;
|
||||
while !bytes[at].is_ascii_whitespace() {
|
||||
at += 1;
|
||||
}
|
||||
tokens.push(std::str::from_utf8(&bytes[start..at]).unwrap().to_owned());
|
||||
}
|
||||
assert_eq!(tokens[0], "P5");
|
||||
assert_eq!(tokens[3], "255");
|
||||
// PGM has a single whitespace separator before its binary pixel stream.
|
||||
at += 1;
|
||||
bytes[at..].to_vec()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn native_math_raster_matches_pdftex_at_the_same_baseline() {
|
||||
// Actual Type1 outlines, spacing, scripts and fractions are compared at a
|
||||
// fixed baseline, independently of Route-D's surrounding paragraph flow.
|
||||
for tool in ["pdftex", "pdftoppm"] {
|
||||
match Command::new(tool).arg("-v").output() {
|
||||
Err(error) if error.kind() == std::io::ErrorKind::NotFound => {
|
||||
eprintln!("{tool} absent; native raster oracle skipped");
|
||||
return;
|
||||
}
|
||||
Err(error) => panic!("{error}"),
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
let arxiv = include_str!("../../../fixtures/arxiv-template/template.tex")
|
||||
.split(r"\begin{equation}")
|
||||
.nth(1)
|
||||
.unwrap()
|
||||
.split(r"\end{equation}")
|
||||
.next()
|
||||
.unwrap()
|
||||
.trim();
|
||||
let cases = [
|
||||
"x_i^2",
|
||||
r"\frac{x_i^2}{y_j}",
|
||||
r"\sum_{i=1}^N",
|
||||
r"\textstyle\sum_{i=1}^N",
|
||||
r"\int\limits_0^1",
|
||||
r"\varOmega^2",
|
||||
arxiv,
|
||||
];
|
||||
let dir =
|
||||
std::env::temp_dir().join(format!("texrra-native-math-raster-{}", std::process::id()));
|
||||
fs::create_dir_all(&dir).unwrap();
|
||||
let mut source = String::from(concat!(
|
||||
"\\pdfpagewidth=612bp \\pdfpageheight=792bp \\pdfhorigin=0pt \\pdfvorigin=0pt\n",
|
||||
"\\def\\frac#1#2{{#1\\over#2}} \\mathchardef\\varOmega=\"010A\n"
|
||||
));
|
||||
let mut pages = Vec::new();
|
||||
for formula in cases {
|
||||
source.push_str(&format!(
|
||||
"\\setbox0=\\hbox{{$\\displaystyle {formula}$}}\n\\shipout\\vbox{{\\kern\\dimexpr100bp-\\ht0\\relax\\hbox{{\\kern72bp\\box0}}}}\n"));
|
||||
let unit = Unit::math(1, parse_math(formula), &Cmr10Metrics::Math);
|
||||
let VerticalItem::Math {
|
||||
height, geometry, ..
|
||||
} = &unit.items[0]
|
||||
else {
|
||||
panic!()
|
||||
};
|
||||
assert!(
|
||||
geometry.is_some(),
|
||||
"formula must use native geometry: {formula}"
|
||||
);
|
||||
let height = *height;
|
||||
let document = Document::new(700 * PT, vec![unit]).with_top_skip(0);
|
||||
let engine = Engine::layout(&document);
|
||||
let mut list = engine.pages()[0].display_list();
|
||||
list.place(72 * PT, 100 * PT - height);
|
||||
list.width = 612 * PT;
|
||||
list.height = 792 * PT;
|
||||
pages.push(list);
|
||||
}
|
||||
source.push_str("\\bye\n");
|
||||
fs::write(dir.join("reference.tex"), source).unwrap();
|
||||
fs::write(
|
||||
dir.join("native.pdf"),
|
||||
display_lists_to_pdf_with_cm_type1(&pages, 612 * PT, 792 * PT, PageOrigin::default()),
|
||||
)
|
||||
.unwrap();
|
||||
let output = Command::new("pdftex")
|
||||
.args([
|
||||
"-interaction=nonstopmode",
|
||||
"-halt-on-error",
|
||||
"reference.tex",
|
||||
])
|
||||
.current_dir(&dir)
|
||||
.output()
|
||||
.unwrap();
|
||||
assert!(
|
||||
output.status.success(),
|
||||
"{}",
|
||||
String::from_utf8_lossy(&output.stdout)
|
||||
);
|
||||
for name in ["reference", "native"] {
|
||||
let output = Command::new("pdftoppm")
|
||||
.args(["-r", "144", "-gray", &format!("{name}.pdf"), name])
|
||||
.current_dir(&dir)
|
||||
.output()
|
||||
.unwrap();
|
||||
assert!(
|
||||
output.status.success(),
|
||||
"{}",
|
||||
String::from_utf8_lossy(&output.stderr)
|
||||
);
|
||||
}
|
||||
for (index, formula) in cases.iter().enumerate() {
|
||||
let page = index + 1;
|
||||
let expected = gray_pixels(&dir.join(format!("reference-{page}.pgm")));
|
||||
let actual = gray_pixels(&dir.join(format!("native-{page}.pgm")));
|
||||
assert_eq!(expected.len(), actual.len());
|
||||
let width = 1224usize;
|
||||
let bbox = |pixels: &[u8]| {
|
||||
let mut box_ = [usize::MAX, usize::MAX, 0, 0];
|
||||
for (i, pixel) in pixels.iter().enumerate().filter(|(_, value)| **value < 128) {
|
||||
let _ = pixel;
|
||||
box_[0] = box_[0].min(i % width);
|
||||
box_[1] = box_[1].min(i / width);
|
||||
box_[2] = box_[2].max(i % width);
|
||||
box_[3] = box_[3].max(i / width);
|
||||
}
|
||||
box_
|
||||
};
|
||||
let a = bbox(&actual);
|
||||
let e = bbox(&expected);
|
||||
for axis in 0..4 {
|
||||
assert!(
|
||||
a[axis].abs_diff(e[axis]) <= 1,
|
||||
"{formula}: native bbox {a:?}, pdfTeX bbox {e:?}; artifacts {}",
|
||||
dir.display()
|
||||
);
|
||||
}
|
||||
let ink = expected.iter().filter(|value| **value < 128).count();
|
||||
let different = expected
|
||||
.iter()
|
||||
.zip(&actual)
|
||||
.filter(|(a, b)| (**a < 128) != (**b < 128))
|
||||
.count();
|
||||
eprintln!("page {page}: bbox {a:?} vs {e:?}, {different}/{ink} ink pixels differ");
|
||||
assert!(
|
||||
different as f64 / (ink as f64) < 0.02,
|
||||
"{formula}: {different}/{ink} ink pixels differ; artifacts {}",
|
||||
dir.display()
|
||||
);
|
||||
}
|
||||
if std::env::var_os("TEXRRA_KEEP_MATH_ARTIFACTS").is_some() {
|
||||
eprintln!("native math raster artifacts: {}", dir.display());
|
||||
} else {
|
||||
fs::remove_dir_all(dir).unwrap();
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user