Write native PDF catalogs and open actions
This commit is contained in:
1 parent
a53d9c9bf9
commit
f4b003bd27
20 files changed
+811
-40
No files matched your search
@@ -246,7 +246,7 @@ fn genuine_fraction_primitives_and_retained_boxes_survive_format_roundtrip() {
|
||||
let envelope: serde_json::Value = serde_json::from_slice(&bytes).unwrap();
|
||||
let payload: serde_json::Value =
|
||||
serde_json::from_str(envelope["payload"].as_str().unwrap()).unwrap();
|
||||
assert_eq!(payload["schema"], 22);
|
||||
assert_eq!(payload["schema"], 23);
|
||||
let state = State::initex().with_etex();
|
||||
let loaded = FormatImage::decode(&bytes)
|
||||
.unwrap()
|
||||
|
||||
@@ -0,0 +1,332 @@
|
||||
use lopdf::{Dictionary, Document, Object};
|
||||
use std::{
|
||||
fs,
|
||||
process::Command,
|
||||
sync::atomic::{AtomicUsize, Ordering},
|
||||
};
|
||||
use texrra_tex_core::{
|
||||
execution::{
|
||||
Error, Execution, Executor, FormatImage, InputProfile, JobTime, Limits, Profile,
|
||||
SourceFile, SourceProvider, State,
|
||||
},
|
||||
pdf::{NativePdfDocument, shipout_lists_to_native_pdf_document},
|
||||
};
|
||||
|
||||
const SETUP: &str = r"\catcode123=1 \catcode125=2 \catcode94=7 \pdfoutput=1 \pdfobjcompresslevel=0 \pdfcompresslevel=0 \pdfpkresolution=600 ";
|
||||
const PAGE: &str = r"\shipout\hbox{\vrule width8pt height6pt}";
|
||||
|
||||
struct RulesOnly;
|
||||
|
||||
impl SourceProvider for RulesOnly {
|
||||
fn read(&mut self, name: &str, _: &str) -> Result<SourceFile, String> {
|
||||
Err(format!("unexpected input {name}"))
|
||||
}
|
||||
}
|
||||
|
||||
fn run_native(source: &str) -> Result<Execution, Error> {
|
||||
Executor::new(
|
||||
State::initex()
|
||||
.with_etex()
|
||||
.with_input_profile(InputProfile::TeX8Bit),
|
||||
Limits::default(),
|
||||
)
|
||||
.with_native_pages()
|
||||
.run(
|
||||
SourceFile {
|
||||
name: "catalog.tex".into(),
|
||||
data: source.as_bytes().to_vec(),
|
||||
},
|
||||
&mut RulesOnly,
|
||||
)
|
||||
}
|
||||
|
||||
fn export_native(execution: &Execution) -> NativePdfDocument {
|
||||
shipout_lists_to_native_pdf_document(
|
||||
&execution.shipout_display_lists().unwrap(),
|
||||
execution.state.pdf_final_options(),
|
||||
)
|
||||
.unwrap()
|
||||
}
|
||||
|
||||
fn pair(body: &str) -> (Document, Document, Vec<String>) {
|
||||
let source = format!("{SETUP}{body}\\end\n");
|
||||
static NEXT: AtomicUsize = AtomicUsize::new(0);
|
||||
let work = std::env::temp_dir().join(format!(
|
||||
"texrra-pdf-catalog-{}-{}",
|
||||
std::process::id(),
|
||||
NEXT.fetch_add(1, Ordering::Relaxed)
|
||||
));
|
||||
fs::create_dir_all(&work).unwrap();
|
||||
fs::write(work.join("catalog.tex"), &source).unwrap();
|
||||
let reference = Command::new("pdftex")
|
||||
.args([
|
||||
"-ini",
|
||||
"-etex",
|
||||
"-interaction=nonstopmode",
|
||||
"-halt-on-error",
|
||||
"catalog.tex",
|
||||
])
|
||||
.current_dir(&work)
|
||||
.output()
|
||||
.unwrap();
|
||||
assert!(
|
||||
reference.status.success(),
|
||||
"{}",
|
||||
String::from_utf8_lossy(&reference.stdout)
|
||||
);
|
||||
let reference = Document::load(work.join("catalog.pdf")).unwrap();
|
||||
fs::remove_dir_all(work).unwrap();
|
||||
let native = export_native(&run_native(&source).unwrap());
|
||||
(
|
||||
reference,
|
||||
Document::load_mem(&native.bytes).unwrap(),
|
||||
native.diagnostics,
|
||||
)
|
||||
}
|
||||
|
||||
fn get<'a>(doc: &'a Document, dictionary: &'a Dictionary, key: &[u8]) -> &'a Object {
|
||||
let value = dictionary.get(key).unwrap();
|
||||
if let Object::Reference(id) = value {
|
||||
doc.get_object(*id).unwrap()
|
||||
} else {
|
||||
value
|
||||
}
|
||||
}
|
||||
|
||||
fn comparable(object: &Object) -> String {
|
||||
match object {
|
||||
Object::Dictionary(dictionary) => comparable_dictionary(dictionary),
|
||||
Object::Array(items) => format!(
|
||||
"array {:?}",
|
||||
items.iter().map(comparable).collect::<Vec<_>>()
|
||||
),
|
||||
Object::String(bytes, _) => format!("string {bytes:?}"),
|
||||
_ => format!("{object:?}"),
|
||||
}
|
||||
}
|
||||
|
||||
fn comparable_dictionary(dictionary: &Dictionary) -> String {
|
||||
let entries: std::collections::BTreeMap<_, _> = dictionary
|
||||
.iter()
|
||||
.map(|(key, value)| (key, comparable(value)))
|
||||
.collect();
|
||||
format!("dictionary {entries:?}")
|
||||
}
|
||||
|
||||
fn action(doc: &Document) -> &Dictionary {
|
||||
let catalog = doc.catalog().unwrap();
|
||||
assert!(matches!(
|
||||
catalog.get(b"OpenAction"),
|
||||
Ok(Object::Reference(_))
|
||||
));
|
||||
get(doc, catalog, b"OpenAction").as_dict().unwrap()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn catalog_appends_expanded_lists_and_prints_with_final_token_settings() {
|
||||
let (reference, native, _) = pair(&format!(
|
||||
r"\def\language{{en-GB}}{{\pdfcatalog{{/Lang (\language) /Raw (^^e9)}}}}
|
||||
\pdfcatalog{{/ViewerPreferences << /HideToolbar true >> /Custom (\noexpand\literal)}}
|
||||
\def\language{{en-US}}\escapechar=33 {PAGE}"
|
||||
));
|
||||
for key in [b"Lang".as_slice(), b"Raw", b"ViewerPreferences", b"Custom"] {
|
||||
let original = reference.catalog().unwrap().get(key).unwrap();
|
||||
let actual = native.catalog().unwrap().get(key).unwrap();
|
||||
assert_eq!(comparable(original), comparable(actual));
|
||||
}
|
||||
assert!(native.catalog().unwrap().get(b"OpenAction").is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn open_actions_use_the_actual_objects_and_page_references() {
|
||||
for command in [
|
||||
r"user {<< /S /URI /URI (https://example.org/paper) >>}",
|
||||
r"goto file {paper.pdf} page 3 {/Fit} newwindow ",
|
||||
r"goto file {(paper.pdf)} name {chapter} nonewwindow ",
|
||||
r"goto file {paper.pdf} struct {[5 /Fit]} name {chapter}",
|
||||
r"thread file {paper.pdf} num 3 ",
|
||||
] {
|
||||
let (reference, native, _) = pair(&format!("\\pdfcatalog{{}} openaction {command}{PAGE}"));
|
||||
assert_eq!(
|
||||
comparable_dictionary(action(&reference)),
|
||||
comparable_dictionary(action(&native)),
|
||||
"{command}"
|
||||
);
|
||||
}
|
||||
let (reference, native, _) = pair(&format!(
|
||||
"\\pdfcatalog{{}} openaction goto page 2 {{/FitH 700}}{PAGE}{PAGE}"
|
||||
));
|
||||
for pdf in [&reference, &native] {
|
||||
let target = action(pdf).get(b"D").unwrap().as_array().unwrap();
|
||||
assert_eq!(target[0].as_reference().unwrap(), pdf.get_pages()[&2]);
|
||||
assert_eq!(target[1].as_name().unwrap(), b"FitH");
|
||||
assert_eq!(target[2].as_i64().unwrap(), 700);
|
||||
}
|
||||
let (reference, native, _) = pair(
|
||||
r"\pdfcatalog{} openaction goto num 9
|
||||
\shipout\hbox{\pdfdest num 9 fit\vrule width8pt height6pt}",
|
||||
);
|
||||
for pdf in [&reference, &native] {
|
||||
let target = get(pdf, action(pdf), b"D").as_array().unwrap();
|
||||
assert_eq!(target[0].as_reference().unwrap(), pdf.get_pages()[&1]);
|
||||
assert_eq!(target[1].as_name().unwrap(), b"Fit");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn absent_targets_follow_reference_destination_and_xref_behavior() {
|
||||
let (reference, native, messages) = pair(&format!(
|
||||
"\\pdfcatalog{{}} openaction goto name {{missing}}{PAGE}"
|
||||
));
|
||||
assert_eq!(
|
||||
comparable_dictionary(action(&reference)),
|
||||
comparable_dictionary(action(&native))
|
||||
);
|
||||
assert!(
|
||||
messages
|
||||
.iter()
|
||||
.any(|message| message.contains("name{missing}"))
|
||||
);
|
||||
for pdf in [&reference, &native] {
|
||||
let names = get(pdf, pdf.catalog().unwrap(), b"Names")
|
||||
.as_dict()
|
||||
.unwrap();
|
||||
let dests = get(pdf, names, b"Dests").as_dict().unwrap();
|
||||
let entries = dests.get(b"Names").unwrap().as_array().unwrap();
|
||||
assert_eq!(entries[0].as_str().unwrap(), b"missing");
|
||||
let target = pdf.get_object(entries[1].as_reference().unwrap()).unwrap();
|
||||
let target = if let Object::Dictionary(dictionary) = target {
|
||||
get(pdf, dictionary, b"D")
|
||||
} else {
|
||||
target
|
||||
};
|
||||
let target = target.as_array().unwrap();
|
||||
assert_eq!(target[0].as_reference().unwrap(), pdf.get_pages()[&1]);
|
||||
assert_eq!(target[1].as_name().unwrap(), b"Fit");
|
||||
}
|
||||
for compression in [0, 2] {
|
||||
// pdfTeX inserts diagnostic comments in raw (uncompressed) object
|
||||
// streams, which this version of lopdf cannot unpack.
|
||||
let stream_compression = if compression == 0 { 0 } else { 9 };
|
||||
let (reference, native, messages) = pair(&format!(
|
||||
"\\pdfminorversion=5 \\pdfobjcompresslevel={compression} \\pdfcompresslevel={stream_compression} \\pdfcatalog{{}} openaction goto page 2 {{/Fit}}{PAGE}"
|
||||
));
|
||||
assert!(messages.iter().any(|message| message.contains("page 2")));
|
||||
for pdf in [&reference, &native] {
|
||||
let target = action(pdf).get(b"D").unwrap().as_array().unwrap();
|
||||
assert_eq!(pdf.get_pages().len(), 1);
|
||||
assert!(pdf.get_object(target[0].as_reference().unwrap()).is_err());
|
||||
assert_eq!(target[1].as_name().unwrap(), b"Fit");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn format_images_retain_catalog_primitive_and_clear_job_catalog_data() {
|
||||
let seed = format!("{SETUP}\\pdfcatalog{{/Lang (seed)}}\\dump\n");
|
||||
let dump = run_native(&seed).unwrap();
|
||||
assert!(dump.state.pdf_final_options().catalog.is_some());
|
||||
let image = FormatImage::from_dump(dump, Vec::new(), Vec::new())
|
||||
.unwrap()
|
||||
.encode()
|
||||
.unwrap();
|
||||
let job = FormatImage::decode(&image)
|
||||
.unwrap()
|
||||
.new_job(
|
||||
Profile::EtexBootstrap,
|
||||
InputProfile::TeX8Bit,
|
||||
JobTime::new(2026, 1, 2, 123).unwrap(),
|
||||
Limits::default(),
|
||||
|_| Ok(seed.as_bytes().to_vec()),
|
||||
)
|
||||
.unwrap()
|
||||
.with_native_pages()
|
||||
.run(
|
||||
SourceFile {
|
||||
name: "document.tex".into(),
|
||||
data: format!("\\pdfcatalog{{/PageLayout /SinglePage}}{PAGE}\\end").into_bytes(),
|
||||
},
|
||||
&mut RulesOnly,
|
||||
)
|
||||
.unwrap();
|
||||
let doc = Document::load_mem(&export_native(&job).bytes).unwrap();
|
||||
let catalog = doc.catalog().unwrap();
|
||||
assert!(catalog.get(b"Lang").is_err());
|
||||
assert_eq!(
|
||||
catalog.get(b"PageLayout").unwrap().as_name().unwrap(),
|
||||
b"SinglePage"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn missing_local_threads_build_the_reference_fallback_bead() {
|
||||
for (identifier, title) in [(r"name {chapter}", "chapter"), ("num 2", "2")] {
|
||||
let (reference, native, messages) = pair(&format!(
|
||||
"\\pdfcatalog{{}} openaction thread {identifier} {PAGE}"
|
||||
));
|
||||
assert!(
|
||||
messages
|
||||
.iter()
|
||||
.any(|message| message.contains("thread destination"))
|
||||
);
|
||||
for pdf in [&reference, &native] {
|
||||
let threads = get(pdf, pdf.catalog().unwrap(), b"Threads")
|
||||
.as_array()
|
||||
.unwrap();
|
||||
assert_eq!(threads.len(), 1);
|
||||
let thread_id = threads[0].as_reference().unwrap();
|
||||
let thread = pdf.get_object(thread_id).unwrap().as_dict().unwrap();
|
||||
let bead_id = thread.get(b"F").unwrap().as_reference().unwrap();
|
||||
let bead = pdf.get_object(bead_id).unwrap().as_dict().unwrap();
|
||||
let info = get(pdf, thread, b"I").as_dict().unwrap();
|
||||
assert_eq!(
|
||||
info.get(b"Title").unwrap().as_str().unwrap(),
|
||||
title.as_bytes()
|
||||
);
|
||||
assert_eq!(bead.get(b"T").unwrap().as_reference().unwrap(), thread_id);
|
||||
assert_eq!(bead.get(b"V").unwrap().as_reference().unwrap(), bead_id);
|
||||
assert_eq!(bead.get(b"N").unwrap().as_reference().unwrap(), bead_id);
|
||||
assert_eq!(
|
||||
bead.get(b"P").unwrap().as_reference().unwrap(),
|
||||
pdf.get_pages()[&1]
|
||||
);
|
||||
assert_eq!(action(pdf).get(b"S").unwrap().as_name().unwrap(), b"Thread");
|
||||
let destination = action(pdf).get(b"D").unwrap();
|
||||
if identifier.starts_with("name") {
|
||||
assert_eq!(destination.as_str().unwrap(), title.as_bytes());
|
||||
} else {
|
||||
assert_eq!(destination.as_reference().unwrap(), thread_id);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rejects_duplicate_actions_and_freezes_file_options_only_for_an_action() {
|
||||
let duplicate = format!(
|
||||
r"{SETUP}\pdfcatalog{{}} openaction goto page 1 {{/Fit}}
|
||||
\pdfcatalog{{}} openaction goto page 1 {{/Fit}}{PAGE}\end"
|
||||
);
|
||||
let error = run_native(&duplicate).unwrap_err();
|
||||
assert!(error.message.contains("duplicate of openaction"));
|
||||
|
||||
let changed = format!(
|
||||
r"{SETUP}\pdfminorversion=4 \pdfcatalog{{}} openaction goto page 1 {{/Fit}}
|
||||
\pdfminorversion=5 {PAGE}\end"
|
||||
);
|
||||
assert!(
|
||||
run_native(&changed)
|
||||
.unwrap_err()
|
||||
.message
|
||||
.contains("version cannot change")
|
||||
);
|
||||
let (_, native, _) = pair(&format!(
|
||||
r"\pdfminorversion=4 \pdfcatalog{{/Lang (en)}}\pdfminorversion=5 {PAGE}"
|
||||
));
|
||||
assert_eq!(native.version, "1.5");
|
||||
|
||||
let (_, native, _) = pair(&format!(
|
||||
r"\pdfoutput=0 \pdfcatalog{{/Lang (en)}}\pdfoutput=1 {PAGE}"
|
||||
));
|
||||
assert!(native.catalog().unwrap().get(b"Lang").is_err());
|
||||
}
|
||||
@@ -334,7 +334,7 @@ fn old_schema_and_missing_unicode_state_are_rejected_even_with_valid_checksums()
|
||||
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"], 22);
|
||||
assert_eq!(original["schema"], 23);
|
||||
for (schema, expected) in [
|
||||
(1, "incompatible native format"),
|
||||
(2, "incompatible native format"),
|
||||
@@ -357,7 +357,8 @@ fn old_schema_and_missing_unicode_state_are_rejected_even_with_valid_checksums()
|
||||
(19, "incompatible native format"),
|
||||
(20, "incompatible native format"),
|
||||
(21, "incompatible native format"),
|
||||
(22, "glyph_unicode"),
|
||||
(22, "incompatible native format"),
|
||||
(23, "glyph_unicode"),
|
||||
] {
|
||||
let mut payload = original.clone();
|
||||
payload["schema"] = schema.into();
|
||||
|
||||
@@ -164,7 +164,7 @@ fn new_format_owns_vcenter_and_boxed_math_without_reinjecting_old_meanings() {
|
||||
let envelope: serde_json::Value = serde_json::from_slice(&bytes).unwrap();
|
||||
let payload: serde_json::Value =
|
||||
serde_json::from_str(envelope["payload"].as_str().unwrap()).unwrap();
|
||||
assert_eq!(payload["schema"], 22);
|
||||
assert_eq!(payload["schema"], 23);
|
||||
let executor = FormatImage::decode(&bytes)
|
||||
.unwrap()
|
||||
.new_job(
|
||||
|
||||
Reference in new issue
Block a user