//! Actual online native jobs: output/shipout, auxiliary files and strict errors. #[path = "support/native_fonts.rs"] mod native_fonts; use std::{ fs, path::PathBuf, process::Command, sync::atomic::{AtomicU64, Ordering}, }; fn directory() -> PathBuf { static N: AtomicU64 = AtomicU64::new(0); let p = std::env::temp_dir().join(format!( "texrra-native-pages-{}-{}", std::process::id(), N.fetch_add(1, Ordering::Relaxed) )); fs::create_dir_all(&p).unwrap(); p } #[test] fn native_job_exports_only_actual_shipouts_with_real_fonts_and_auxiliary_bytes() { let p = directory(); let root = PathBuf::from(env!("CARGO_MANIFEST_DIR")); let source = root.join("examples/native-bootstrap/native-job.tex"); let before = fs::read(&source).unwrap(); let r = native_fonts::command() .args([ "native", "--job", "--initex", "--etex", "--resource-manifest", "resources.json", ]) .arg(&source) .arg("native.pdf") .current_dir(&p) .output() .unwrap(); assert!( r.status.success(), "{p:?}: {}", String::from_utf8_lossy(&r.stderr) ); let r = Command::new("pdfinfo") .arg("native.pdf") .current_dir(&p) .output() .unwrap(); assert!(r.status.success()); assert!( String::from_utf8_lossy(&r.stdout) .lines() .any(|s| s.starts_with("Pages:") && s.ends_with('4')) ); assert_eq!( fs::read(p.join("pages.aux")).unwrap(), b"FIRST-PAGE=1\nLAST-PAGE=4\n" ); let r = Command::new("pdftotext") .args(["-layout", "native.pdf", "-"]) .current_dir(&p) .output() .unwrap(); assert!(r.status.success()); let text = String::from_utf8(r.stdout).unwrap(); for page in 1..=4 { assert!( text.contains(&format!("Native page {page}")) && text.contains(&format!("Footer {page}")), "{text}" ); } let r = Command::new("pdffonts") .arg("native.pdf") .current_dir(&p) .output() .unwrap(); assert!(r.status.success()); for font in ["CMR10", "CMMI10", "CMMI7"] { assert!(String::from_utf8_lossy(&r.stdout).contains(font)); } let trace: serde_json::Value = serde_json::from_slice(&fs::read(p.join("resources.json")).unwrap()).unwrap(); for suffix in [ "native-job.tex", "math-fonts.tex", "cmr10.tfm", "cmmi7.tfm", "cmr10.pfb", "cmmi7.pfb", ] { assert!( trace["reads"] .as_array() .unwrap() .iter() .any(|r| r["path"].as_str().unwrap().ends_with(suffix)), "missing actual read {suffix}" ); } assert_eq!(fs::read(source).unwrap(), before); fs::remove_dir_all(p).unwrap(); } #[test] fn native_job_errors_keep_existing_pdf_and_source_intact() { let p = directory(); for (body, expected) in [ ( r"\setbox255=\hbox{}\hbox{}\penalty-10000\end", "box255 is not void", ), ( r"\output{\relax}\hbox{}\penalty-10000\end", "did not empty box255", ), ( r"\maxdeadcycles=2\output{\unvbox255}\hbox{}\penalty-10000\end", "dead cycles", ), ( r"\output{\bad}\hbox{}\penalty-10000\end", "undefined native control sequence", ), (r"\hbox{}", "end"), ( r"\documentclass{article}\end", "undefined native control sequence", ), ] { let source = format!("\\catcode123=1\\catcode125=2\n{body}\n"); fs::write(p.join("probe.tex"), &source).unwrap(); fs::write(p.join("native.pdf"), b"KEEP").unwrap(); let r = native_fonts::command() .args([ "native", "--job", "--initex", "--etex", "probe.tex", "native.pdf", ]) .current_dir(&p) .output() .unwrap(); assert_eq!(r.status.code(), Some(1), "{body}"); assert!( String::from_utf8_lossy(&r.stderr).contains(expected), "{body}: {}", String::from_utf8_lossy(&r.stderr) ); assert_eq!(fs::read(p.join("native.pdf")).unwrap(), b"KEEP"); assert_eq!(fs::read_to_string(p.join("probe.tex")).unwrap(), source); } fs::remove_dir_all(p).unwrap(); } #[test] fn initex_page_parameters_are_not_seeded_from_the_pdf_driver() { let p = directory(); let source = r"\catcode123=1\catcode125=2\message{INITEX-VSIZE=\number\vsize;TOP=\number\topskip;DEPTH=\number\maxdepth}\shipout\hbox{}\end"; fs::write(p.join("probe.tex"), source).unwrap(); let r = native_fonts::command() .args([ "native", "--job", "--initex", "--etex", "probe.tex", "native.pdf", ]) .current_dir(&p) .output() .unwrap(); assert!(r.status.success(), "{}", String::from_utf8_lossy(&r.stderr)); let log = fs::read_to_string(p.join("native.log")).unwrap(); assert!(log.contains("INITEX-VSIZE=0;TOP=0;DEPTH=0"), "{log}"); assert!( fs::read(p.join("native.pdf")) .unwrap() .starts_with(b"%PDF-") ); fs::remove_dir_all(p).unwrap(); } #[test] fn saved_pdf_position_is_observed_in_shipout_order() { let work = directory(); let source = r"\catcode123=1 \catcode125=2 \pdfoutput=1 \pdfpageheight=100pt \pdfhorigin=10pt \pdfvorigin=12pt \immediate\openout5=positions.dat \setbox5=\hbox{\kern32pt\pdfsavepos} \immediate\write5{\the\pdflastxpos,\the\pdflastypos} \shipout\hbox to40pt{\vrule width8pt height9pt \hskip 2pt plus1fil \pdfsavepos\write5{\the\pdflastxpos,\the\pdflastypos} \hbox{\kern3pt\pdfsavepos\write5{\the\pdflastxpos,\the\pdflastypos}} \kern7pt} \immediate\write5{\the\pdflastxpos,\the\pdflastypos} \immediate\closeout5 \end"; fs::write(work.join("probe.tex"), source).unwrap(); let output = native_fonts::command() .args([ "native", "--job", "--initex", "--etex", "probe.tex", "native.pdf", ]) .current_dir(&work) .output() .unwrap(); assert!( output.status.success(), "{}", String::from_utf8_lossy(&output.stderr) ); let native = fs::read(work.join("positions.dat")).unwrap(); let output = Command::new("pdftex") .args([ "-ini", "-etex", "-interaction=nonstopmode", "-halt-on-error", "probe.tex", ]) .current_dir(&work) .output() .unwrap(); assert!( output.status.success(), "{}", String::from_utf8_lossy(&output.stdout) ); assert_eq!(native, fs::read(work.join("positions.dat")).unwrap()); assert_eq!( native, b"0,0\n2621440,5177344\n2818048,5177344\n2818048,5177344\n" ); fs::remove_dir_all(work).unwrap(); } #[test] fn native_pdf_text_uses_the_rounded_origin_after_positioned_literals() { let work = directory(); let source = work.join("origin.tex"); fs::write( &source, r"\catcode123=1 \catcode125=2 \catcode35=6 \catcode37=14 \pdfoutput=1 \pdfdecimaldigits=3 \pdfpagewidth=200pt \pdfpageheight=200pt \pdfhorigin=0sp \pdfvorigin=0sp \font\body=cmr10 \body \def\place#1#2#3{\hbox to0sp{\kern#1sp\lower#2sp\hbox{#3}\hss}} \shipout\hbox{% \place{66}{13107134}{\pdfliteral{q Q}}% \place{330}{13106870}{\pdfliteral{q Q}}% \place{33}{13107134}{A}} \end", ) .unwrap(); let result = native_fonts::command() .args(["native", "--job", "--initex", "--etex"]) .arg(&source) .arg("origin.pdf") .current_dir(&work) .output() .unwrap(); assert!( result.status.success(), "{}", String::from_utf8_lossy(&result.stderr) ); let pdf = lopdf::Document::load(work.join("origin.pdf")).unwrap(); let contents = pdf.get_page_content(pdf.get_pages()[&1]).unwrap(); let stream = lopdf::content::Content::decode(&contents).unwrap(); let mut moves = stream.operations.iter().filter(|op| op.operator == "Td"); let start = moves.next().expect("first glyph position"); // The two literals leave 1 sp of residue on each axis after moving // back. pdfTeX 1.40.29 emits 0 0 Td for the first glyph. assert!(matches!( start.operands.as_slice(), [x, y] if [x, y].iter().all(|axis| matches!( axis, lopdf::Object::Integer(0) | lopdf::Object::Real(0.0) )) ), "{start:?}"); assert!(moves.next().is_none()); fs::remove_dir_all(work).unwrap(); } #[test] fn pdftex_origin_uses_the_two_axis_threshold_for_literals_and_rules() { let work = directory(); let source = work.join("origin.tex"); fs::write( &source, r"\catcode123=1 \catcode125=2 \catcode35=6 \catcode37=14 \pdfoutput=1 \pdfdecimaldigits=3 \pdfpagewidth=200pt \pdfpageheight=200pt \pdfhorigin=0sp \pdfvorigin=0sp \def\place#1#2#3{\hbox to0sp{\kern#1sp\lower#2sp\hbox{#3}\hss}} \shipout\hbox{% \place{33}{13107200}{\pdfliteral{1 1 m 40 1 l S}}% \place{33}{13107528}{\vrule width20pt height655sp depth0sp}% \place{66}{13107167}{\pdfliteral{1 2 m 40 2 l S}}% \place{0}{13107200}{\pdfliteral{1 3 m 40 3 l S}}} \end", ) .unwrap(); let result = native_fonts::command() .args(["native", "--job", "--initex", "--etex"]) .arg(&source) .arg("origin.pdf") .current_dir(&work) .output() .unwrap(); assert!( result.status.success(), "{}", String::from_utf8_lossy(&result.stderr) ); let pdf = lopdf::Document::load(work.join("origin.pdf")).unwrap(); let contents = pdf.get_page_content(pdf.get_pages()[&1]).unwrap(); let stream = lopdf::content::Content::decode(&contents).unwrap(); let ordered: Vec<_> = stream.operations.iter() .filter(|op| matches!(op.operator.as_str(), "cm" | "S")) .collect(); let operators: Vec<_> = ordered.iter().map(|op| op.operator.as_str()).collect(); assert_eq!(operators, ["S", "S", "cm", "S", "cm", "S"]); assert!(matches!( &ordered[2].operands[4..], [lopdf::Object::Real(0.001), lopdf::Object::Real(0.001)] )); assert!(matches!( &ordered[4].operands[4..], [lopdf::Object::Real(-0.001), lopdf::Object::Real(-0.001)] )); fs::remove_dir_all(work).unwrap(); } #[test] fn shipped_pdf_spaces_take_a_real_font_slot_in_output_order() { let work = directory(); let space_tfm = Command::new("kpsewhich") .arg("pdftexspace.tfm") .output() .unwrap(); assert!(space_tfm.status.success()); let space_tfm = String::from_utf8(space_tfm.stdout).unwrap(); let assets = PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("crates/texrra-tex-core/assets"); let tfm_paths = std::env::join_paths([ assets.as_path(), std::path::Path::new(space_tfm.trim()).parent().unwrap(), ]) .unwrap(); for (name, movement, succeeds) in [ ("short", r"\kern1pt", true), ("automatic", r"\kern5pt", false), ("explicit", r"\pdffakespace", false), ] { let path = work.join(format!("{name}.tex")); let source = format!( r"\catcode123=1 \catcode125=2 \pdfoutput=1 \font\roman=cmr10 \shipout\hbox{{\pdfinterwordspaceon\roman A% \write16{{BEFORE=\the\fontdimen8\roman}}{movement} B% \write16{{AFTER=\the\fontdimen9\roman}}}} \end" ); fs::write(&path, source).unwrap(); let pdf = work.join(format!("{name}.pdf")); let output = native_fonts::command() .args(["native", "--job", "--initex", "--etex"]) .env("TFMFONTS", &tfm_paths) .arg(&path) .arg(&pdf) .current_dir(&work) .output() .unwrap(); let terminal = String::from_utf8_lossy(&output.stdout); let error = String::from_utf8_lossy(&output.stderr); assert_eq!(output.status.success(), succeeds, "{name}: {terminal}\n{error}"); let log = fs::read_to_string(pdf.with_extension("log")).unwrap(); assert!(log.lines().any(|line| line == "BEFORE=0.0pt"), "{log}"); if succeeds { assert!(log.lines().any(|line| line == "AFTER=0.0pt"), "{log}"); assert!(fs::read(&pdf).unwrap().starts_with(b"%PDF-")); } else { assert!(error.contains("font has 8 parameters"), "{name}: {error}"); assert!(!pdf.exists(), "{name}: incomplete job published a PDF"); } } fs::remove_dir_all(work).unwrap(); } #[test] fn unicode_job_shapes_file_font_and_exports_the_actual_glyphs() { let p = directory(); let face = PathBuf::from(env!("CARGO_MANIFEST_DIR")) .join("vendor/printpdf/assets/fonts/RobotoMedium.ttf"); fs::copy(face, p.join("actual.ttf")).unwrap(); fs::write( p.join("probe.tex"), r#"\catcode123=1 \catcode125=2 \pdfcompresslevel=0 \pdfobjcompresslevel=0 \font\body="[actual.ttf]" at 10pt \shipout\hbox{\body AV office naïve} \end"#, ) .unwrap(); let result = Command::new(env!("CARGO_BIN_EXE_texrra")) .args([ "native", "--job", "--initex", "--etex", "--input-profile", "unicode", "--input-policy", "project", "--layout-manifest", "layout.json", "probe.tex", "native.pdf", ]) .env("TEXRRA_STATE_DIR", p.join("state")) .current_dir(&p) .output() .unwrap(); assert!(result.status.success(), "{}", String::from_utf8_lossy(&result.stderr)); let layout: serde_json::Value = serde_json::from_slice(&fs::read(p.join("layout.json")).unwrap()).unwrap(); let glyphs = layout["pages"][0]["glyphs"].as_array().unwrap(); let text: String = glyphs.iter().map(|glyph| glyph["text"].as_str().unwrap()).collect(); assert_eq!(text, "AVofficenaïve"); assert!(glyphs.iter().any(|glyph| glyph["text"] == "fi" && glyph["glyph"] == 420)); assert!(glyphs.iter().all(|glyph| glyph["resource"]["path"].as_str().unwrap().ends_with("actual.ttf"))); let map = layout["source_map"]["pages"][0]["entries"].as_array().unwrap(); assert_eq!(map.len(), glyphs.len()); let pdf = fs::read(p.join("native.pdf")).unwrap(); let pdf = String::from_utf8_lossy(&pdf); assert!(pdf.contains("/Subtype /CIDFontType2")); assert!(pdf.contains("/FontFile2")); assert!(pdf.contains("/ToUnicode")); fs::remove_dir_all(p).unwrap(); }