Write XeLaTeX document name trees and attachments

This commit is contained in:
gloamxun committed 2026-11-28 20:54:56 +08:00
1 parent d627614af8
commit dcc6a3984c
9 files changed
+446 -14

No files matched your search

@@ -102,6 +102,8 @@ impl Setup {
pub(crate) struct Destination {
pub(crate) name: Vec<u8>,
pub(crate) page: usize,
#[serde(default)]
pub(crate) order: super::xdv_annotation::Order,
view: String,
operands: Vec<Operand>,
point: [i64; 2],
@@ -121,6 +123,7 @@ impl Destination {
input: &[u8],
current_page: usize,
point: [i64; 2],
order: super::xdv_annotation::Order,
) -> Result<Self, String> {
let (name, rest) = split_string(trim_pdf(input))?;
let Object::String(name, _) = parse_value(name)? else {
@@ -176,6 +179,7 @@ impl Destination {
Ok(Self {
name,
page,
order,
view,
operands,
point,
@@ -12,6 +12,7 @@ use super::xdv_object::{
};
mod named_objects;
mod name_trees;
mod page_dictionaries;
mod page_resources;
mod forms;
@@ -37,6 +38,10 @@ pub(crate) struct Navigation {
page_resources: PageResources,
#[serde(default, skip_serializing_if = "Forms::is_empty")]
forms: Forms,
#[serde(default, skip_serializing_if = "Vec::is_empty")]
name_registrations: Vec<name_trees::Registration>,
#[serde(default, skip_serializing_if = "Option::is_none")]
names_root: Option<Dictionary>,
}
#[derive(Clone, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)]
@@ -130,6 +135,9 @@ impl Navigation {
self.page_dictionaries.collect_references(pending);
self.page_resources.collect_references(pending);
self.forms.collect_references(pending);
for value in self.names_root.iter().flat_map(|root| root.values()) {
value.collect_references(pending);
}
}
pub(crate) fn reserve_objects<'a>(
@@ -162,7 +170,7 @@ impl Navigation {
diagnostics: &mut Vec<String>,
) -> Result<(), String> {
for (name, &id) in references.named {
if self.forms.number(name).is_some() {
if name.as_slice() == b"names" || self.forms.number(name).is_some() {
continue;
}
objects[id as usize - 1] = if let Some(object) = self.objects.get(name) {
@@ -178,15 +186,25 @@ impl Navigation {
Ok(())
}
pub(crate) fn finish_catalog(&self, base: &str, references: &References<'_>) -> Result<Vec<u8>, String> {
pub(crate) fn finish_catalog(
&self,
base: &str,
references: &References<'_>,
generated_names: lopdf::Dictionary,
objects: &mut Vec<Vec<u8>>,
diagnostics: &mut Vec<String>,
) -> Result<Vec<u8>, String> {
let Object::Dictionary(mut catalog) = parse_value(format!("{base} >>").as_bytes())? else {
unreachable!("native PDF catalog is a dictionary");
};
let additions = output_dictionary(&self.catalog, references)?;
let reserved = references.named.get(b"names".as_slice()).copied();
let has_name_root = reserved.is_some() || self.names_root.is_some() || !generated_names.is_empty();
for (key, value) in &additions {
match key.as_slice() {
b"Type" | b"Pages" => {}
b"Outlines" | b"Threads" if catalog.has(key) => {}
b"Names" if has_name_root => {}
b"Names" if catalog.has(key) => {
if let (Ok(Object::Dictionary(generated)), Object::Dictionary(extra)) =
(catalog.get_mut(key), value)
@@ -199,6 +217,44 @@ impl Navigation {
_ => catalog.set(key.clone(), value.clone()),
}
}
if has_name_root {
let mut names = self.names_root.as_ref().map(|fields| output_dictionary(fields, references))
.transpose()?.unwrap_or_default();
if let Ok(Object::Dictionary(legacy)) = catalog.get(b"Names") {
for (key, value) in legacy {
names.set(key.clone(), value.clone());
}
}
for (key, value) in &generated_names {
names.set(key.clone(), value.clone());
}
let external_root = match additions.get(b"Names") {
Ok(Object::Dictionary(extra)) => {
for (key, value) in extra {
names.set(key.clone(), value.clone());
}
None
}
Ok(Object::Reference((id, 0))) if Some(*id) == reserved => None,
Ok(other) => Some(other.clone()),
Err(_) => None,
};
if reserved.is_some() || external_root.is_none() {
let body = encode_device_value(Object::Dictionary(names))?;
let id = if let Some(id) = reserved {
objects[id as usize - 1] = body;
id
} else {
objects.push(body);
u32::try_from(objects.len()).map_err(|_| "XDV PDF object ID out of range")?
};
catalog.set("Names", Object::Reference((id, 0)));
}
if let Some(other) = external_root {
diagnostics.push(name_trees::warning("Could not modify Names dictionary."));
catalog.set("Names", other);
}
}
encode_device_value(Object::Dictionary(catalog))
}
@@ -0,0 +1,267 @@
//! Document name trees populated by shipped XDV specials.
use std::collections::{BTreeMap, btree_map::Entry};
use lopdf::{Dictionary as PdfDictionary, Object, StringFormat};
use serde::{Deserialize, Serialize};
use super::super::xdv_object::{parse_object, parse_object_prefix};
use super::{Navigation, Order, Position, References, Value, encode_device_value, parse_value};
const DESTS: &[u8] = b"Dests";
const BRANCHES: usize = 4;
const LEAF_SIZE: usize = 2 * BRANCHES;
#[derive(Clone, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)]
pub(super) struct Registration {
category: Vec<u8>,
order: Order,
entries: Vec<(Vec<u8>, Value)>,
}
#[derive(Default)]
pub(crate) struct PreparedNames<'a> {
trees: BTreeMap<&'a [u8], BTreeMap<&'a [u8], &'a Value>>,
}
impl Navigation {
pub(crate) fn add_names(
&mut self,
bytes: &[u8],
position: Position,
order: Order,
limit: usize,
) -> Result<Vec<String>, String> {
self.add_payload(bytes.len(), limit)?;
let parsed = parse_registration(bytes, position, order);
match parsed {
Err(message) => Ok(vec![warning(&message)]),
Ok((registration, problem)) => {
if !registration.entries.is_empty() {
self.name_registrations.push(registration);
}
Ok(problem.into_iter().map(warning).collect())
}
}
}
pub(crate) fn prepare_names<'a>(
&'a self,
positioned: impl Fn(&[u8]) -> Option<Order>,
diagnostics: &mut Vec<String>,
) -> PreparedNames<'a> {
let mut result = PreparedNames::default();
for registration in &self.name_registrations {
let category = registration.category.as_slice();
let tree = result.trees.entry(category).or_default();
for (key, value) in &registration.entries {
let key = key.as_slice();
let position_wins = category == DESTS
&& positioned(key).is_some_and(|order| order < registration.order);
if position_wins || tree.contains_key(key) {
diagnostics.push(duplicate(key));
diagnostics.push(warning("Failed to add Name tree entry..."));
break;
}
tree.insert(key, value);
}
}
result
}
}
fn parse_registration(
bytes: &[u8],
position: Position,
order: Order,
) -> Result<(Registration, Option<&'static str>), String> {
let (category, rest) = parse_object_prefix(bytes, position)?;
let Value::Name(category) = category else {
return Err("PDF name expected for XDV name dictionary category.".into());
};
if !matches!(
category.as_slice(),
b"Dests"
| b"AP"
| b"JavaScript"
| b"Pages"
| b"Templates"
| b"IDS"
| b"URLS"
| b"EmbeddedFiles"
| b"AlternatePresentations"
| b"Renditions"
) {
return Err(format!(
"Unknown name dictionary category {:?}.",
String::from_utf8_lossy(&category)
));
}
let (keys, rest) = parse_object_prefix(rest, position)?;
let operands = match keys {
Value::Array(_) if !rest.is_empty() => {
return Err("Unexpected material after XDV name tree array.".into());
}
Value::Array(values) if values.len() % 2 == 0 => values,
Value::Array(_) => return Err("Array size not multiple of 2 for pdf:names.".into()),
Value::String(_) => vec![keys, parse_object(rest, position)?],
_ => return Err("Invalid object type for pdf:names.".into()),
};
let mut remaining = operands.into_iter();
let mut entries = Vec::new();
let mut problem = None;
while let Some(key) = remaining.next() {
let value = remaining.next().expect("paired name tree operands");
match key {
Value::String(key) if !key.is_empty() => entries.push((key, value)),
Value::String(_) => {
problem = Some("Null string used for name tree key.");
break;
}
_ => {
problem = Some("Name tree key must be string.");
break;
}
}
}
Ok((
Registration {
category,
order,
entries,
},
problem,
))
}
pub(super) fn warning(message: &str) -> String {
format!("xdvipdfmx: warning: {message}\n")
}
fn duplicate(key: &[u8]) -> String {
warning(&format!(
"Object @{} already defined.",
String::from_utf8_lossy(key)
))
}
fn export_key<'a>(
key: &'a [u8],
category: &[u8],
compacted: &'a BTreeMap<Vec<u8>, Vec<u8>>,
keep_destinations: bool,
) -> Option<&'a [u8]> {
if category == DESTS && !keep_destinations {
compacted.get(key).map(Vec::as_slice)
} else {
Some(key)
}
}
impl PreparedNames<'_> {
pub(crate) fn is_empty(&self) -> bool {
self.trees.values().all(BTreeMap::is_empty)
}
pub(crate) fn has_destination(&self, key: &[u8]) -> bool {
self.trees
.get(DESTS)
.is_some_and(|entries| entries.contains_key(key))
}
pub(crate) fn collect_references<'a>(
&self,
pending: &mut Vec<&'a [u8]>,
compacted: &BTreeMap<Vec<u8>, Vec<u8>>,
keep_destinations: bool,
) where
Self: 'a,
{
for (&category, entries) in &self.trees {
for (&key, &value) in entries {
if export_key(key, category, compacted, keep_destinations).is_some() {
value.collect_references(pending);
}
}
}
}
pub(crate) fn write(
&self,
positioned: BTreeMap<&[u8], String>,
compacted: &BTreeMap<Vec<u8>, Vec<u8>>,
keep_destinations: bool,
references: &References<'_>,
objects: &mut Vec<Vec<u8>>,
) -> Result<PdfDictionary, String> {
let mut trees = BTreeMap::<&[u8], BTreeMap<&[u8], Object>>::new();
for (&category, entries) in &self.trees {
let tree = trees.entry(category).or_default();
for (&key, &value) in entries {
if let Some(key) = export_key(key, category, compacted, keep_destinations) {
tree.insert(key, value.output(references)?);
}
}
}
for (key, value) in positioned {
let tree = trees.entry(DESTS).or_default();
if let Entry::Vacant(entry) = tree.entry(key) {
entry.insert(parse_value(value.as_bytes())?);
}
}
let mut output = PdfDictionary::new();
for (category, entries) in trees {
if !entries.is_empty() {
let mut entries: Vec<_> = entries.into_iter().collect();
for (_, value) in &mut entries {
if matches!(
value,
Object::Array(_) | Object::Dictionary(_) | Object::String(..)
) {
*value = push_object(objects, std::mem::replace(value, Object::Null))?;
}
}
output.set(category.to_vec(), write_node(objects, &entries, true)?);
}
}
Ok(output)
}
}
fn key(value: &[u8]) -> Object {
Object::String(value.to_vec(), StringFormat::Hexadecimal)
}
fn push_object(objects: &mut Vec<Vec<u8>>, object: Object) -> Result<Object, String> {
objects.push(encode_device_value(object)?);
let id = u32::try_from(objects.len()).map_err(|_| "XDV PDF object ID out of range")?;
Ok(Object::Reference((id, 0)))
}
fn write_node(
objects: &mut Vec<Vec<u8>>,
entries: &[(&[u8], Object)],
root: bool,
) -> Result<Object, String> {
let mut node = PdfDictionary::new();
if !root {
node.set(
"Limits",
Object::Array(vec![key(entries[0].0), key(entries.last().unwrap().0)]),
);
}
if entries.len() <= LEAF_SIZE {
let names = entries
.iter()
.flat_map(|(name, value)| [key(name), value.clone()])
.collect();
node.set("Names", Object::Array(names));
} else {
let mut kids = Vec::with_capacity(BRANCHES);
for i in 0..BRANCHES {
let range = (i * entries.len() / BRANCHES)..((i + 1) * entries.len() / BRANCHES);
kids.push(write_node(objects, &entries[range], false)?);
}
node.set("Kids", Object::Array(kids));
}
push_object(objects, Object::Dictionary(node))
}
@@ -120,12 +120,13 @@ impl ObjectCommand {
let Self { name, change } = self;
let display = String::from_utf8_lossy(&name);
let warning = |message: String| vec![format!("xdvipdfmx: warning: {message}\n")];
if matches!(name.as_slice(), b"catalog" | b"pages" | b"thispage")
if matches!(name.as_slice(), b"catalog" | b"pages" | b"thispage" | b"names")
&& let Change::Put(values) = change
{
let fields = match name.as_slice() {
b"catalog" => &mut navigation.catalog,
b"pages" => &mut navigation.page_dictionaries.root,
b"names" => navigation.names_root.get_or_insert_with(Default::default),
_ => navigation.page_dictionaries.pages.entry(page).or_default(),
};
fields.append(&mut only_dictionary(values)?);
@@ -139,7 +139,7 @@ impl Position {
b"@pages" => Ok(Value::PageTree),
b"@prevpage" => self.page.checked_sub(1).filter(|page| *page > 0)
.map(Value::Page).ok_or_else(|| "XDV has no previous page".into()),
b"@names" | b"@resources" | b"@docinfo" => Err(format!(
b"@resources" | b"@docinfo" => Err(format!(
"unsupported XDV PDF device reference {}",
String::from_utf8_lossy(token)
)),