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 { Ok(self.0.default_pk_resolution()) } fn read(&mut self, name: &str, from: &str) -> Result { NoFiles.read(name, from) } fn virtual_font(&mut self, name: &str, from: &str) -> Result, String> { self.0 .read_optional(ResourceKind::Vf, name, Path::new(from)) } fn resource( &mut self, kind: ResourceKind, name: &str, from: &str, ) -> Result { 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 { 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 { 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); } #[test] fn letterspacing_uses_fresh_widths_and_the_selected_fonts_live_quad() { let (root, mut host) = fixture("letterspacing"); let bytes = br"\catcode123=1 \catcode125=2 \pdfoutput=1 \pdfcompresslevel=0 \pdfobjcompresslevel=0 \pdfpagewidth=90pt \pdfpageheight=65pt \pdfhorigin=5pt \pdfvorigin=5pt \font\base=ptmrc7t at 12pt \fontdimen6\base=20pt \letterspacefont\spaced=\base 100 \letterspacefont\tight=\base -137 nolig \message{[\number\fontdimen6\base,\number\fontdimen6\spaced,\number\fontcharwd\spaced 65,\number\fontcharwd\tight 65]} \shipout\vbox{\hbox{\spaced aB AV fi}\kern5pt\hbox{\tight aB AV fi}}\end"; reference(&root, bytes); let revision = execute(&root, bytes, &mut host); assert!(revision.execution.events.iter().any(|event| { matches!(event, Event::Message { text, .. } if text == "[1310720,786432,685766,499382]") })); let mut pages = revision.execution.shipout_display_lists().unwrap(); for (name, has_kern) in [("ptmrc7t+100ls", true), ("ptmrc7t-137ls", false)] { let font = pages[0] .items .iter() .find_map(|item| match item { DisplayItem::NativeGlyph { font, .. } if font.name == name => Some(font), _ => None, }) .unwrap(); assert_eq!( font.metrics().lig_kern(Some(b'A'), b'V').is_some(), has_kern ); } resolve_native_fonts(&mut pages, &mut host).unwrap(); let map = SourceMap::from_revision(&revision, &pages).unwrap(); assert!( map.pages[0] .entries .iter() .any(|entry| { entry.source.derivations.contains(&Derivation::FontProgram) }) ); assert!( host.0 .trace() .reads .iter() .any(|r| r.path.ends_with("utmr8a.pfb")) ); 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 { 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); } #[test] fn autoexpanded_virtual_shipout_allocates_job_fonts_before_following_commands() { const SOURCE: &str = r"\catcode123=1 \catcode125=2 \pdfoutput=1 \pdfpkresolution=600 \font\virtual=ptmr7t \pdffontexpand\virtual 75 75 25 autoexpand \pdfadjustspacing=1 \parfillskip=0pt \hsize=31pt \setbox0=\vbox{\virtual \noindent AAAA\par} \font\sentinel=cmr10 \fontdimen8\sentinel=1pt \shipout\copy0 \end "; let (root, mut host) = fixture("job-font-ids"); let revision = execute(&root, SOURCE.as_bytes(), &mut host); let fonts = revision.execution.state.fonts(); let names: Vec<_> = fonts.fonts().iter().map(FontInstance::name).collect(); assert_eq!( names, ["nullfont", "ptmr7t", "ptmr7t+75", "ptmr7t-75", "cmr10", "ptmr8r", "ptmr8r+75", "ptmr8r-75", "ptmr8r+75"], ); let source = SOURCE.replace(r"\end", r"\fontdimen9\sentinel=2pt \end"); let run = |bytes: &str, host: &mut Host| { Executor::new(State::initex().with_etex(), Limits::default()) .with_native_pages() .run( SourceFile { name: root.join("probe.tex").to_string_lossy().into_owned(), data: bytes.as_bytes().to_vec() }, host, ) }; assert!( run(&source, &mut host) .unwrap_err() .message.contains("only the last loaded font can extend fontdimen") ); let control = source.replace(r"\shipout\copy0", ""); assert_eq!(run(&control, &mut host).unwrap().state.fonts().fonts().len(), 5); } #[test] fn inherited_virtual_limits_replace_one_bound_and_keep_allocated_slots() { let (root, mut host) = fixture("inherited-limits"); let bytes = br"\catcode123=1 \catcode125=2 \pdfoutput=1 \pdfpkresolution=600 \font\local=ptmr8r \pdffontexpand\local 50 50 25 autoexpand \font\virtual=ptmr7t \pdffontexpand\virtual 75 0 25 autoexpand \pdfadjustspacing=1 \parfillskip=0pt \hsize=31pt \setbox0=\vbox{\virtual \noindent AAAA\par} \shipout\box0 \pdffontexpand\local 75 50 25 autoexpand \shipout\vbox{\hsize=27.4pt \local \noindent AAAA\par} \end "; let revision = execute(&root, bytes, &mut host); assert_eq!( revision.execution.state.fonts().fonts().iter().map(FontInstance::name).collect::>(), ["nullfont", "ptmr8r", "ptmr8r+50", "ptmr8r-50", "ptmr7t", "ptmr7t+75", "ptmr8r+75", "ptmr8r+75"], ); let pages = revision.execution.shipout_display_lists().unwrap(); assert_eq!(pages.len(), 2); assert_eq!( pages[1].items.iter().filter(|item| { matches!(item, DisplayItem::NativeGlyph { font, .. } if font.name == "ptmr8r" && font.expansion == -50) }).count(), 4, ); }