Files
texrra-engine/crates/texrra-tex-core/tests/virtual_fonts.rs
T

259 lines
9.1 KiB
Rust

use std::{
fs,
path::{Path, PathBuf},
process::Command,
};
use texrra_tex_core::{
execution::*,
native_font::resolve_native_fonts,
pdf,
provenance::Derivation,
render::DisplayItem,
resources::{FileWorld, LoadedResource, ResourceKind, SearchPath, WorldConfig},
source_map::SourceMap,
};
struct Host(FileWorld);
impl SourceProvider for Host {
fn default_pk_resolution(&mut self) -> Result<i32, String> {
Ok(self.0.default_pk_resolution())
}
fn read(&mut self, name: &str, from: &str) -> Result<SourceFile, String> {
NoFiles.read(name, from)
}
fn virtual_font(&mut self, name: &str, from: &str) -> Result<Option<LoadedResource>, String> {
self.0
.read_optional(ResourceKind::Vf, name, Path::new(from))
}
fn resource(
&mut self,
kind: ResourceKind,
name: &str,
from: &str,
) -> Result<LoadedResource, String> {
self.0.read(kind, name, Path::new(from))
}
}
fn kpse(argument: &str) -> PathBuf {
let output = Command::new("kpsewhich").arg(argument).output().unwrap();
assert!(output.status.success(), "{argument}");
PathBuf::from(String::from_utf8(output.stdout).unwrap().trim())
}
fn fixture(label: &str) -> (PathBuf, Host) {
let root = std::env::temp_dir().join(format!("texrra-vf-{label}-{}", std::process::id()));
fs::create_dir(&root).unwrap();
let roots = vec![kpse("--var-value=TEXMFDIST"), kpse("--var-value=TEXMFVAR")];
let mut world = WorldConfig::from_environment(&root, roots).unwrap();
world.texmf_roots.sort();
let map = kpse("pdftex.map");
world.paths.insert(
ResourceKind::Map,
vec![SearchPath::directory(map.parent().unwrap(), false)],
);
(root, Host(FileWorld::new(world).unwrap()))
}
fn source(font: &str, text: &str) -> Vec<u8> {
format!(
concat!(
"\\catcode123=1\\catcode125=2\n",
"\\pdfoutput=1\\pdfcompresslevel=0\\pdfobjcompresslevel=0\n",
"\\pdfpagewidth=70pt\\pdfpageheight=30pt\\pdfhorigin=5pt\\pdfvorigin=5pt\n",
"\\font\\paint={} at 12pt \\paint\n",
"\\setbox0=\\hbox{{{}}}\\shipout\\box0\\end\n",
),
font, text
)
.into_bytes()
}
fn execute(root: &Path, contents: &[u8], host: &mut Host) -> RevisionExecution {
let state = State::initex().with_etex();
let execution = Executor::new(state, Limits::default())
.with_native_pages()
.run(
SourceFile {
name: root.join("probe.tex").to_string_lossy().into_owned(),
data: contents.to_vec(),
},
host,
)
.unwrap();
RevisionExecution::from_execution(1, execution, None)
}
fn reference(root: &Path, contents: &[u8]) {
fs::write(root.join("probe.tex"), contents).unwrap();
let run = Command::new("pdftex")
.current_dir(root)
.env_remove("TEXINPUTS")
.args([
"-ini",
"-etex",
"-no-shell-escape",
"-halt-on-error",
"-interaction=nonstopmode",
"-recorder",
"probe.tex",
])
.output()
.unwrap();
fs::write(root.join("pdftex.stdout"), &run.stdout).unwrap();
fs::write(root.join("pdftex.stderr"), &run.stderr).unwrap();
assert!(
run.status.success(),
"{}",
String::from_utf8_lossy(&run.stdout)
);
}
fn raster(root: &Path, filename: &str, label: &str) -> Vec<u8> {
let run = Command::new("pdftoppm")
.current_dir(root)
.args(["-r", "144", "-gray", filename, label])
.output()
.unwrap();
assert!(
run.status.success(),
"{}",
String::from_utf8_lossy(&run.stderr)
);
fs::read(root.join(format!("{label}-1.pgm"))).unwrap()
}
fn render(root: &Path, execution: &Execution, pages: &[texrra_tex_core::render::DisplayList]) {
let document =
pdf::shipout_lists_to_native_pdf_document(pages, execution.state.pdf_final_options())
.unwrap();
fs::write(root.join("native.pdf"), document.bytes).unwrap();
fs::write(root.join("native.svg"), pages[0].try_to_svg().unwrap()).unwrap();
assert!(
raster(root, "native.pdf", "native") == raster(root, "probe.pdf", "reference"),
"native and pdfTeX raster evidence in {}",
root.display()
);
}
#[test]
fn actual_times_virtual_small_caps_use_scaled_local_type1_and_source_origins() {
let (root, mut host) = fixture("times");
let bytes = source("ptmrc7t", "aB");
reference(&root, &bytes);
let revision = execute(&root, &bytes, &mut host);
let mut pages = revision.execution.shipout_display_lists().unwrap();
let before = SourceMap::from_revision(&revision, &pages).unwrap();
assert!(pages[0].items.iter().any(|item| {
matches!(item, DisplayItem::NativeGlyph { font, .. } if font.name == "ptmrc7t")
}));
resolve_native_fonts(&mut pages, &mut host).unwrap();
let glyphs: Vec<_> = pages[0]
.items
.iter()
.filter_map(|item| match item {
DisplayItem::NativeGlyph {
font,
size,
slot,
paint: Some(paint),
..
} => Some((font.name.as_str(), *size, *slot, paint.program.name())),
_ => None,
})
.collect();
assert_eq!(glyphs.len(), 2);
assert!(
glyphs
.iter()
.all(|g| g.0 == "ptmr8r" && g.3 == "NimbusRomNo9L-Regu")
);
assert_eq!([glyphs[0].2, glyphs[1].2], [b'A', b'B']);
assert!(glyphs[0].1 < glyphs[1].1);
let after = SourceMap::from_revision(&revision, &pages).unwrap();
assert_eq!(before.pages[0].entries.len(), after.pages[0].entries.len());
for (old, new) in before.pages[0].entries.iter().zip(&after.pages[0].entries) {
assert_eq!(old.source.tokens, new.source.tokens);
assert!(new.source.derivations.contains(&Derivation::FontProgram));
assert_ne!(old.kind, new.kind);
}
let reads = &host.0.trace().reads;
for name in ["ptmrc7t.vf", "ptmr8r.tfm", "8r.enc", "utmr8a.pfb"] {
assert!(reads.iter().any(|r| r.path.ends_with(name)), "{name}");
}
render(&root, &revision.execution, &pages);
}
fn tfm_width(tfm: &[u8], slot: u8) -> [u8; 4] {
let field = |index: usize| {
u16::from_be_bytes(tfm[2 * index..2 * index + 2].try_into().unwrap()) as usize
};
let first = field(2);
let info = (6 + field(1)) * 4;
let widths = info + (field(3) - first + 1) * 4;
let index = usize::from(tfm[info + (usize::from(slot) - first) * 4]);
tfm[widths + 4 * index..widths + 4 * index + 4]
.try_into()
.unwrap()
}
fn virtual_program(tfm: &[u8], local: &str, commands: &[u8]) -> Vec<u8> {
let mut vf = vec![247, 202, 0];
vf.extend(&tfm[24..32]); // TFM checksum and design size.
vf.extend([243, 0]); // Define local font zero at the full parent size.
vf.extend(&tfm[24..28]);
vf.extend(1_048_576i32.to_be_bytes());
vf.extend(&tfm[28..32]);
vf.extend([0, local.len() as u8]);
vf.extend(local.as_bytes());
vf.extend([commands.len() as u8, b'A']);
vf.extend(&tfm_width(tfm, b'A')[1..]);
vf.extend(commands);
vf.push(248);
vf
}
#[test]
fn nested_vf_preserves_pen_position_rules_and_one_to_many_origin() {
let (root, mut host) = fixture("nested");
let tfm = fs::read(kpse("cmr10.tfm")).unwrap();
for name in ["vfouter", "vfinner"] {
fs::write(root.join(format!("{name}.tfm")), &tfm).unwrap();
}
let mut commands = vec![141, b'B', 160];
commands.extend(131_072i32.to_be_bytes()); // Down 1/8 of the virtual font size.
commands.push(137); // A rule at the current pen without advancing.
commands.extend(65_536i32.to_be_bytes());
commands.extend(262_144i32.to_be_bytes());
commands.extend([142, 133, b'C']); // Restore both axes and put C.
let inner = virtual_program(&tfm, "cmr10", &commands);
fs::write(root.join("vfinner.vf"), inner).unwrap();
fs::write(
root.join("vfouter.vf"),
virtual_program(&tfm, "vfinner", &[b'A']),
)
.unwrap();
let bytes = source("vfouter", "A");
reference(&root, &bytes);
let revision = execute(&root, &bytes, &mut host);
let mut pages = revision.execution.shipout_display_lists().unwrap();
let before = SourceMap::from_revision(&revision, &pages).unwrap();
resolve_native_fonts(&mut pages, &mut host).unwrap();
let after = SourceMap::from_revision(&revision, &pages).unwrap();
let origin = &before.pages[0].entries[0].source.tokens;
assert_eq!(after.pages[0].entries.len(), 3);
assert!(
after.pages[0]
.entries
.iter()
.all(|p| &p.source.tokens == origin)
);
assert!(matches!(pages[0].items.as_slice(), [
DisplayItem::NativeGlyph { slot: b'B', x, y, font, .. },
DisplayItem::Rule { x: rule_x, y: rule_y, width, height },
DisplayItem::NativeGlyph { slot: b'C', x: c_x, y: c_y, .. },
] if *c_x == *x && *c_y == *y && *rule_x == *x + font.metrics.width('B')
&& *rule_y == *y + 49_152 && *width == 196_608 && *height == 49_152));
render(&root, &revision.execution, &pages);
}