527 lines
18 KiB
Rust
527 lines
18 KiB
Rust
//! Actual dynamic fonts, PDF embedding and late resource I/O through the CLI.
|
|
#[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-dynamic-{}-{}",
|
|
std::process::id(),
|
|
N.fetch_add(1, Ordering::Relaxed)
|
|
));
|
|
fs::create_dir_all(&p).unwrap();
|
|
p
|
|
}
|
|
#[test]
|
|
fn mathematical_font_descriptors_widths_and_word_positions_match_real_pdftex() {
|
|
let p = directory();
|
|
let root = PathBuf::from(env!("CARGO_MANIFEST_DIR"));
|
|
let fixture = root.join("examples/native-bootstrap/math-operators.tex");
|
|
let before = fs::read(&fixture).unwrap();
|
|
let output = native_fonts::command()
|
|
.args(["native", "--initex", "--etex"])
|
|
.arg(&fixture)
|
|
.arg("native.pdf")
|
|
.current_dir(&p)
|
|
.output()
|
|
.unwrap();
|
|
assert!(
|
|
output.status.success(),
|
|
"{}",
|
|
String::from_utf8_lossy(&output.stderr)
|
|
);
|
|
fs::write(p.join("reference.tex"),format!(r"\pdfoutput=1\pdfobjcompresslevel=0\pdfpagewidth=612bp\pdfpageheight=792bp\vsize=648bp\topskip=10bp\input {}",fixture.display())).unwrap();
|
|
let output = Command::new("pdftex")
|
|
.args([
|
|
"-ini",
|
|
"-etex",
|
|
"-interaction=nonstopmode",
|
|
"-halt-on-error",
|
|
"reference.tex",
|
|
])
|
|
.env(
|
|
"TEXINPUTS",
|
|
format!("{}:", fixture.parent().unwrap().display()),
|
|
)
|
|
.current_dir(&p)
|
|
.output()
|
|
.unwrap();
|
|
assert!(
|
|
output.status.success(),
|
|
"{}",
|
|
String::from_utf8_lossy(&output.stdout)
|
|
);
|
|
let script = r#"
|
|
import re,subprocess,xml.etree.ElementTree as ET
|
|
from pathlib import Path
|
|
def inspect(name):
|
|
data=Path(name).read_bytes()
|
|
objects={int(m[1]):m[2]for m in re.finditer(rb'(?ms)(\d+) 0 obj\s*(.*?)\s*endobj',data)}
|
|
metrics={};widths={}
|
|
for body in objects.values():
|
|
if re.search(rb'/Type\s*/FontDescriptor\b',body):
|
|
font=re.search(rb'/FontName\s*/([^\s/]+)',body)[1].decode().split('+')[-1]
|
|
metrics[font]=[int(re.search(rb'/'+key+rb'\s+(-?\d+)',body)[1])for key in [b'Ascent',b'Descent',b'CapHeight',b'XHeight']]
|
|
if re.search(rb'/Subtype\s*/Type1\b',body):
|
|
font=re.search(rb'/BaseFont\s*/([^\s/]+)',body)[1].decode().split('+')[-1]
|
|
first=int(re.search(rb'/FirstChar\s+(\d+)',body)[1])
|
|
inline=re.search(rb'/Widths\s*\[([^]]*)\]',body)
|
|
if inline: values=inline[1]
|
|
else: values=objects[int(re.search(rb'/Widths\s+(\d+) 0 R',body)[1])].strip()[1:-1]
|
|
widths[font]=(first,[float(n)for n in values.split()])
|
|
words=[(w.text,{k:float(v)for k,v in w.attrib.items()})for w in ET.fromstring(subprocess.check_output(['pdftotext','-bbox',name,'-'])).iter()if w.tag.endswith('}word')]
|
|
return metrics,widths,words
|
|
a,b=inspect('native.pdf'),inspect('reference.pdf')
|
|
assert 'CMEX10' in a[0]
|
|
assert a[0]==b[0],(a[0],b[0])
|
|
assert a[1]==b[1],(a[1],b[1])
|
|
assert [w[0]for w in a[2]]==[w[0]for w in b[2]]
|
|
error=max(abs(x[1][k]-y[1][k])for x,y in zip(a[2],b[2])for k in x[1])
|
|
assert error<=0.02,error
|
|
print(len(a[2]),'actual words, exact font descriptors/widths, maximum bbox error:',error)
|
|
"#;
|
|
let output = Command::new("python3")
|
|
.args(["-c", script])
|
|
.current_dir(&p)
|
|
.output()
|
|
.unwrap();
|
|
assert!(
|
|
output.status.success(),
|
|
"{}\n{}\n{p:?}",
|
|
String::from_utf8_lossy(&output.stdout),
|
|
String::from_utf8_lossy(&output.stderr)
|
|
);
|
|
assert_eq!(fs::read(fixture).unwrap(), before);
|
|
fs::remove_dir_all(p).unwrap();
|
|
}
|
|
#[test]
|
|
fn requested_resources_sizes_and_font_programs_reach_the_actual_pdf() {
|
|
let p = directory();
|
|
let source = include_bytes!("../examples/native-bootstrap/dynamic-fonts.tex");
|
|
fs::write(p.join("probe.tex"), source).unwrap();
|
|
let r = native_fonts::command()
|
|
.args([
|
|
"native",
|
|
"--initex",
|
|
"--etex",
|
|
"--resource-manifest",
|
|
"resources.json",
|
|
"probe.tex",
|
|
"native.pdf",
|
|
])
|
|
.current_dir(&p)
|
|
.output()
|
|
.unwrap();
|
|
assert!(r.status.success(), "{}", String::from_utf8_lossy(&r.stderr));
|
|
assert_eq!(fs::read(p.join("probe.tex")).unwrap(), source);
|
|
let fonts = Command::new("pdffonts")
|
|
.arg(p.join("native.pdf"))
|
|
.output()
|
|
.unwrap();
|
|
assert!(fonts.status.success());
|
|
let fonts = String::from_utf8(fonts.stdout).unwrap();
|
|
for name in ["CMR10", "CMR7", "CMBX10", "CMTI10", "CMTT10", "CMSS10"] {
|
|
assert!(
|
|
fonts
|
|
.lines()
|
|
.any(|l| l.starts_with(name) && l.contains("Type 1") && l.contains("yes")),
|
|
"{fonts}"
|
|
);
|
|
}
|
|
let trace: serde_json::Value =
|
|
serde_json::from_slice(&fs::read(p.join("resources.json")).unwrap()).unwrap();
|
|
for stem in ["cmr10", "cmr7", "cmbx10", "cmti10", "cmtt10", "cmss10"] {
|
|
for ext in ["tfm", "pfb"] {
|
|
assert!(
|
|
trace["reads"].as_array().unwrap().iter().any(|r| r["path"]
|
|
.as_str()
|
|
.unwrap()
|
|
.ends_with(&format!("/{stem}.{ext}"))),
|
|
"missing actual {stem}.{ext}: {trace}"
|
|
);
|
|
}
|
|
}
|
|
assert!(
|
|
trace["reads"]
|
|
.as_array()
|
|
.unwrap()
|
|
.iter()
|
|
.any(|r| r["path"].as_str().unwrap().ends_with("/pdftex.map"))
|
|
);
|
|
let text = Command::new("pdftotext")
|
|
.args([p.join("native.pdf").to_str().unwrap(), "-"])
|
|
.output()
|
|
.unwrap();
|
|
assert!(text.status.success());
|
|
let text = String::from_utf8(text.stdout).unwrap();
|
|
for s in [
|
|
"Real native fonts",
|
|
"bold text",
|
|
"italic text",
|
|
"mono text",
|
|
"sans text",
|
|
"without replacement",
|
|
] {
|
|
assert!(text.contains(s), "{text}");
|
|
}
|
|
fs::remove_dir_all(p).unwrap();
|
|
}
|
|
#[test]
|
|
fn tfm_only_measurement_needs_no_outline_and_missing_output_resources_protect_pdf() {
|
|
let p = directory();
|
|
let empty = p.join("empty");
|
|
fs::create_dir(&empty).unwrap();
|
|
fs::write(p.join("measure.tex"),br"\catcode123=1\catcode125=2\font\F=cmr10 at12pt\setbox0=\hbox{\F AV}\message{WIDTH=\number\wd0}\end").unwrap();
|
|
let r = native_fonts::command()
|
|
.env("T1FONTS", &empty)
|
|
.env("TEXFONTMAPS", &empty)
|
|
.args([
|
|
"native",
|
|
"--initex",
|
|
"--etex",
|
|
"--resource-manifest",
|
|
"measure.json",
|
|
"measure.tex",
|
|
"measure.pdf",
|
|
])
|
|
.current_dir(&p)
|
|
.output()
|
|
.unwrap();
|
|
assert!(r.status.success(), "{}", String::from_utf8_lossy(&r.stderr));
|
|
assert!(!p.join("measure.pdf").exists());
|
|
let trace: serde_json::Value =
|
|
serde_json::from_slice(&fs::read(p.join("measure.json")).unwrap()).unwrap();
|
|
assert!(
|
|
trace["reads"].as_array().unwrap().iter().all(|r| !r["path"]
|
|
.as_str()
|
|
.unwrap()
|
|
.ends_with(".pfb")
|
|
&& !r["path"].as_str().unwrap().ends_with(".map"))
|
|
);
|
|
fs::write(p.join("draw.tex"),br"\catcode123=1\catcode125=2\font\F=cmr10 at12pt\F\hsize=100pt\baselineskip=12pt\parfillskip=0pt plus1fil AV\par\end").unwrap();
|
|
fs::write(p.join("keep.pdf"), b"KEEP").unwrap();
|
|
let r = native_fonts::command()
|
|
.env("T1FONTS", &empty)
|
|
.args([
|
|
"native",
|
|
"--initex",
|
|
"--etex",
|
|
"--resource-manifest",
|
|
"missing.json",
|
|
"draw.tex",
|
|
"keep.pdf",
|
|
])
|
|
.current_dir(&p)
|
|
.output()
|
|
.unwrap();
|
|
assert!(!r.status.success());
|
|
assert!(
|
|
String::from_utf8_lossy(&r.stderr).contains("cmr10.pfb"),
|
|
"{}",
|
|
String::from_utf8_lossy(&r.stderr)
|
|
);
|
|
assert_eq!(fs::read(p.join("keep.pdf")).unwrap(), b"KEEP");
|
|
let trace: serde_json::Value =
|
|
serde_json::from_slice(&fs::read(p.join("missing.json")).unwrap()).unwrap();
|
|
assert!(trace["lookups"].as_array().unwrap().iter().any(|r| {
|
|
r["kind"] == "Type1"
|
|
&& r["name"] == "cmr10.pfb"
|
|
&& r["resolved"].is_null()
|
|
&& r["candidates"]
|
|
.as_array()
|
|
.is_some_and(|c| c.contains(&serde_json::json!(empty.join("cmr10.pfb"))))
|
|
}));
|
|
assert!(
|
|
!trace["reads"]
|
|
.as_array()
|
|
.unwrap()
|
|
.iter()
|
|
.any(|r| r["path"].as_str().is_some_and(|p| p.ends_with("cmr10.pfb")))
|
|
);
|
|
fs::remove_dir_all(p).unwrap();
|
|
}
|
|
|
|
fn raster(path: &std::path::Path, base: &std::path::Path) -> (usize, usize, Vec<u8>) {
|
|
let r = Command::new("pdftoppm")
|
|
.args(["-singlefile", "-gray", "-r", "144"])
|
|
.arg(path)
|
|
.arg(base)
|
|
.output()
|
|
.unwrap();
|
|
assert!(r.status.success(), "{}", String::from_utf8_lossy(&r.stderr));
|
|
let bytes = fs::read(base.with_extension("pgm")).unwrap();
|
|
let (mut at, mut fields) = (0, Vec::new());
|
|
for _ in 0..4 {
|
|
while bytes[at].is_ascii_whitespace() {
|
|
at += 1;
|
|
}
|
|
let start = at;
|
|
while !bytes[at].is_ascii_whitespace() {
|
|
at += 1;
|
|
}
|
|
fields.push(std::str::from_utf8(&bytes[start..at]).unwrap());
|
|
}
|
|
assert_eq!(fields[0], "P5");
|
|
assert_eq!(fields[3], "255");
|
|
let w = fields[1].parse::<usize>().unwrap();
|
|
let h = fields[2].parse::<usize>().unwrap();
|
|
at += 1;
|
|
let pixels = bytes[at..].to_vec();
|
|
assert_eq!(pixels.len(), w * h);
|
|
(w, h, pixels)
|
|
}
|
|
#[test]
|
|
fn external_encoding_and_map_syntax_use_actual_program_glyphs_like_pdftex() {
|
|
let p = directory();
|
|
let root = PathBuf::from(env!("CARGO_MANIFEST_DIR"));
|
|
fs::copy(
|
|
root.join("crates/texrra-tex-core/assets/cmr10.tfm"),
|
|
p.join("fancy.tfm"),
|
|
)
|
|
.unwrap();
|
|
fs::copy(root.join("assets/fonts/cmr10.pfb"), p.join("cmr10.pfb")).unwrap();
|
|
let mut encoding = vec![".notdef"; 256];
|
|
encoding[65] = "W";
|
|
encoding[86] = "V";
|
|
fs::write(
|
|
p.join("custom.enc"),
|
|
format!(
|
|
"/NativeEncoding [\n{}\n] def\n",
|
|
encoding
|
|
.iter()
|
|
.map(|n| format!("/{n}"))
|
|
.collect::<Vec<_>>()
|
|
.join(" ")
|
|
),
|
|
)
|
|
.unwrap();
|
|
let source = format!(
|
|
r"\catcode123=1\catcode125=2\font\F={}/fancy at12pt\F\hsize=100pt\parindent=0pt\baselineskip=12pt\parfillskip=0pt plus1fil AV AV\par\end",
|
|
p.display()
|
|
);
|
|
fs::write(p.join("native.tex"), &source).unwrap();
|
|
fs::write(
|
|
p.join("reference.tex"),
|
|
format!(
|
|
r"\pdfoutput=1\pdfpagewidth=612bp\pdfpageheight=792bp\vsize=648bp\topskip=10bp {source}"
|
|
),
|
|
)
|
|
.unwrap();
|
|
for (spec, reencoded) in [
|
|
(
|
|
r#"" NativeEncoding ReEncodeFont " <custom.enc <cmr10.pfb"#,
|
|
true,
|
|
),
|
|
(
|
|
r#"" DifferentName ReEncodeFont " <custom.enc <cmr10.pfb"#,
|
|
true,
|
|
),
|
|
("<[custom.enc <cmr10.pfb", true),
|
|
(r#"" ReEncodeFont " <custom.enc <cmr10.pfb"#, true),
|
|
(r#"" ignoredword " <custom.enc <cmr10.pfb"#, true),
|
|
(r#"" DifferentName ReEncodeFont " <cmr10.pfb"#, false),
|
|
] {
|
|
fs::write(p.join("pdftex.map"), format!("fancy CMR10 {spec}\n")).unwrap();
|
|
let r = native_fonts::command()
|
|
.env("TEXFONTMAPS", &p)
|
|
.env("T1FONTS", &p)
|
|
.args([
|
|
"native",
|
|
"--initex",
|
|
"--etex",
|
|
"--resource-manifest",
|
|
"trace.json",
|
|
"native.tex",
|
|
"native.pdf",
|
|
])
|
|
.current_dir(&p)
|
|
.output()
|
|
.unwrap();
|
|
assert!(
|
|
r.status.success(),
|
|
"{spec}\n{}",
|
|
String::from_utf8_lossy(&r.stderr)
|
|
);
|
|
let r = Command::new("pdftex")
|
|
.env("TEXFONTMAPS", &p)
|
|
.env("T1FONTS", &p)
|
|
.args([
|
|
"-ini",
|
|
"-etex",
|
|
"-interaction=nonstopmode",
|
|
"-halt-on-error",
|
|
"reference.tex",
|
|
])
|
|
.current_dir(&p)
|
|
.output()
|
|
.unwrap();
|
|
assert!(r.status.success(), "{}", String::from_utf8_lossy(&r.stdout));
|
|
let a = raster(&p.join("native.pdf"), &p.join("native-ink"));
|
|
let b = raster(&p.join("reference.pdf"), &p.join("reference-ink"));
|
|
assert_eq!((a.0, a.1), (b.0, b.1));
|
|
let w = a.0 as isize;
|
|
for (x, y) in [(&a.2, &b.2), (&b.2, &a.2)] {
|
|
let unmatched = x
|
|
.iter()
|
|
.enumerate()
|
|
.filter(|(i, v)| {
|
|
**v < 200
|
|
&& !(-1..=1).any(|dy| {
|
|
(-1..=1).any(|dx| {
|
|
y.get((*i as isize + dy * w + dx) as usize)
|
|
.is_some_and(|p| *p < 200)
|
|
})
|
|
})
|
|
})
|
|
.count();
|
|
assert_eq!(unmatched, 0, "{spec}");
|
|
}
|
|
let texts: [String; 2] = ["native.pdf", "reference.pdf"].map(|name| {
|
|
let r = Command::new("pdftotext")
|
|
.arg(p.join(name))
|
|
.arg("-")
|
|
.output()
|
|
.unwrap();
|
|
assert!(r.status.success());
|
|
String::from_utf8(r.stdout).unwrap()
|
|
});
|
|
assert_eq!(texts[0], texts[1], "{spec}");
|
|
assert!(texts[0].contains(if reencoded { "WV WV" } else { "AV AV" }));
|
|
let trace: serde_json::Value =
|
|
serde_json::from_slice(&fs::read(p.join("trace.json")).unwrap()).unwrap();
|
|
assert_eq!(
|
|
trace["reads"]
|
|
.as_array()
|
|
.unwrap()
|
|
.iter()
|
|
.any(|r| r["path"].as_str().unwrap().ends_with("/custom.enc")),
|
|
reencoded
|
|
);
|
|
}
|
|
// A mapped name which has no actual CharString must fail, not paint blank.
|
|
encoding[65] = "MissingGlyphProgram";
|
|
fs::write(
|
|
p.join("custom.enc"),
|
|
format!(
|
|
"/NativeEncoding [{}] def",
|
|
encoding
|
|
.iter()
|
|
.map(|n| format!("/{n}"))
|
|
.collect::<Vec<_>>()
|
|
.join(" ")
|
|
),
|
|
)
|
|
.unwrap();
|
|
fs::write(p.join("pdftex.map"), "fancy CMR10 <custom.enc <cmr10.pfb\n").unwrap();
|
|
fs::write(p.join("native.pdf"), b"PRESERVE").unwrap();
|
|
let r = native_fonts::command()
|
|
.env("TEXFONTMAPS", &p)
|
|
.env("T1FONTS", &p)
|
|
.args(["native", "--initex", "native.tex", "native.pdf"])
|
|
.current_dir(&p)
|
|
.output()
|
|
.unwrap();
|
|
assert!(!r.status.success());
|
|
assert!(String::from_utf8_lossy(&r.stderr).contains("MissingGlyphProgram"));
|
|
assert_eq!(fs::read(p.join("native.pdf")).unwrap(), b"PRESERVE");
|
|
fs::remove_dir_all(p).unwrap();
|
|
}
|
|
|
|
#[test]
|
|
fn only_selected_discretionary_material_requests_its_actual_font_program() {
|
|
let p = directory();
|
|
let root = PathBuf::from(env!("CARGO_MANIFEST_DIR"));
|
|
let fonts = p.join("fonts");
|
|
fs::create_dir(&fonts).unwrap();
|
|
fs::copy(root.join("assets/fonts/cmr10.pfb"), fonts.join("cmr10.pfb")).unwrap();
|
|
let source = |penalty: i32| {
|
|
format!(
|
|
r"\catcode123=1\catcode125=2\font\body=cmr10\font\alt=cmss10 at12pt\body\hsize=100pt\baselineskip=15pt\rightskip=0pt plus1fil\parfillskip=0pt plus1fil\pretolerance=10000\hyphenpenalty={penalty} A\discretionary{{\alt P}}{{\alt Q}}{{R}}B\par\end"
|
|
)
|
|
};
|
|
let run = |stem: &str| {
|
|
native_fonts::command()
|
|
.env("T1FONTS", &fonts)
|
|
.args([
|
|
"native",
|
|
"--initex",
|
|
"--etex",
|
|
"--resource-manifest",
|
|
&format!("{stem}.json"),
|
|
&format!("{stem}.tex"),
|
|
&format!("{stem}.pdf"),
|
|
])
|
|
.current_dir(&p)
|
|
.output()
|
|
.unwrap()
|
|
};
|
|
let text = |stem: &str| {
|
|
let r = Command::new("pdftotext")
|
|
.args(["-layout"])
|
|
.arg(p.join(format!("{stem}.pdf")))
|
|
.arg("-")
|
|
.output()
|
|
.unwrap();
|
|
assert!(r.status.success());
|
|
String::from_utf8(r.stdout).unwrap()
|
|
};
|
|
fs::write(p.join("unbroken.tex"), source(10000)).unwrap();
|
|
let r = run("unbroken");
|
|
assert!(r.status.success(), "{}", String::from_utf8_lossy(&r.stderr));
|
|
assert!(text("unbroken").contains("ARB"));
|
|
let trace: serde_json::Value =
|
|
serde_json::from_slice(&fs::read(p.join("unbroken.json")).unwrap()).unwrap();
|
|
assert!(
|
|
trace["reads"]
|
|
.as_array()
|
|
.unwrap()
|
|
.iter()
|
|
.any(|r| r["path"].as_str().unwrap().ends_with("cmss10.tfm"))
|
|
);
|
|
assert!(
|
|
!trace["lookups"]
|
|
.as_array()
|
|
.unwrap()
|
|
.iter()
|
|
.any(|r| r["name"] == "cmss10.pfb"),
|
|
"unselected alternatives must not read outlines"
|
|
);
|
|
fs::write(p.join("broken.tex"), source(-10000)).unwrap();
|
|
fs::write(p.join("broken.pdf"), b"KEEP").unwrap();
|
|
let r = run("broken");
|
|
assert!(!r.status.success());
|
|
assert!(String::from_utf8_lossy(&r.stderr).contains("cmss10.pfb"));
|
|
assert_eq!(fs::read(p.join("broken.pdf")).unwrap(), b"KEEP");
|
|
fs::copy(
|
|
root.join("assets/fonts/cmss10.pfb"),
|
|
fonts.join("cmss10.pfb"),
|
|
)
|
|
.unwrap();
|
|
let r = run("broken");
|
|
assert!(r.status.success(), "{}", String::from_utf8_lossy(&r.stderr));
|
|
let printed = text("broken");
|
|
assert!(
|
|
printed.contains("AP") && printed.contains("QB") && !printed.contains('R'),
|
|
"{printed}"
|
|
);
|
|
let trace: serde_json::Value =
|
|
serde_json::from_slice(&fs::read(p.join("broken.json")).unwrap()).unwrap();
|
|
assert!(
|
|
trace["reads"]
|
|
.as_array()
|
|
.unwrap()
|
|
.iter()
|
|
.any(|r| r["path"].as_str().unwrap().ends_with("cmss10.pfb"))
|
|
);
|
|
assert_eq!(
|
|
fs::read_to_string(p.join("broken.tex")).unwrap(),
|
|
source(-10000)
|
|
);
|
|
fs::remove_dir_all(p).unwrap();
|
|
}
|