Advance native LaTeX execution and preview
This commit is contained in:
1 parent
91f9d76b16
commit
2741546ca8
414 files changed
+99872
-933
No files matched your search
@@ -0,0 +1,378 @@
|
||||
//! Compare actual final Type1 CMaps and extracted bytes against pdfTeX.
|
||||
#[path = "support/font_world.rs"]
|
||||
mod font_world;
|
||||
use std::{collections::BTreeMap, fs, path::Path, process::Command};
|
||||
use texrra_tex_core::execution::*;
|
||||
const HEADER: &str =
|
||||
r"\catcode123=1\catcode125=2\catcode35=6\pdfoutput=1\pdfcompresslevel=0\font\f=cmr10\f ";
|
||||
fn source(text: &str) -> SourceFile {
|
||||
SourceFile {
|
||||
name: "probe.tex".into(),
|
||||
data: text.as_bytes().to_vec(),
|
||||
}
|
||||
}
|
||||
fn native(text: &str) -> Execution {
|
||||
Executor::new(
|
||||
State::initex().with_etex().with_pdf_output(),
|
||||
Limits::default(),
|
||||
)
|
||||
.with_native_pages()
|
||||
.run(source(text), &mut font_world::FontFiles)
|
||||
.unwrap()
|
||||
}
|
||||
fn pdf(e: &Execution) -> Vec<u8> {
|
||||
let mut pages = e.shipout_display_lists().unwrap();
|
||||
texrra_tex_core::native_font::resolve_native_fonts(&mut pages, &mut font_world::FontFiles)
|
||||
.unwrap();
|
||||
texrra_tex_core::pdf::shipout_lists_to_native_pdf(&pages, e.state.pdf_final_options()).unwrap()
|
||||
}
|
||||
fn directory(label: &str) -> std::path::PathBuf {
|
||||
let p = std::env::temp_dir().join(format!("texrra-pdf-unicode-{}-{label}", std::process::id()));
|
||||
fs::create_dir_all(&p).unwrap();
|
||||
p
|
||||
}
|
||||
fn reference(p: &Path, text: &str) -> std::process::Output {
|
||||
fs::write(p.join("probe.tex"), text).unwrap();
|
||||
Command::new("pdftex")
|
||||
.args([
|
||||
"-ini",
|
||||
"-etex",
|
||||
"-interaction=nonstopmode",
|
||||
"-halt-on-error",
|
||||
"probe.tex",
|
||||
])
|
||||
.current_dir(p)
|
||||
.output()
|
||||
.unwrap()
|
||||
}
|
||||
fn extracted(p: &Path, name: &str) -> Vec<u8> {
|
||||
let r = Command::new("pdftotext")
|
||||
.args(["-raw", name, "-"])
|
||||
.current_dir(p)
|
||||
.output()
|
||||
.unwrap();
|
||||
assert!(r.status.success(), "{}", String::from_utf8_lossy(&r.stderr));
|
||||
r.stdout
|
||||
}
|
||||
// Both writers emit scalar bfrange and explicit bfchar records. Read the full
|
||||
// streams, including unused slots and explicit malformed UTF-16 hex strings.
|
||||
fn cmaps(pdf: &[u8]) -> Vec<BTreeMap<u8, String>> {
|
||||
let text = String::from_utf8_lossy(pdf);
|
||||
text.split("begincmap")
|
||||
.skip(1)
|
||||
.map(|s| {
|
||||
let tokens: Vec<_> = s
|
||||
.split("endcmap")
|
||||
.next()
|
||||
.unwrap()
|
||||
.split_whitespace()
|
||||
.collect();
|
||||
let mut map = BTreeMap::new();
|
||||
let hex = |s: &str| {
|
||||
s.strip_prefix('<')
|
||||
.unwrap()
|
||||
.strip_suffix('>')
|
||||
.unwrap()
|
||||
.to_owned()
|
||||
};
|
||||
for (i, token) in tokens.iter().enumerate() {
|
||||
if !matches!(*token, "beginbfchar" | "beginbfrange") {
|
||||
continue;
|
||||
}
|
||||
let count: usize = tokens[i - 1].parse().unwrap();
|
||||
let size = if *token == "beginbfchar" { 2 } else { 3 };
|
||||
for row in tokens[i + 1..i + 1 + count * size].chunks(size) {
|
||||
let first = u8::from_str_radix(&hex(row[0]), 16).unwrap();
|
||||
if size == 2 {
|
||||
assert!(map.insert(first, hex(row[1])).is_none());
|
||||
} else {
|
||||
let last = u8::from_str_radix(&hex(row[1]), 16).unwrap();
|
||||
let value = hex(row[2]);
|
||||
let number = u64::from_str_radix(&value, 16).unwrap();
|
||||
for slot in first..=last {
|
||||
let value = format!(
|
||||
"{:0width$X}",
|
||||
number + u64::from(slot - first),
|
||||
width = value.len()
|
||||
);
|
||||
assert!(map.insert(slot, value).is_none());
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
map
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn final_parameter_table_scopes_sequences_and_invalid_overrides_match_pdftex() {
|
||||
let p = directory("maps");
|
||||
for (i, body) in [
|
||||
r"\pdfgentounicode=1\shipout\hbox{A}",
|
||||
r"\pdfglyphtounicode{A}{0042}\pdfgentounicode=-1\shipout\hbox{A}",
|
||||
r"\pdfglyphtounicode{A}{0042}\pdfgentounicode=0\shipout\hbox{A}",
|
||||
r"\pdfglyphtounicode{A}{0042}\pdfgentounicode=20\shipout\hbox{A}",
|
||||
r"{\globaldefs=-1\pdfglyphtounicode{A}{0042}}\pdfgentounicode=1\shipout\hbox{A}",
|
||||
r"\pdfglyphtounicode{A}{0042}\pdfgentounicode=1\shipout\hbox{A}\pdfglyphtounicode{A}{0043}",
|
||||
r"\pdfglyphtounicode{A}{0042}\pdfgentounicode=1\shipout\hbox{A}\pdfgentounicode=0",
|
||||
r"\pdfglyphtounicode{A}{0042}\shipout\hbox{A}\pdfgentounicode=1",
|
||||
r"\pdfglyphtounicode{A}{0042}\pdfgentounicode=1{\pdfgentounicode=0\shipout\hbox{A}}",
|
||||
r"\pdfglyphtounicode{A}{0042}\pdfglyphtounicode{B}{0043}\pdfgentounicode=1\shipout\hbox{A}",
|
||||
r"\pdfglyphtounicode{A}{0042}\pdfglyphtounicode{tfm:cmr10/A}{1F600}\pdfgentounicode=1\shipout\hbox{A}",
|
||||
r"\def\name{A}\def\value{0066 0069}\pdfglyphtounicode{\name}{\value}\pdfgentounicode=1\shipout\hbox{A}",
|
||||
r"\pdfglyphtounicode{A}{ 0066 0069 }\pdfgentounicode=1\shipout\hbox{A}",
|
||||
r"\pdfglyphtounicode{A}{D800}\pdfgentounicode=1\shipout\hbox{A}",
|
||||
r"\pdfglyphtounicode{A}{0 41}\pdfgentounicode=1\shipout\hbox{A}",
|
||||
r"\pdfglyphtounicode{A}{0042}\pdfglyphtounicode{A}{03b1}\pdfgentounicode=1\shipout\hbox{A}",
|
||||
r"\pdfglyphtounicode{A}{0042}\pdfglyphtounicode{A}{110000}\pdfgentounicode=1\shipout\hbox{A}",
|
||||
r"\pdfglyphtounicode{A}{0042}\pdfglyphtounicode{tfm:cmr10/A}{110000}\pdfgentounicode=1\shipout\hbox{A}",
|
||||
r"\pdfglyphtounicode{}{0042}\pdfglyphtounicode{.notdef}{0043}\pdfgentounicode=1\shipout\hbox{A}",
|
||||
r"\let\map=\pdfglyphtounicode\immediate\map{A}{00000000000041}\pdfgentounicode=1\shipout\hbox{A}",
|
||||
r"\pdfglyphtounicode{A}{0000}\pdfgentounicode=1\shipout\hbox{A}",
|
||||
].iter().enumerate() {
|
||||
let text = format!(r"{HEADER}{body}\end");
|
||||
let e = native(&text);
|
||||
let r = reference(&p,&text);
|
||||
assert!(r.status.success(), "case {i}: {}",String::from_utf8_lossy(&r.stdout));
|
||||
let ours = pdf(&e);
|
||||
fs::write(p.join("native.pdf"), &ours).unwrap();
|
||||
let expected = fs::read(p.join("probe.pdf")).unwrap();
|
||||
assert_eq!(cmaps(&ours), cmaps(&expected), "case {i}: {body}");
|
||||
assert_eq!(extracted(&p,"native.pdf"),extracted(&p,"probe.pdf"),"case {i}: {body}");
|
||||
assert!(e.reads.contains(&Dependency::GlyphUnicode));
|
||||
assert!(e.reads.contains(&Dependency::Parameter(Parameter::Pdfgentounicode)));
|
||||
}
|
||||
fs::remove_dir_all(p).unwrap();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn parameter_assignment_and_extension_afterassignment_prefix_rules_match_pdftex() {
|
||||
let p = directory("assignment");
|
||||
let text = format!(
|
||||
r"{HEADER}\newlinechar=33
|
||||
\message{{!CFG=\number\pdfgentounicode;!}}
|
||||
\let\U=\pdfgentounicode {{\U=4\advance\U by2\message{{!CFG=\the\U;!}}}}
|
||||
\message{{!CFG=\the\U;!}}
|
||||
\def\done{{\message{{!AFTER=\the\count0;!}}}}
|
||||
\afterassignment\done\pdfglyphtounicode{{A}}{{0042}}\count0=7
|
||||
\pdfgentounicode=1\shipout\hbox{{A}}\end"
|
||||
);
|
||||
let e = native(&text);
|
||||
assert!(reference(&p, &text).status.success());
|
||||
let log = fs::read_to_string(p.join("probe.log")).unwrap();
|
||||
let expected: Vec<_> = log
|
||||
.lines()
|
||||
.filter(|s| s.starts_with("CFG=") || s.starts_with("AFTER="))
|
||||
.collect();
|
||||
let actual: Vec<_> = e
|
||||
.events
|
||||
.iter()
|
||||
.filter_map(|e| match e {
|
||||
Event::Message { text, .. } => Some(text.trim()),
|
||||
_ => None,
|
||||
})
|
||||
.collect();
|
||||
assert_eq!(actual, expected);
|
||||
assert_eq!(actual, ["CFG=0;", "CFG=6;", "CFG=0;", "AFTER=7;"]);
|
||||
for prefix in [r"\global", r"\long", r"\protected"] {
|
||||
let text = format!(r"{HEADER}{prefix}\pdfglyphtounicode{{A}}{{0042}}\end");
|
||||
let e = Executor::new(State::initex().with_etex(), Limits::default())
|
||||
.run(source(&text), &mut font_world::FontFiles);
|
||||
assert!(e.is_err());
|
||||
assert!(!reference(&p, &text).status.success());
|
||||
}
|
||||
fs::remove_dir_all(p).unwrap();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn real_format_dump_restores_the_unicode_table_for_a_new_job() {
|
||||
let p = directory("format");
|
||||
let seed = format!(r"{HEADER}\pdfglyphtounicode{{A}}{{0066 0069}}\pdfgentounicode=1\dump");
|
||||
let dump = native(&seed);
|
||||
let state = State::initex().with_etex().with_pdf_output();
|
||||
let image = FormatImage::from_dump(dump, Vec::new(), Vec::new())
|
||||
.unwrap()
|
||||
.encode()
|
||||
.unwrap();
|
||||
let document = r"\shipout\hbox{A}\end";
|
||||
let e = FormatImage::decode(&image)
|
||||
.unwrap()
|
||||
.new_job(
|
||||
state.profile(),
|
||||
state.input_profile(),
|
||||
JobTime::new(2026, 11, 12, 0).unwrap(),
|
||||
Limits::default(),
|
||||
|_| Ok(seed.as_bytes().to_vec()),
|
||||
)
|
||||
.unwrap()
|
||||
.with_native_pages()
|
||||
.run(source(document), &mut font_world::FontFiles)
|
||||
.unwrap();
|
||||
assert!(reference(&p, &seed).status.success());
|
||||
fs::write(p.join("document.tex"), document).unwrap();
|
||||
let r = Command::new("pdftex")
|
||||
.args([
|
||||
"-fmt=./probe.fmt",
|
||||
"-interaction=nonstopmode",
|
||||
"-halt-on-error",
|
||||
"document.tex",
|
||||
])
|
||||
.current_dir(&p)
|
||||
.output()
|
||||
.unwrap();
|
||||
assert!(r.status.success(), "{}", String::from_utf8_lossy(&r.stdout));
|
||||
let ours = pdf(&e);
|
||||
let expected = fs::read(p.join("document.pdf")).unwrap();
|
||||
assert_eq!(cmaps(&ours), cmaps(&expected));
|
||||
assert_eq!(
|
||||
cmaps(&ours)[0].get(&65).map(String::as_str),
|
||||
Some("00660069")
|
||||
);
|
||||
fs::write(p.join("native.pdf"), ours).unwrap();
|
||||
assert_eq!(extracted(&p, "native.pdf"), extracted(&p, "document.pdf"));
|
||||
fs::remove_dir_all(p).unwrap();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn actual_reencoding_resolves_unused_glyph_names_as_pdftex_does() {
|
||||
use texrra_tex_core::resources::{FileWorld, ResourceKind, SearchPath, WorldConfig};
|
||||
struct Host<'a>(&'a Path);
|
||||
impl SourceProvider for Host<'_> {
|
||||
fn read(&mut self, name: &str, _: &str) -> Result<SourceFile, String> {
|
||||
Err(format!("unexpected source {name}"))
|
||||
}
|
||||
fn resource(
|
||||
&mut self,
|
||||
kind: ResourceKind,
|
||||
name: &str,
|
||||
from: &str,
|
||||
) -> Result<texrra_tex_core::resources::LoadedResource, String> {
|
||||
if matches!(kind, ResourceKind::Map | ResourceKind::Encoding) {
|
||||
let mut config = WorldConfig::new(self.0);
|
||||
config
|
||||
.paths
|
||||
.insert(kind, vec![SearchPath::directory(self.0, false)]);
|
||||
FileWorld::new(config)?.read(kind, name, Path::new(from))
|
||||
} else {
|
||||
font_world::resource(kind, name, from)
|
||||
}
|
||||
}
|
||||
}
|
||||
let p = directory("reencoding");
|
||||
let names = [
|
||||
"A.alt",
|
||||
"A_B",
|
||||
"unknown_A_unknown",
|
||||
"unknown_unknown",
|
||||
"uni00410042",
|
||||
"u1F600",
|
||||
"u0043",
|
||||
"u1f600",
|
||||
"uniD800",
|
||||
"uni0041D800",
|
||||
"u110000",
|
||||
"uFFF",
|
||||
"odd",
|
||||
"surrogate",
|
||||
"uni0041",
|
||||
"u0042",
|
||||
"A_B.alt",
|
||||
"B",
|
||||
"u0000",
|
||||
"u10FFFF",
|
||||
"uni0000FFFF",
|
||||
];
|
||||
let mut encoding = vec![".notdef"; 256];
|
||||
encoding[..names.len()].copy_from_slice(&names);
|
||||
encoding[65] = "A"; // The only painted slot has a real outline.
|
||||
let vector = encoding
|
||||
.iter()
|
||||
.map(|s| format!("/{s}"))
|
||||
.collect::<Vec<_>>()
|
||||
.join(" ");
|
||||
fs::write(
|
||||
p.join("probe.enc"),
|
||||
format!("/ProbeEncoding [{vector}] def\n"),
|
||||
)
|
||||
.unwrap();
|
||||
fs::write(
|
||||
p.join("pdftex.map"),
|
||||
"cmr10 CMR10 \"ProbeEncoding ReEncodeFont\" <probe.enc <cmr10.pfb\n",
|
||||
)
|
||||
.unwrap();
|
||||
let text = format!(
|
||||
r"{HEADER}
|
||||
\pdfglyphtounicode{{A}}{{0041}}\pdfglyphtounicode{{tfm:cmr10/A}}{{1F600}}
|
||||
\pdfglyphtounicode{{B}}{{0066 0069}}\pdfglyphtounicode{{A_B}}{{0043}}
|
||||
\pdfglyphtounicode{{u0043}}{{110000}}\pdfglyphtounicode{{odd}}{{0 41}}
|
||||
\pdfglyphtounicode{{surrogate}}{{D800}}
|
||||
\pdfgentounicode=1\shipout\hbox{{A}}\end"
|
||||
);
|
||||
let e = native(&text);
|
||||
let mut pages = e.shipout_display_lists().unwrap();
|
||||
texrra_tex_core::native_font::resolve_native_fonts(&mut pages, &mut Host(&p)).unwrap();
|
||||
let ours =
|
||||
texrra_tex_core::pdf::shipout_lists_to_native_pdf(&pages, e.state.pdf_final_options())
|
||||
.unwrap();
|
||||
let reference_text = text.replacen(HEADER, &format!(r"{HEADER}\pdfmapfile{{=pdftex.map}}"), 1);
|
||||
let r = reference(&p, &reference_text);
|
||||
assert!(r.status.success(), "{}", String::from_utf8_lossy(&r.stdout));
|
||||
assert_eq!(cmaps(&ours), cmaps(&fs::read(p.join("probe.pdf")).unwrap()));
|
||||
assert!(cmaps(&ours)[0].len() > names.len() / 2);
|
||||
fs::remove_dir_all(p).unwrap();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn old_schema_and_missing_unicode_state_are_rejected_even_with_valid_checksums() {
|
||||
use sha2::{Digest, Sha256};
|
||||
let seed = format!(r"{HEADER}\pdfglyphtounicode{{A}}{{0042}}\dump");
|
||||
let encoded = FormatImage::from_dump(native(&seed), Vec::new(), Vec::new())
|
||||
.unwrap()
|
||||
.encode()
|
||||
.unwrap();
|
||||
let envelope: serde_json::Value = serde_json::from_slice(&encoded).unwrap();
|
||||
let original: serde_json::Value =
|
||||
serde_json::from_str(envelope["payload"].as_str().unwrap()).unwrap();
|
||||
assert_eq!(original["schema"], 20);
|
||||
for (schema, expected) in [
|
||||
(1, "incompatible native format"),
|
||||
(2, "incompatible native format"),
|
||||
(3, "incompatible native format"),
|
||||
(4, "incompatible native format"),
|
||||
(5, "incompatible native format"),
|
||||
(6, "incompatible native format"),
|
||||
(7, "incompatible native format"),
|
||||
(8, "incompatible native format"),
|
||||
(9, "incompatible native format"),
|
||||
(10, "incompatible native format"),
|
||||
(11, "incompatible native format"),
|
||||
(12, "incompatible native format"),
|
||||
(13, "incompatible native format"),
|
||||
(14, "incompatible native format"),
|
||||
(15, "incompatible native format"),
|
||||
(16, "incompatible native format"),
|
||||
(17, "incompatible native format"),
|
||||
(18, "incompatible native format"),
|
||||
(19, "incompatible native format"),
|
||||
(20, "glyph_unicode"),
|
||||
] {
|
||||
let mut payload = original.clone();
|
||||
payload["schema"] = schema.into();
|
||||
payload["state"]
|
||||
.as_object_mut()
|
||||
.unwrap()
|
||||
.remove("glyph_unicode")
|
||||
.unwrap();
|
||||
let payload = serde_json::to_string(&payload).unwrap();
|
||||
let bytes = serde_json::to_vec(&serde_json::json!({
|
||||
"sha256": format!("{:x}",Sha256::digest(payload.as_bytes())), "payload": payload,
|
||||
}))
|
||||
.unwrap();
|
||||
let error = FormatImage::decode(&bytes)
|
||||
.err()
|
||||
.expect("old or incomplete state must fail");
|
||||
assert!(error.contains(expected), "{error}");
|
||||
}
|
||||
assert!(FormatImage::decode(&encoded).is_ok());
|
||||
}
|
||||
Reference in new issue
Block a user