Merge XDV document information in shipout order

This commit is contained in:
gloamxun committed 2026-11-25 19:28:12 +08:00
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,
+14 -11
View File
@@ -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) {
+1
View File
@@ -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")));
}
+25
View File
@@ -2175,6 +2175,31 @@ PDF,恢复实际 PFB 并反转斜切时复用 1277 步,只替换第二页。
全量编译一致。incremental-receipt.json 的 SHA-256 为
bbc0991b0316e6d76aa58649ec873525f5544ab530d93fe491fc6e16bd00a27d。
### XDV 发页时合并 PDF 文档信息
`pdf:docinfo` 使用现有 PDF 对象解析与导出,按实际发页顺序合并
文档字典,后一次设置覆盖同名字段。已保存的 UTF-16BE 保留原字节,
UTF-8 文本字段转为 UTF-16BE,自定义二进制字段独立保留。标准信息
字段为空时省略,类型不符时省略并报告。PDF 的 Producer 标记实际
原生导出器。当前支持直接 PDF 对象,XDV 设备引用仍待接入。
[上游文档字典处理](https://github.com/TeX-Live/texlive-source/blob/279984fab6eaed8d17e02882f2668ab5caac0f27/texk/dvipdfm-x/spc_pdfm.c)
两个双页的同源对照通过。字典覆盖、保留字段、直接 Unicode 和
UTF-16BE 标题与参考一致,四页 144 DPI 灰度图逐像素相同。8 项
XeTeX 定向检查与 1 项 PDF 信息字典回归通过。
三页原子项目的两次连续编辑各复用 114 步并重放 2 次宿主调用。
编辑第二页的 PDF 标题时更新 PDF,页面更新集合为空。随后编辑同页的
规则宽度时只更新第二页。首个已发页的 Subject 保留,两次的 PDF、SVG
与来源映射均等于同版本独立全量。
用原 schema71 和同一官方归档复编 ACL。首次发页已越过 `pdf:docinfo`,
停在 `hxetex.def:232:19` 的 `pdf:dest`,原样项目尚未生成 PDF。
真实参考的命名目标探测已覆盖 `@thispage`、后页引用、当前位置、
同名保留首次定义和保留未引用目标的设备选项。完整回执
`target/p3-xdv-docinfo/receipt.json`,SHA-256 为
`275ca3d914190797d76a47c189a3eb25661d7cac16f9f9087c9552186cbd0e89`。
### XeTeX 字形边缘悬挂与断行
XeTeX profile 执行 `\XeTeXprotrudechars`。级别 1 在封装实际行时
+6
View File
@@ -723,6 +723,12 @@ XeTeX 字形悬挂接入后,按上一轮冻结的十份 ACL 文件和字体复
原生尚未输出 PDF。回执 `target/p3-xetex-protrusion/receipt.json`。
[字形悬挂阶段记录](P2_M1_PROGRESS.md#xetex-字形边缘悬挂与断行)
XDV 文档信息字典接入后,复用原样 schema71 格式与同一份 ACL 归档。
十份项目源摘要再次核对一致。原样 ACL 首次发页已越过 `pdf:docinfo`,
新的首处差异为 `hxetex.def:232:19` 发出的 `pdf:dest`。
原生仍未生成 PDF。回执 `target/p3-xdv-docinfo/receipt.json`。
[XDV 文档信息阶段记录](P2_M1_PROGRESS.md#xdv-发页时合并-pdf-文档信息)
### 原样 Elsevier CAS 双栏与 NeurIPS 2025
以 `767c8ff`、既有真实 schema51 和参考格式复验官方 CAS 双栏。