Advance native LaTeX execution and preview

This commit is contained in:
gloamxun committed 2026-11-18 22:17:21 +08:00
1 parent 91f9d76b16
commit 2741546ca8
414 files changed
+99872 -933

No files matched your search

@@ -0,0 +1,175 @@
use serde_json::{Value, json};
use std::{fs, path::Path, process::Command};
use texrra_tex_core::{
execution::{Event, Execution, NativeShipout},
math_engine_tex::MathItem,
};
pub(super) fn compare_shipout(case: &Path, native: Execution) -> Result<Value, String> {
let mut pages = compare_shipouts(case, &native)?;
if pages.len() != 1 {
return Err(format!("expected one shipout, found {}", pages.len()));
}
Ok(pages.pop().unwrap())
}
pub(super) fn compare_shipouts(case: &Path, native: &Execution) -> Result<Vec<Value>, String> {
let output = Command::new("python3")
.arg(Path::new(env!("CARGO_MANIFEST_DIR")).join("../../scripts/native-math-dvi-oracle.py"))
.arg(case.join("probe.dvi"))
.output()
.map_err(|error| error.to_string())?;
if !output.status.success() {
return Err(String::from_utf8_lossy(&output.stderr).into_owned());
}
let pages: Vec<Value> = serde_json::from_slice(&output.stdout).unwrap();
let ships: Vec<_> = native
.events
.iter()
.filter_map(|event| match event {
Event::Shipout(ship) => Some(ship),
_ => None,
})
.collect();
if pages.len() != ships.len() {
return Err(format!(
"reference ships {}, native ships {}",
pages.len(),
ships.len()
));
}
let label = case.file_name().unwrap().to_str().unwrap();
pages
.iter()
.zip(ships)
.enumerate()
.map(|(i, (page, ship))| {
if pages.len() == 1 {
compare_page(case, label, page, ship)
} else {
let path = case.join(format!("page-{}", i + 1));
fs::create_dir_all(&path).map_err(|error| error.to_string())?;
compare_page(&path, label, page, ship)
}
})
.collect()
}
fn compare_page(
case: &Path,
label: &str,
page: &Value,
ship: &NativeShipout,
) -> Result<Value, String> {
let geometry = ship.box_node.geometry()?;
let height = geometry.metrics.height;
let mut found = Vec::new();
for paint in geometry.items {
let x = paint.x;
let y = paint.y + height;
match paint.item {
MathItem::NativeGlyph {
font, size, slot, ..
} => {
found.push(json!({"font": font.name, "size": size, "slot": slot, "x": x, "y": y}));
}
MathItem::Rule { width, height } => {
found.push(json!({"width": width, "height": height, "x": x, "y": y}));
}
_ => return Err("unexpected non-native paint item".into()),
}
}
let expected: Vec<_> = page["paint_order"]
.as_array()
.unwrap()
.iter()
.map(|order| {
let kind = order[0].as_str().unwrap();
let index = order[1].as_u64().unwrap() as usize;
let mut item = page[if kind == "glyph" { "glyphs" } else { "rules" }][index].clone();
item.as_object_mut().unwrap().remove("advance");
item
})
.collect();
fs::write(
case.join("native-paint.json"),
serde_json::to_vec_pretty(&found).unwrap(),
)
.unwrap();
fs::write(
case.join("reference-paint.json"),
serde_json::to_vec_pretty(&expected).unwrap(),
)
.unwrap();
if found.len() != expected.len() {
return Err(format!(
"reference items {}, native items {}",
expected.len(),
found.len()
));
}
let mut max_error = 0;
for (index, (mut actual, mut reference)) in found.into_iter().zip(expected).enumerate() {
for axis in ["x", "y"] {
let a = actual
.as_object_mut()
.unwrap()
.remove(axis)
.unwrap()
.as_i64()
.unwrap();
let b = reference
.as_object_mut()
.unwrap()
.remove(axis)
.unwrap()
.as_i64()
.unwrap();
max_error = max_error.max((a - b).abs());
}
if actual != reference {
return Err(format!(
"paint item {index}: {actual} differs from {reference}"
));
}
}
if max_error > 1 {
return Err(format!("paint geometry differs by {max_error} sp"));
}
Ok(
json!({"case": label, "glyphs": page["glyphs"].as_array().unwrap().len(),
"rules": page["rules"].as_array().unwrap().len(), "ordered": true, "max_coordinate_error_sp": max_error}),
)
}
pub(super) fn run_reference(case: &Path, source: &str, invalid: bool) -> String {
run_reference_with_showboxes(case, source, usize::from(!invalid))
}
pub(super) fn run_reference_with_showboxes(case: &Path, source: &str, shows: usize) -> String {
let invalid = shows == 0;
fs::create_dir_all(case).unwrap();
fs::write(case.join("probe.tex"), source).unwrap();
let mut pdftex = Command::new("pdftex");
pdftex.current_dir(case).env_remove("TEXINPUTS").args([
"-ini",
"-etex",
"-interaction=nonstopmode",
"-no-shell-escape",
]);
if invalid {
pdftex.arg("-halt-on-error");
}
let reference = pdftex.arg("probe.tex").output().unwrap();
assert_eq!(reference.status.code(), Some(1), "{case:?}");
let log = fs::read_to_string(case.join("probe.log")).unwrap();
let errors: Vec<_> = log.lines().filter(|line| line.starts_with('!')).collect();
if invalid {
assert!(errors.iter().any(|error| *error != "! OK."), "{case:?}");
assert!(!case.join("probe.dvi").exists(), "{case:?}");
} else {
assert_eq!(errors, vec!["! OK."; shows], "{case:?}");
assert!(case.join("probe.dvi").is_file(), "{case:?}");
}
log
}
@@ -0,0 +1,151 @@
//! Explicit physical font world for native executor tests. NoFiles in the
//! library remains strict and has no binary resource fallback.
use std::path::{Path, PathBuf};
use texrra_tex_core::{
execution::{NoFiles, SourceFile, SourceProvider},
resources::{FileWorld, LoadedResource, ResourceKind, SearchPath, WorldConfig},
};
#[allow(dead_code)]
#[derive(Default)]
pub struct FontFiles;
pub fn resource(kind: ResourceKind, name: &str, from: &str) -> Result<LoadedResource, String> {
let root = PathBuf::from(env!("CARGO_MANIFEST_DIR"));
let mut config = WorldConfig::new(&root);
config.paths.insert(
ResourceKind::Tfm,
vec![SearchPath::directory(root.join("assets"), false)],
);
config.paths.insert(
ResourceKind::Type1,
vec![SearchPath::directory(
root.join("../../assets/fonts"),
false,
)],
);
if kind == ResourceKind::Map {
let r = std::process::Command::new("kpsewhich")
.arg(name)
.output()
.map_err(|e| e.to_string())?;
if !r.status.success() {
return Err("test font map is unavailable".into());
}
let path = PathBuf::from(
String::from_utf8(r.stdout)
.map_err(|e| e.to_string())?
.trim(),
);
config.paths.insert(
kind,
vec![SearchPath::directory(
path.parent().ok_or("test map parent")?,
false,
)],
);
}
FileWorld::new(config)?.read(kind, name, Path::new(from))
}
impl SourceProvider for FontFiles {
fn default_pk_resolution(&mut self) -> Result<i32, String> {
Ok(WorldConfig::new(env!("CARGO_MANIFEST_DIR")).default_pk_resolution)
}
fn read(&mut self, name: &str, from: &str) -> Result<SourceFile, String> {
NoFiles.read(name, from)
}
fn resource(&mut self, k: ResourceKind, n: &str, f: &str) -> Result<LoadedResource, String> {
resource(k, n, f)
}
}
#[allow(unused_macros)]
macro_rules! font_resources {
() => {
fn resource(
&mut self,
k: texrra_tex_core::resources::ResourceKind,
n: &str,
f: &str,
) -> Result<texrra_tex_core::resources::LoadedResource, String> {
font_world::resource(k, n, f)
}
};
}
#[allow(unused_imports)]
pub(crate) use font_resources;
/// Inspect the actual retained math box, including its shift on the hlist.
/// Independent DVI oracles must not silently ignore newly owned sub-boxes.
#[allow(dead_code)]
pub fn math_geometry(
b: &texrra_tex_core::HorizontalBox,
) -> Option<texrra_tex_core::math_engine_tex::MathGeometry> {
if let Some(child) = &b.native_box {
let mut g = child.geometry().expect("actual native math box geometry");
for item in &mut g.items {
item.y += child.shift;
}
Some(g)
} else {
b.math_geometry.as_deref().cloned()
}
}
/// Extract labels only after the actual output encoding has been resolved.
/// TFM-only character nodes deliberately retain raw slots, not guessed Unicode.
#[allow(dead_code)]
pub fn painted_text(items: &[texrra_tex_core::HorizontalItem]) -> String {
use texrra_tex_core::{
HorizontalItem,
math_engine_tex::MathItem,
render::{DisplayItem, DisplayList},
};
fn append(items: &[HorizontalItem], out: &mut Vec<DisplayItem>) {
for item in items {
if let HorizontalItem::Box(b) = item {
if let Some(native) = &b.native_box {
if let Some(children) = native.horizontal_items() {
append(&children, out);
}
} else if let Some(g) = &b.math_geometry {
for p in &g.items {
match &p.item {
MathItem::NativeGlyph {
font,
slot,
character,
size,
} => out.push(DisplayItem::NativeGlyph {
x: 0,
y: 0,
size: *size,
font: font.clone(),
slot: *slot,
character: *character,
paint: None,
}),
MathItem::Rule { .. } => {}
MathItem::Glyph { .. } => panic!("legacy font in native test material"),
MathItem::PdfImage(_) => panic!("PDF image in a DVI fixture"),
}
}
}
}
}
}
let mut list = DisplayList::default();
append(items, &mut list.items);
texrra_tex_core::native_font::resolve_native_fonts(
std::slice::from_mut(&mut list),
&mut FontFiles,
)
.unwrap();
list.items
.iter()
.filter_map(|i| {
if let DisplayItem::NativeGlyph { character, .. } = i {
Some(*character)
} else {
None
}
})
.collect()
}
@@ -0,0 +1,89 @@
//! Independent real binary TFM fixture builder shared by text/math oracles.
use std::collections::BTreeMap;
#[derive(Clone, Copy)]
pub enum Op {
Lig(u8, u8),
Kern(i32),
}
pub fn font(programs: &[(Option<u8>, u8, Op)], boundary: Option<u8>) -> Vec<u8> {
let mut groups: BTreeMap<Option<u8>, Vec<(u8, Op)>> = BTreeMap::new();
for (left, right, op) in programs {
groups.entry(*left).or_default().push((*right, *op));
}
let mut instructions = Vec::<[u8; 4]>::new();
if let Some(b) = boundary {
instructions.push([255, b, 0, 0]);
}
let mut labels = BTreeMap::new();
let mut kerns = Vec::new();
for (left, commands) in groups {
labels.insert(left, instructions.len());
for (index, (right, op)) in commands.iter().enumerate() {
let (code, rem) = match op {
Op::Lig(code, rem) => (*code, *rem),
Op::Kern(n) => {
let i = kerns.len();
kerns.push(*n);
(128 + (i / 256) as u8, i as u8)
}
};
instructions.push([
if index + 1 == commands.len() { 128 } else { 0 },
*right,
code,
rem,
]);
}
}
if let Some(label) = labels.get(&None) {
instructions.push([255, 0, (label / 256) as u8, *label as u8]);
}
let mut bytes = Vec::new();
let (lh, bc, ec, nw, nh, nd, ni, nl, nk, ne, np) = (
2,
65,
90,
27,
2,
2,
1,
instructions.len(),
kerns.len(),
0,
7,
);
let lf = 6 + lh + (ec - bc + 1) + nw + nh + nd + ni + nl + nk + ne + np;
for n in [lf, lh, bc, ec, nw, nh, nd, ni, nl, nk, ne, np] {
bytes.extend_from_slice(&(n as u16).to_be_bytes());
}
bytes.extend_from_slice(&0x10203040u32.to_be_bytes());
bytes.extend_from_slice(&(10i32 << 20).to_be_bytes());
for slot in bc..=ec {
let label = labels.get(&Some(slot as u8));
bytes.extend_from_slice(&[
(slot - bc + 1) as u8,
0x11,
if label.is_some() { 1 } else { 0 },
label.copied().unwrap_or(0) as u8,
]);
}
let mut table = vec![0];
table.extend((1..=26).map(|i| (1 << 18) + i * 1111));
table.extend([0, 734003, 0, 209715, 0]);
table.extend(kerns);
// Width/height/depth/italic are before the lig/kern instruction table.
for n in &table[..32] {
bytes.extend_from_slice(&i32::to_be_bytes(*n));
}
for i in instructions {
bytes.extend_from_slice(&i);
}
for n in &table[32..] {
bytes.extend_from_slice(&i32::to_be_bytes(*n));
}
for n in [0, 1 << 18, 1 << 17, 1 << 16, 1 << 19, 1 << 20, 1 << 17] {
bytes.extend_from_slice(&i32::to_be_bytes(n));
}
assert_eq!(bytes.len(), lf * 4);
bytes
}