Merge XDV document information in shipout order
This commit is contained in:
1 parent
6826efbeb1
commit
dd695a8945
9 files changed
+251
-21
No files matched your search
@@ -92,14 +92,22 @@ impl Executor {
|
||||
return Ok(Some(graphics));
|
||||
}
|
||||
let body = data.strip_prefix(b"pdf:").map(<[u8]>::trim_ascii_start);
|
||||
let Some(mut body) =
|
||||
body.and_then(|body| body.strip_prefix(b"literal"))
|
||||
.filter(|body| {
|
||||
!body
|
||||
.first()
|
||||
.is_some_and(|b| b.is_ascii_alphanumeric() || *b == b'_' || *b == b':')
|
||||
})
|
||||
else {
|
||||
if let Some(dictionary) = body.and_then(|body| xdv_operand(body, b"docinfo")) {
|
||||
use crate::pdf_device::xdv_document::merge_docinfo;
|
||||
let (entries, warnings) = merge_docinfo(&self.state.pdf_info, dictionary)
|
||||
.map_err(|error| self.error(error, special.span))?;
|
||||
if entries.len() > self.limits.tokens {
|
||||
return self.fail("native PDF information payload limit exceeded");
|
||||
}
|
||||
for warning in warnings {
|
||||
files.observe_diagnostic(WriteDestination::TerminalAndLog, &warning)
|
||||
.map_err(|error| self.error(error, special.span))?;
|
||||
}
|
||||
self.reads.insert(Dependency::PdfInfoState);
|
||||
self.state.pdf_info = entries;
|
||||
return Ok(None);
|
||||
}
|
||||
let Some(mut body) = body.and_then(|body| xdv_operand(body, b"literal")) else {
|
||||
let name = data
|
||||
.split(|b| b.is_ascii_whitespace())
|
||||
.next()
|
||||
@@ -142,6 +150,12 @@ impl Executor {
|
||||
}
|
||||
}
|
||||
|
||||
fn xdv_operand<'a>(data: &'a [u8], command: &[u8]) -> Option<&'a [u8]> {
|
||||
data.strip_prefix(command).filter(|rest| {
|
||||
!rest.first().is_some_and(|byte| byte.is_ascii_alphanumeric() || matches!(byte, b'_' | b':'))
|
||||
})
|
||||
}
|
||||
|
||||
fn xdv_transform(data: &[u8]) -> Result<Option<PdfGraphics>, &'static str> {
|
||||
let Some(separator) = data.iter().position(|&byte| byte == b':') else {
|
||||
return Ok(None);
|
||||
|
||||
@@ -420,6 +420,7 @@ pub enum Dependency {
|
||||
MagnificationState,
|
||||
PdfFileState,
|
||||
PdfCatalogState,
|
||||
PdfInfoState,
|
||||
PdfObjects,
|
||||
PdfImages,
|
||||
PdfLastPosition,
|
||||
|
||||
@@ -2784,23 +2784,26 @@ fn write_pdf(
|
||||
objects[0] = catalog;
|
||||
|
||||
if let Some(level) = final_compression {
|
||||
let device = pages[0].pdf.as_ref().expect("validated native PDF options");
|
||||
let info = match unicode {
|
||||
Some(options) => native_information_dictionary(crate::pdf_device::PdfInfo {
|
||||
entries: remapped.as_ref().and_then(|resources| resources.info.as_deref())
|
||||
.unwrap_or(options.info.entries),
|
||||
date: options.info.date,
|
||||
}),
|
||||
Some(options) => {
|
||||
let info = crate::pdf_device::PdfInfo {
|
||||
entries: remapped.as_ref().and_then(|resources| resources.info.as_deref())
|
||||
.unwrap_or(options.info.entries),
|
||||
date: options.info.date,
|
||||
};
|
||||
if device.driver == crate::pdf_device::PdfDriver::Xdv {
|
||||
crate::pdf_device::xdv_document::information_dictionary(info, diagnostics)?
|
||||
} else {
|
||||
native_information_dictionary(info)
|
||||
}
|
||||
}
|
||||
None => metadata_object(metadata)
|
||||
.map(String::into_bytes)
|
||||
.unwrap_or_else(|| b"<< /Producer (texrra Route-D native) >>".to_vec()),
|
||||
};
|
||||
objects.push(info);
|
||||
let options = &pages[0]
|
||||
.pdf
|
||||
.as_ref()
|
||||
.expect("validated native PDF options")
|
||||
.file;
|
||||
return Ok(objects::serialize(&objects, Some(objects.len()), options, level.max(0).min(9) as u8));
|
||||
return Ok(objects::serialize(&objects, Some(objects.len()), &device.file, level.max(0).min(9) as u8));
|
||||
}
|
||||
|
||||
let info_ref = match metadata_object(metadata) {
|
||||
|
||||
@@ -97,6 +97,7 @@ pub fn print_sp(value: i64, digits: u8) -> String {
|
||||
}
|
||||
}
|
||||
mod color;
|
||||
pub(crate) mod xdv_document;
|
||||
pub(crate) mod xdv_image;
|
||||
mod graphics;
|
||||
pub(crate) use color::{ColorResult, PdfColorStacks};
|
||||
|
||||
@@ -258,7 +258,7 @@ pub(crate) fn check_pdf_nesting(bytes: &[u8]) -> Result<(), String> {
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn parse_value(bytes: &[u8]) -> Result<Object, String> {
|
||||
pub(super) fn parse_value(bytes: &[u8]) -> Result<Object, String> {
|
||||
check_pdf_nesting(bytes)?;
|
||||
// The content parser accepts complete PDF arrays, including references
|
||||
// inside them. Requiring the final operator also rejects a partially
|
||||
@@ -303,7 +303,7 @@ pub(crate) fn font_attributes_affect_paint(bytes: &[u8]) -> Result<bool, String>
|
||||
Ok(attributes.iter().any(|(name, _)| name != b"ToUnicode"))
|
||||
}
|
||||
|
||||
fn encode_value(object: Object) -> Result<Vec<u8>, String> {
|
||||
pub(super) fn encode_value(object: Object) -> Result<Vec<u8>, String> {
|
||||
if let Object::Stream(stream) = object {
|
||||
let mut output = encode_value(Object::Dictionary(stream.dict))?;
|
||||
output.extend_from_slice(b"\nstream\n");
|
||||
|
||||
@@ -0,0 +1,129 @@
|
||||
//! Document dictionary specials executed in XDV page order.
|
||||
use lopdf::{Object, StringFormat};
|
||||
|
||||
use super::{
|
||||
PdfInfo,
|
||||
page_resources::{encode_value, parse_entries, parse_value},
|
||||
};
|
||||
|
||||
const TEXT_KEYS: &[&[u8]] = &[
|
||||
b"Title",
|
||||
b"Author",
|
||||
b"Subject",
|
||||
b"Keywords",
|
||||
b"Creator",
|
||||
b"Producer",
|
||||
b"Contents",
|
||||
b"Subj",
|
||||
b"TU",
|
||||
b"T",
|
||||
b"TM",
|
||||
];
|
||||
|
||||
const INFO_STRING_KEYS: &[&[u8]] = &[
|
||||
b"Title",
|
||||
b"Author",
|
||||
b"Subject",
|
||||
b"Keywords",
|
||||
b"Creator",
|
||||
b"Producer",
|
||||
b"CreationDate",
|
||||
b"ModDate",
|
||||
];
|
||||
|
||||
pub(crate) fn merge_docinfo(
|
||||
current: &[u8],
|
||||
special: &[u8],
|
||||
) -> Result<(Vec<u8>, Vec<String>), String> {
|
||||
let Object::Dictionary(additions) = parse_value(special)? else {
|
||||
return Err("pdf:docinfo requires a PDF dictionary".into());
|
||||
};
|
||||
let mut document = parse_entries(current)?;
|
||||
let mut warnings = Vec::new();
|
||||
for (key, value) in &additions {
|
||||
let mut value = value.clone();
|
||||
convert_text(key, &mut value, &mut warnings)?;
|
||||
document.set(key.clone(), value);
|
||||
}
|
||||
|
||||
let encoded = encode_value(Object::Dictionary(document))?;
|
||||
let entries = encoded
|
||||
.trim_ascii()
|
||||
.strip_prefix(b"<<")
|
||||
.and_then(|body| body.strip_suffix(b">>"))
|
||||
.expect("the PDF encoder emits a dictionary");
|
||||
Ok((entries.to_vec(), warnings))
|
||||
}
|
||||
|
||||
fn convert_text(key: &[u8], value: &mut Object, warnings: &mut Vec<String>) -> Result<(), String> {
|
||||
match value {
|
||||
Object::String(bytes, format)
|
||||
if TEXT_KEYS.contains(&key)
|
||||
&& !bytes.starts_with(&[0xfe, 0xff])
|
||||
&& !bytes.is_ascii() =>
|
||||
{
|
||||
if let Ok(text) = std::str::from_utf8(bytes) {
|
||||
*bytes = [0xfe, 0xff]
|
||||
.into_iter()
|
||||
.chain(text.encode_utf16().flat_map(u16::to_be_bytes))
|
||||
.collect();
|
||||
*format = StringFormat::Hexadecimal;
|
||||
} else {
|
||||
warnings.push(format!(
|
||||
"xdvipdfmx: warning: Input string conversion (to UTF16BE) failed for {}...\n",
|
||||
String::from_utf8_lossy(key),
|
||||
));
|
||||
}
|
||||
}
|
||||
Object::Array(values) => {
|
||||
for value in values {
|
||||
convert_text(key, value, warnings)?;
|
||||
}
|
||||
}
|
||||
Object::Dictionary(entries) => {
|
||||
for (key, value) in entries.iter_mut() {
|
||||
convert_text(key, value, warnings)?;
|
||||
}
|
||||
}
|
||||
Object::Reference(_) => {
|
||||
return Err("unsupported reference in XDV document information".into());
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub(crate) fn information_dictionary(
|
||||
info: PdfInfo<'_>,
|
||||
diagnostics: &mut Vec<String>,
|
||||
) -> Result<Vec<u8>, String> {
|
||||
let mut dictionary = parse_entries(info.entries)?;
|
||||
// Identify the native producer, while respecting a creator set by the document.
|
||||
if !dictionary.has(b"Creator") {
|
||||
dictionary.set("Creator", Object::string_literal("TeX"));
|
||||
}
|
||||
for &key in INFO_STRING_KEYS {
|
||||
match dictionary.get(key) {
|
||||
Ok(Object::String(bytes, _)) if bytes.is_empty() => {
|
||||
dictionary.remove(key);
|
||||
}
|
||||
Ok(Object::String(_, _)) | Err(_) => {}
|
||||
Ok(_) => {
|
||||
diagnostics.push(format!(
|
||||
"xdvipdfmx: warning: {:?} removed from DocInfo because its value is not a string.",
|
||||
String::from_utf8_lossy(key),
|
||||
));
|
||||
dictionary.remove(key);
|
||||
}
|
||||
}
|
||||
}
|
||||
if !dictionary.has(b"Producer") {
|
||||
dictionary.set("Producer", Object::string_literal("texrra Route-D native"));
|
||||
}
|
||||
if !dictionary.has(b"CreationDate")
|
||||
&& let Some(date) = info.date
|
||||
{
|
||||
dictionary.set("CreationDate", Object::string_literal(date));
|
||||
}
|
||||
encode_value(Object::Dictionary(dictionary))
|
||||
}
|
||||
@@ -441,3 +441,54 @@ fn xetex_protrusion_level_scopes_and_font_codes_are_job_local() {
|
||||
.unwrap();
|
||||
assert_eq!(messages(&result), ["2/0", "1/1600", "2/1600"]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn xdv_docinfo_merges_shipped_dictionaries_into_pdf_info() {
|
||||
use lopdf::Document;
|
||||
use texrra_tex_core::pdf::shipout_lists_to_native_pdf_document;
|
||||
|
||||
let state = State::initex()
|
||||
.with_etex()
|
||||
.with_input_profile(InputProfile::XeTeX);
|
||||
let result = Executor::new(state, Limits::default())
|
||||
.with_native_pages()
|
||||
.run(
|
||||
source(
|
||||
r"\catcode123=1 \catcode125=2
|
||||
\setbox0=\hbox{\special{pdf:docinfo<</Discarded(true)>>}}
|
||||
\shipout\hbox{\special{pdf:docinfo<</Title(Earlier)/Subject(Kept)/Creator(User)>>}
|
||||
\vrule width5pt height3pt depth0pt}
|
||||
\shipout\hbox{\special{pdf:docinfo << /Title(Edited Ω) /Creator() /Author 42
|
||||
/UserBytes <FF00> >>}\vrule width5pt height3pt depth0pt}
|
||||
\end",
|
||||
),
|
||||
&mut TestDevice,
|
||||
)
|
||||
.unwrap();
|
||||
assert!(result.reads.contains(&Dependency::PdfInfoState));
|
||||
let pages: Vec<_> = result
|
||||
.events
|
||||
.iter()
|
||||
.filter_map(|event| match event {
|
||||
Event::Shipout(page) => Some(page.display_list().unwrap()),
|
||||
_ => None,
|
||||
})
|
||||
.collect();
|
||||
assert_eq!(pages.len(), 2);
|
||||
let output =
|
||||
shipout_lists_to_native_pdf_document(&pages, result.state.pdf_final_options()).unwrap();
|
||||
let pdf = Document::load_mem(&output.bytes).unwrap();
|
||||
let id = pdf.trailer.get(b"Info").unwrap().as_reference().unwrap();
|
||||
let info = pdf.get_object(id).unwrap().as_dict().unwrap();
|
||||
let title: Vec<_> = [0xFE, 0xFF]
|
||||
.into_iter()
|
||||
.chain("Edited Ω".encode_utf16().flat_map(u16::to_be_bytes))
|
||||
.collect();
|
||||
assert_eq!(info.get(b"Title").unwrap().as_str().unwrap(), title);
|
||||
assert_eq!(info.get(b"Subject").unwrap().as_str().unwrap(), b"Kept");
|
||||
assert_eq!(info.get(b"UserBytes").unwrap().as_str().unwrap(), [255, 0]);
|
||||
for omitted in [b"Author".as_slice(), b"Creator", b"Discarded"] {
|
||||
assert!(!info.has(omitted));
|
||||
}
|
||||
assert!(output.diagnostics.iter().any(|text| text.contains("Author")));
|
||||
}
|
||||
Reference in new issue
Block a user