Write XeLaTeX document name trees and attachments
This commit is contained in:
1 parent
d627614af8
commit
dcc6a3984c
9 files changed
+446
-14
No files matched your search
@@ -65,7 +65,7 @@ impl Executor {
|
|||||||
};
|
};
|
||||||
if kind == b"dest" {
|
if kind == b"dest" {
|
||||||
let destination = crate::pdf_device::xdv_destination::Destination::parse(
|
let destination = crate::pdf_device::xdv_destination::Destination::parse(
|
||||||
operands, position.page, position.coordinates,
|
operands, position.page, position.coordinates, (position.page, graphics_step, 1),
|
||||||
).map_err(|error| self.error(error, special.span))?;
|
).map_err(|error| self.error(error, special.span))?;
|
||||||
links.xdv_destinations.push(destination);
|
links.xdv_destinations.push(destination);
|
||||||
return Ok(None);
|
return Ok(None);
|
||||||
@@ -79,12 +79,14 @@ impl Executor {
|
|||||||
.map_err(|error| self.error(error, special.span))?;
|
.map_err(|error| self.error(error, special.span))?;
|
||||||
graphics = Some(operation);
|
graphics = Some(operation);
|
||||||
Ok(warnings)
|
Ok(warnings)
|
||||||
} else if matches!(kind, b"docview" | b"outline" | b"pageresources") {
|
} else if matches!(kind, b"docview" | b"outline" | b"pageresources" | b"names") {
|
||||||
let navigation = Arc::make_mut(self.state.xdv_navigation.get_or_insert_with(Default::default));
|
let navigation = Arc::make_mut(self.state.xdv_navigation.get_or_insert_with(Default::default));
|
||||||
if kind == b"docview" {
|
if kind == b"docview" {
|
||||||
navigation.merge_catalog(operands, position, self.limits.tokens)
|
navigation.merge_catalog(operands, position, self.limits.tokens)
|
||||||
} else if kind == b"outline" {
|
} else if kind == b"outline" {
|
||||||
navigation.add_outline(operands, position, (position.page, graphics_step, 1), self.limits.tokens)
|
navigation.add_outline(operands, position, (position.page, graphics_step, 1), self.limits.tokens)
|
||||||
|
} else if kind == b"names" {
|
||||||
|
navigation.add_names(operands, position, (position.page, graphics_step, 1), self.limits.tokens)
|
||||||
} else {
|
} else {
|
||||||
navigation.set_page_resources(operands, position, self.limits.tokens)
|
navigation.set_page_resources(operands, position, self.limits.tokens)
|
||||||
}
|
}
|
||||||
@@ -367,6 +369,7 @@ pub(super) fn xdv_navigation_operand(data: &[u8]) -> Option<(&'static [u8], &[u8
|
|||||||
(b"docview", b"docview"), (b"outline", b"outline"), (b"out", b"outline"),
|
(b"docview", b"docview"), (b"outline", b"outline"), (b"out", b"outline"),
|
||||||
(b"obj", b"obj"), (b"object", b"obj"), (b"put", b"put"), (b"close", b"close"),
|
(b"obj", b"obj"), (b"object", b"obj"), (b"put", b"put"), (b"close", b"close"),
|
||||||
(b"stream", b"stream"), (b"fstream", b"fstream"), (b"pageresources", b"pageresources"),
|
(b"stream", b"stream"), (b"fstream", b"fstream"), (b"pageresources", b"pageresources"),
|
||||||
|
(b"names", b"names"),
|
||||||
(b"bxobj", b"bxobj"), (b"bform", b"bxobj"), (b"beginxobj", b"bxobj"),
|
(b"bxobj", b"bxobj"), (b"bform", b"bxobj"), (b"beginxobj", b"bxobj"),
|
||||||
(b"exobj", b"exobj"), (b"eform", b"exobj"), (b"endxobj", b"exobj"),
|
(b"exobj", b"exobj"), (b"eform", b"exobj"), (b"endxobj", b"exobj"),
|
||||||
(b"uxobj", b"uxobj"), (b"usexobj", b"uxobj"),
|
(b"uxobj", b"uxobj"), (b"usexobj", b"uxobj"),
|
||||||
|
|||||||
@@ -3610,16 +3610,31 @@ fn write_pdf(
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
for name in xdv_names.keys() {
|
|
||||||
if !xdv_destinations.contains_key(name.as_slice()) {
|
|
||||||
diagnostics.push(format!("xdvipdfmx: warning: PDF destination {:?} not defined.",
|
|
||||||
String::from_utf8_lossy(name)));
|
|
||||||
}
|
|
||||||
}
|
|
||||||
let empty_xdv = crate::pdf_device::xdv_navigation::Navigation::default();
|
let empty_xdv = crate::pdf_device::xdv_navigation::Navigation::default();
|
||||||
let xdv_objects = xdv.unwrap_or(&empty_xdv);
|
let xdv_objects = xdv.unwrap_or(&empty_xdv);
|
||||||
|
let declared_names = xdv_objects.prepare_names(
|
||||||
|
|key| xdv_destinations.get(key).map(|(destination, _, _)| destination.order),
|
||||||
|
diagnostics,
|
||||||
|
);
|
||||||
|
xdv_destinations.retain(|key, _| {
|
||||||
|
if declared_names.has_destination(key) {
|
||||||
|
diagnostics.push(format!(
|
||||||
|
"xdvipdfmx: warning: Object @{} already defined.",
|
||||||
|
String::from_utf8_lossy(key),
|
||||||
|
));
|
||||||
|
false
|
||||||
|
} else {
|
||||||
|
true
|
||||||
|
}
|
||||||
|
});
|
||||||
|
for name in xdv_names.keys() {
|
||||||
|
if !xdv_destinations.contains_key(name.as_slice()) && !declared_names.has_destination(name) {
|
||||||
|
diagnostics.push(format!("xdvipdfmx: warning: PDF destination {:?} not defined.", String::from_utf8_lossy(name)));
|
||||||
|
}
|
||||||
|
}
|
||||||
let mut pending = Vec::new();
|
let mut pending = Vec::new();
|
||||||
xdv_objects.collect_references(&mut pending);
|
xdv_objects.collect_references(&mut pending);
|
||||||
|
declared_names.collect_references(&mut pending, &xdv_names, keep_xdv_destinations);
|
||||||
for (_, annotation) in &xdv_annotations {
|
for (_, annotation) in &xdv_annotations {
|
||||||
annotation.collect_references(&mut pending);
|
annotation.collect_references(&mut pending);
|
||||||
}
|
}
|
||||||
@@ -3678,7 +3693,12 @@ fn write_pdf(
|
|||||||
.ok_or_else(|| format!("XDV destination refers to nonexistent page {}", destination.page))?;
|
.ok_or_else(|| format!("XDV destination refers to nonexistent page {}", destination.page))?;
|
||||||
retained.insert(name, destination.array(*page_object, height, magnification, &references)?);
|
retained.insert(name, destination.array(*page_object, height, magnification, &references)?);
|
||||||
}
|
}
|
||||||
if !retained.is_empty() {
|
let mut generated_names = lopdf::Dictionary::new();
|
||||||
|
if !declared_names.is_empty() {
|
||||||
|
generated_names = declared_names.write(
|
||||||
|
retained, &xdv_names, keep_xdv_destinations, &references, &mut objects,
|
||||||
|
)?;
|
||||||
|
} else if !retained.is_empty() {
|
||||||
let entries: Vec<_> = retained.into_iter().map(|(name, value)| {
|
let entries: Vec<_> = retained.into_iter().map(|(name, value)| {
|
||||||
let name = format!("<{}>", name.iter().map(|byte| format!("{byte:02X}")).collect::<String>());
|
let name = format!("<{}>", name.iter().map(|byte| format!("{byte:02X}")).collect::<String>());
|
||||||
(name, value)
|
(name, value)
|
||||||
@@ -3706,7 +3726,7 @@ fn write_pdf(
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
objects[0] = if let Some(xdv) = xdv {
|
objects[0] = if let Some(xdv) = xdv {
|
||||||
xdv.finish_catalog(&catalog, &references)?
|
xdv.finish_catalog(&catalog, &references, generated_names, &mut objects, diagnostics)?
|
||||||
} else {
|
} else {
|
||||||
let mut catalog = catalog.into_bytes();
|
let mut catalog = catalog.into_bytes();
|
||||||
if let Some(extra) = extra {
|
if let Some(extra) = extra {
|
||||||
|
|||||||
@@ -102,6 +102,8 @@ impl Setup {
|
|||||||
pub(crate) struct Destination {
|
pub(crate) struct Destination {
|
||||||
pub(crate) name: Vec<u8>,
|
pub(crate) name: Vec<u8>,
|
||||||
pub(crate) page: usize,
|
pub(crate) page: usize,
|
||||||
|
#[serde(default)]
|
||||||
|
pub(crate) order: super::xdv_annotation::Order,
|
||||||
view: String,
|
view: String,
|
||||||
operands: Vec<Operand>,
|
operands: Vec<Operand>,
|
||||||
point: [i64; 2],
|
point: [i64; 2],
|
||||||
@@ -121,6 +123,7 @@ impl Destination {
|
|||||||
input: &[u8],
|
input: &[u8],
|
||||||
current_page: usize,
|
current_page: usize,
|
||||||
point: [i64; 2],
|
point: [i64; 2],
|
||||||
|
order: super::xdv_annotation::Order,
|
||||||
) -> Result<Self, String> {
|
) -> Result<Self, String> {
|
||||||
let (name, rest) = split_string(trim_pdf(input))?;
|
let (name, rest) = split_string(trim_pdf(input))?;
|
||||||
let Object::String(name, _) = parse_value(name)? else {
|
let Object::String(name, _) = parse_value(name)? else {
|
||||||
@@ -176,6 +179,7 @@ impl Destination {
|
|||||||
Ok(Self {
|
Ok(Self {
|
||||||
name,
|
name,
|
||||||
page,
|
page,
|
||||||
|
order,
|
||||||
view,
|
view,
|
||||||
operands,
|
operands,
|
||||||
point,
|
point,
|
||||||
|
|||||||
@@ -12,6 +12,7 @@ use super::xdv_object::{
|
|||||||
};
|
};
|
||||||
|
|
||||||
mod named_objects;
|
mod named_objects;
|
||||||
|
mod name_trees;
|
||||||
mod page_dictionaries;
|
mod page_dictionaries;
|
||||||
mod page_resources;
|
mod page_resources;
|
||||||
mod forms;
|
mod forms;
|
||||||
@@ -37,6 +38,10 @@ pub(crate) struct Navigation {
|
|||||||
page_resources: PageResources,
|
page_resources: PageResources,
|
||||||
#[serde(default, skip_serializing_if = "Forms::is_empty")]
|
#[serde(default, skip_serializing_if = "Forms::is_empty")]
|
||||||
forms: Forms,
|
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)]
|
#[derive(Clone, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)]
|
||||||
@@ -130,6 +135,9 @@ impl Navigation {
|
|||||||
self.page_dictionaries.collect_references(pending);
|
self.page_dictionaries.collect_references(pending);
|
||||||
self.page_resources.collect_references(pending);
|
self.page_resources.collect_references(pending);
|
||||||
self.forms.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>(
|
pub(crate) fn reserve_objects<'a>(
|
||||||
@@ -162,7 +170,7 @@ impl Navigation {
|
|||||||
diagnostics: &mut Vec<String>,
|
diagnostics: &mut Vec<String>,
|
||||||
) -> Result<(), String> {
|
) -> Result<(), String> {
|
||||||
for (name, &id) in references.named {
|
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;
|
continue;
|
||||||
}
|
}
|
||||||
objects[id as usize - 1] = if let Some(object) = self.objects.get(name) {
|
objects[id as usize - 1] = if let Some(object) = self.objects.get(name) {
|
||||||
@@ -178,15 +186,25 @@ impl Navigation {
|
|||||||
Ok(())
|
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 {
|
let Object::Dictionary(mut catalog) = parse_value(format!("{base} >>").as_bytes())? else {
|
||||||
unreachable!("native PDF catalog is a dictionary");
|
unreachable!("native PDF catalog is a dictionary");
|
||||||
};
|
};
|
||||||
let additions = output_dictionary(&self.catalog, references)?;
|
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 {
|
for (key, value) in &additions {
|
||||||
match key.as_slice() {
|
match key.as_slice() {
|
||||||
b"Type" | b"Pages" => {}
|
b"Type" | b"Pages" => {}
|
||||||
b"Outlines" | b"Threads" if catalog.has(key) => {}
|
b"Outlines" | b"Threads" if catalog.has(key) => {}
|
||||||
|
b"Names" if has_name_root => {}
|
||||||
b"Names" if catalog.has(key) => {
|
b"Names" if catalog.has(key) => {
|
||||||
if let (Ok(Object::Dictionary(generated)), Object::Dictionary(extra)) =
|
if let (Ok(Object::Dictionary(generated)), Object::Dictionary(extra)) =
|
||||||
(catalog.get_mut(key), value)
|
(catalog.get_mut(key), value)
|
||||||
@@ -199,6 +217,44 @@ impl Navigation {
|
|||||||
_ => catalog.set(key.clone(), value.clone()),
|
_ => 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))
|
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 ®istration.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 Self { name, change } = self;
|
||||||
let display = String::from_utf8_lossy(&name);
|
let display = String::from_utf8_lossy(&name);
|
||||||
let warning = |message: String| vec![format!("xdvipdfmx: warning: {message}\n")];
|
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 Change::Put(values) = change
|
||||||
{
|
{
|
||||||
let fields = match name.as_slice() {
|
let fields = match name.as_slice() {
|
||||||
b"catalog" => &mut navigation.catalog,
|
b"catalog" => &mut navigation.catalog,
|
||||||
b"pages" => &mut navigation.page_dictionaries.root,
|
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(),
|
_ => navigation.page_dictionaries.pages.entry(page).or_default(),
|
||||||
};
|
};
|
||||||
fields.append(&mut only_dictionary(values)?);
|
fields.append(&mut only_dictionary(values)?);
|
||||||
|
|||||||
@@ -139,7 +139,7 @@ impl Position {
|
|||||||
b"@pages" => Ok(Value::PageTree),
|
b"@pages" => Ok(Value::PageTree),
|
||||||
b"@prevpage" => self.page.checked_sub(1).filter(|page| *page > 0)
|
b"@prevpage" => self.page.checked_sub(1).filter(|page| *page > 0)
|
||||||
.map(Value::Page).ok_or_else(|| "XDV has no previous page".into()),
|
.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 {}",
|
"unsupported XDV PDF device reference {}",
|
||||||
String::from_utf8_lossy(token)
|
String::from_utf8_lossy(token)
|
||||||
)),
|
)),
|
||||||
|
|||||||
@@ -1204,3 +1204,57 @@ fn xdv_imported_image_matches_forward_catalog_and_page_references() {
|
|||||||
assert_eq!(pdf.get_object(stamp).unwrap().as_str().unwrap(), b"proof");
|
assert_eq!(pdf.get_object(stamp).unwrap().as_str().unwrap(), b"proof");
|
||||||
assert_eq!(form.dict.get(b"Subtype").unwrap().as_name().unwrap(), b"Form");
|
assert_eq!(form.dict.get(b"Subtype").unwrap().as_name().unwrap(), b"Form");
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn xdv_name_trees_keep_binary_keys_and_share_the_catalog_root() {
|
||||||
|
use lopdf::{Document, Object};
|
||||||
|
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
|
||||||
|
\shipout\hbox{%
|
||||||
|
\special{pdf:put @catalog << /Copy @names >>}%
|
||||||
|
\special{pdf:put @names << /Pages << /Names [(page) @nextpage] >> >>}%
|
||||||
|
\special{pdf:dest (mixed) [@thispage /FitH 55]}%
|
||||||
|
\special{pdf:names /Dests [(manual) [@nextpage /Fit] (mixed) [@nextpage /Fit] (unreached) [@nextpage /Fit]]}%
|
||||||
|
\special{pdf:ann width 5pt height 2pt << /Subtype /Link /Dest (manual) >>}%
|
||||||
|
\special{pdf:ann width 5pt height 2pt << /Subtype /Link /Dest (mixed) >>}%
|
||||||
|
\special{pdf:names /IDS [<ff> 9 (b) 8 (a) 7 <6100> 6 (c) 5 (d) 4 (e) 3 (f) 2 <00> 1]}%
|
||||||
|
\special{pdf:names /AP (first) @leaf}%
|
||||||
|
\vrule width5pt height3pt}
|
||||||
|
\shipout\hbox{\special{pdf:obj @leaf << /Proof (shared) >>}\vrule width5pt height3pt}
|
||||||
|
\end"),
|
||||||
|
&mut TestDevice,
|
||||||
|
).unwrap();
|
||||||
|
let pages = result.shipout_display_lists().unwrap();
|
||||||
|
let output = shipout_lists_to_native_pdf_document(&pages, result.state.pdf_final_options()).unwrap();
|
||||||
|
let pdf = Document::load_mem(&output.bytes).unwrap();
|
||||||
|
let resolve = |value: &Object| pdf.get_object(value.as_reference().unwrap()).unwrap();
|
||||||
|
let id = pdf.catalog().unwrap().get(b"Names").unwrap().as_reference().unwrap();
|
||||||
|
assert_eq!(pdf.catalog().unwrap().get(b"Copy").unwrap().as_reference().unwrap(), id);
|
||||||
|
let root = pdf.get_dictionary(id).unwrap();
|
||||||
|
let ids = resolve(root.get(b"IDS").unwrap()).as_dict().unwrap();
|
||||||
|
assert!(!ids.has(b"Limits"));
|
||||||
|
let children = ids.get(b"Kids").unwrap().as_array().unwrap();
|
||||||
|
let keys: Vec<_> = children.iter().flat_map(|child| {
|
||||||
|
let node = resolve(child).as_dict().unwrap();
|
||||||
|
let values = node.get(b"Names").unwrap().as_array().unwrap();
|
||||||
|
let limits = node.get(b"Limits").unwrap().as_array().unwrap();
|
||||||
|
assert_eq!(limits[0].as_str().unwrap(), values[0].as_str().unwrap());
|
||||||
|
assert_eq!(limits[1].as_str().unwrap(), values[values.len()-2].as_str().unwrap());
|
||||||
|
values.iter().step_by(2).map(|key| key.as_str().unwrap().to_vec())
|
||||||
|
}).collect();
|
||||||
|
assert_eq!(keys, [b"\0".as_slice(), b"a", b"a\0", b"b", b"c", b"d", b"e", b"f", b"\xff"]);
|
||||||
|
|
||||||
|
let pages = pdf.get_pages();
|
||||||
|
let dests = resolve(root.get(b"Dests").unwrap()).as_dict().unwrap()
|
||||||
|
.get(b"Names").unwrap().as_array().unwrap();
|
||||||
|
assert_eq!(dests.len(), 4);
|
||||||
|
assert_eq!(resolve(&dests[1]).as_array().unwrap()[0].as_reference().unwrap(), pages[&2]);
|
||||||
|
assert_eq!(resolve(&dests[3]).as_array().unwrap()[0].as_reference().unwrap(), pages[&1]);
|
||||||
|
let ap = resolve(root.get(b"AP").unwrap()).as_dict().unwrap()
|
||||||
|
.get(b"Names").unwrap().as_array().unwrap();
|
||||||
|
assert_eq!(resolve(&ap[1]).as_dict().unwrap().get(b"Proof").unwrap().as_str().unwrap(), b"shared");
|
||||||
|
assert!(output.diagnostics.iter().any(|message| message.contains("Object @mixed already defined.")));
|
||||||
|
}
|
||||||
@@ -18,6 +18,33 @@
|
|||||||
| W6 会话 | 实施中 | 共享库/CLI 与当前原生文字/数学/规则来源进入公共结果;真实 A4 副本九类/27 revision 与独立干净作业页面/PDF/aux/映射一致,新增数学场景独立参考通过;详细失败/捕获重放及宿主/离线/CLI观察已通过;原子项目版本/已知生成初态及TeX流记录已接通;完整副作用/恢复契约、旧来源和性能仍缺 |
|
| W6 会话 | 实施中 | 共享库/CLI 与当前原生文字/数学/规则来源进入公共结果;真实 A4 副本九类/27 revision 与独立干净作业页面/PDF/aux/映射一致,新增数学场景独立参考通过;详细失败/捕获重放及宿主/离线/CLI观察已通过;原子项目版本/已知生成初态及TeX流记录已接通;完整副作用/恢复契约、旧来源和性能仍缺 |
|
||||||
| W7 总验收 | 未满足 | 原有和新增测试、原样项目、格式与会话门禁全部通过才能结项 |
|
| W7 总验收 | 未满足 | 原有和新增测试、原样项目、格式与会话门禁全部通过才能结项 |
|
||||||
|
|
||||||
|
## 2026-11-28 XeLaTeX PDF 名称树与附件
|
||||||
|
|
||||||
|
`pdf:names` 接入原生出页,支持单个名称和成对数组。二进制键按
|
||||||
|
原始字节排序,多层树保存实际边界。目录、前向引用和 `@names`
|
||||||
|
共用同一对象。命名文件流保持引用身份,`pdf:dest` 和 `pdf:names`
|
||||||
|
共享跳转目标并按实际出页顺序处理重名。重名保留首个定义,
|
||||||
|
保留同批已接受条目。现有链接与书签继续决定本地目标的保留范围。
|
||||||
|
[参考名称树](https://raw.githubusercontent.com/TeX-Live/texlive-source/e49735c7ed1aa2ed9c2e68e6632d27f20d42eca7/texk/dvipdfm-x/pdfnames.c)
|
||||||
|
|
||||||
|
五组设备输入和原样 article.cls、hyperref.sty 共十页,144 DPI
|
||||||
|
彩色逐像素相同。44 个二进制键的多层树、键界、对象类型与
|
||||||
|
本地链接均与参考一致。四个附件均能提取且字节一致,article
|
||||||
|
的 aux 亦逐字节相同。开发构建和十二项定向回归通过。
|
||||||
|
|
||||||
|
三页会话改附件负载、改子文件中的键名、恢复资源时,每个成功
|
||||||
|
修订复用 144 步,保持页面绘制,更新最终 PDF,与独立全量的
|
||||||
|
PDF、测量页、SVG、来源映射和 aux 一致。附件缺失的修订保留
|
||||||
|
上次发布结果。
|
||||||
|
|
||||||
|
回执在 `target/p3-xdv-name-trees/receipt.json`,SHA-256 为
|
||||||
|
`3b366362fdc5f16ed300eef3e68eb22742d7e32a92982dde5c7d710177855bd7`。
|
||||||
|
下一批合并推进 `pdf:mapfile`、`pdf:mapline` 和字体资源失效。
|
||||||
|
直接对照位于 `target/p3-xdv-font-maps`,参考实际嵌入 CMR10,
|
||||||
|
原生当前停在 `pdf:mapfile`。使用已有原样项目定位组合缺口,
|
||||||
|
按功能批次构建并运行代表性检查。原样出版矩阵、W0–W7、
|
||||||
|
发布版整体验收和 100 ms 可见延迟门槛留在统一验收阶段。
|
||||||
|
|
||||||
## 2026-11-28 XeLaTeX 图形链接与设备坐标
|
## 2026-11-28 XeLaTeX 图形链接与设备坐标
|
||||||
|
|
||||||
出页时,图形链接从实际 XObject 放置获得注释范围。前向引用
|
出页时,图形链接从实际 XObject 放置获得注释范围。前向引用
|
||||||
|
|||||||
Reference in new issue
Block a user