Ship XDV annotations from measured page ranges

This commit is contained in:
gloamxun committed 2026-11-25 21:12:44 +08:00
1 parent 515dbe6181
commit 20986b2fd5
16 files changed
+873 -54

No files matched your search

@@ -103,10 +103,15 @@ pub struct PageLinks {
pub destinations: Vec<PageDestination>,
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub(crate) xdv_destinations: Vec<super::xdv_destination::Destination>,
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub(crate) xdv_annotations: Vec<super::xdv_annotation::Annotation>,
}
impl PageLinks {
pub(crate) fn is_empty(&self) -> bool {
self.annotations.is_empty() && self.destinations.is_empty() && self.xdv_destinations.is_empty()
self.annotations.is_empty()
&& self.destinations.is_empty()
&& self.xdv_destinations.is_empty()
&& self.xdv_annotations.is_empty()
}
}
@@ -0,0 +1,339 @@
//! Link and explicit annotation geometry produced by the XDV page device.
use std::{collections::BTreeMap, sync::Arc};
use lopdf::Object;
use super::xdv_navigation::read_fields;
use super::xdv_object::{
Dictionary, Position, atom, encode_device_value, output_with_destination, target_name, trim_pdf,
};
use super::{Affine, xdv_image};
pub(crate) type Order = (usize, usize, u8);
#[derive(Clone, Copy)]
pub(crate) enum Command {
Begin,
End,
Expand,
Explicit,
Link(bool),
}
impl Command {
pub(crate) fn recognize(input: &[u8]) -> Option<(Self, &[u8])> {
let body = trim_pdf(input).strip_prefix(b"pdf:").map(trim_pdf)?;
let (word, rest) = atom(body);
let command = match word {
b"bannot" | b"beginann" | b"bann" => Self::Begin,
b"eannot" | b"endann" | b"eann" => Self::End,
b"xannot" | b"extendann" | b"xann" => Self::Expand,
b"annotation" | b"annotate" | b"annot" | b"ann" => Self::Explicit,
b"link" => Self::Link(true),
b"nolink" => Self::Link(false),
_ => return None,
};
Some((command, trim_pdf(rest)))
}
}
#[derive(Clone, Debug, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
pub(crate) struct Annotation {
pub(crate) order: Order,
fields: Arc<Dictionary>,
/// Physical PDF coordinates in thousandths of a big point.
rect: [i64; 4],
}
impl Annotation {
pub(crate) fn named_reference(&self) -> Option<(Order, &[u8])> {
target_name(&self.fields).map(|name| (self.order, name))
}
pub(crate) fn pdf(
&self,
pages: &[usize],
names: &BTreeMap<Vec<u8>, Vec<u8>>,
) -> Result<Vec<u8>, String> {
let mut dictionary = output_with_destination(&self.fields, pages, names)?;
dictionary.set(
"Rect",
Object::Array(
self.rect
.map(|value| Object::Real(value as f64 / 1000.0))
.to_vec(),
),
);
encode_device_value(Object::Dictionary(dictionary))
}
}
#[derive(Clone)]
struct Active {
fields: Arc<Dictionary>,
depth: usize,
}
#[derive(Clone)]
pub(crate) struct AnnotationState {
active: Option<Active>,
bounds: Option<Bounds>,
enabled: bool,
}
impl Default for AnnotationState {
fn default() -> Self {
Self {
active: None,
bounds: None,
enabled: true,
}
}
}
impl AnnotationState {
pub(crate) fn is_active(&self) -> bool {
self.active.is_some()
}
pub(crate) fn page(&mut self) -> Page<'_> {
Page {
state: self,
depth: 0,
annotations: Vec::new(),
}
}
}
pub(crate) struct Page<'a> {
state: &'a mut AnnotationState,
depth: usize,
annotations: Vec<Annotation>,
}
impl Page<'_> {
pub(crate) fn tracking(&self) -> bool {
self.state.enabled
&& self
.state
.active
.as_ref()
.is_some_and(|active| self.depth >= active.depth)
}
pub(crate) fn enter(&mut self, depth: usize) {
self.depth = depth;
}
pub(crate) fn leave(&mut self, depth: usize, order: Order) {
if depth != 0
&& self.state.enabled
&& self
.state
.active
.as_ref()
.is_some_and(|active| active.depth == depth)
{
self.flush(order);
}
self.depth = depth.saturating_sub(1);
}
pub(crate) fn apply(
&mut self,
command: Command,
operands: &[u8],
point: [f64; 2],
transform: Affine,
position: Position,
order: Order,
) -> Result<Vec<String>, String> {
match command {
Command::Begin => {
if self.state.active.is_some() {
return Ok(vec![
"xdvipdfmx: warning: Can't begin an annotation when one is pending.\n"
.into(),
]);
}
let (fields, warnings) = read_fields(operands, position)?;
self.state.active = Some(Active {
fields: Arc::new(fields),
depth: self.depth,
});
Ok(warnings)
}
Command::End => {
if self.state.active.is_none() {
return Ok(vec![
"xdvipdfmx: warning: Tried to end an annotation without starting one!\n"
.into(),
]);
}
self.flush(order);
self.state.active = None;
Ok(Vec::new())
}
Command::Expand if !self.tracking() => Ok(Vec::new()),
Command::Expand | Command::Explicit => {
let dictionary = operands
.windows(2)
.position(|window| window == b"<<")
.unwrap_or(operands.len());
let bounds = Dimensions::read(&operands[..dictionary], position.magnification)?
.bounds(point, transform, position);
if matches!(command, Command::Expand) {
self.expand(bounds);
return Ok(Vec::new());
}
let (fields, warnings) = read_fields(&operands[dictionary..], position)?;
self.annotations.push(Annotation {
order,
fields: Arc::new(fields),
rect: bounds.quantized(),
});
Ok(warnings)
}
Command::Link(enabled) => {
self.state.enabled = enabled;
Ok(Vec::new())
}
}
}
pub(crate) fn expand(&mut self, bounds: Bounds) {
self.state.bounds = Some(self.state.bounds.map_or(bounds, |old| old.union(bounds)));
}
fn flush(&mut self, order: Order) {
if let Some(bounds) = self.state.bounds.take()
&& let Some(active) = &self.state.active
{
self.annotations.push(Annotation {
order,
fields: active.fields.clone(),
rect: bounds.quantized(),
});
}
}
pub(crate) fn finish(self) -> Vec<Annotation> {
self.annotations
}
}
#[derive(Clone, Copy)]
pub(crate) struct Bounds([f64; 4]);
impl Bounds {
pub(crate) fn from_logical(
[left, top, right, bottom]: [f64; 4],
transform: Affine,
height: i64,
magnification: i32,
) -> Self {
Self::from_corners(
[[left, top], [right, top], [left, bottom], [right, bottom]],
transform,
height,
magnification,
)
}
pub(crate) fn from_corners(
corners: [[f64; 2]; 4],
transform: Affine,
height: i64,
magnification: i32,
) -> Self {
let scale = bp_per_sp(magnification);
let mut bounds = [
f64::INFINITY,
f64::INFINITY,
f64::NEG_INFINITY,
f64::NEG_INFINITY,
];
for [x, y] in corners {
let [x, y] = transform.point(x, y);
let [x, y] = [x * scale, (height as f64 - y) * scale];
bounds = [
bounds[0].min(x),
bounds[1].min(y),
bounds[2].max(x),
bounds[3].max(y),
];
}
Self(bounds)
}
fn union(self, other: Self) -> Self {
let [a, b, c, d] = self.0;
let [x, y, u, v] = other.0;
Self([a.min(x), b.min(y), c.max(u), d.max(v)])
}
fn quantized(self) -> [i64; 4] {
self.0.map(|value| (value * 1000.0).round() as i64)
}
}
fn bp_per_sp(magnification: i32) -> f64 {
f64::from(magnification) / 1000.0 * (800.0 / 803.0) / 65536.0
}
#[derive(Default)]
struct Dimensions {
sizes: [Option<f64>; 3],
bbox: Option<[f64; 4]>,
}
impl Dimensions {
fn read(operands: &[u8], magnification: i32) -> Result<Self, String> {
let text =
std::str::from_utf8(operands).map_err(|_| "invalid XDV annotation dimensions")?;
let mut words = text.split_ascii_whitespace().peekable();
let mut dimensions = Self::default();
while let Some(command) = words.next() {
match command {
"width" => {
dimensions.sizes[0] = Some(xdv_image::length(&mut words, magnification)?)
}
"height" => {
dimensions.sizes[1] = Some(xdv_image::length(&mut words, magnification)?)
}
"depth" => {
dimensions.sizes[2] = Some(xdv_image::length(&mut words, magnification)?)
}
"bbox" => {
let mut bounds = [0.0; 4];
for value in &mut bounds {
*value = xdv_image::number(words.next())?;
}
dimensions.bbox = Some(bounds);
}
_ => return Err(format!("unsupported XDV annotation dimension {command}")),
}
}
if dimensions.bbox.is_some() && dimensions.sizes.iter().any(Option::is_some) {
return Err("XDV annotation bbox conflicts with width, height or depth".into());
}
Ok(dimensions)
}
fn bounds(self, [x, y]: [f64; 2], transform: Affine, position: Position) -> Bounds {
let [left, bottom, right, top] = if let Some(bbox) = self.bbox {
bbox.map(|value| value / bp_per_sp(position.magnification))
} else {
let [width, height, depth] = self
.sizes
.map(|value| value.unwrap_or_default() / bp_per_sp(1000));
[0.0, -depth, width, height]
};
Bounds::from_logical(
[x + left, y - top, x + right, y - bottom],
transform,
position.height,
position.magnification,
)
}
}
@@ -191,23 +191,25 @@ impl ImageSpecial {
-left * width / natural_w,
-bottom * height / natural_h - depth,
]);
let clip = (self.clip && self.bbox.is_some()).then_some([
let annotation_box = self.bbox.is_some().then_some([
left / natural_w,
bottom / natural_h,
box_w / natural_w,
box_h / natural_h,
]);
PdfImageUse::new_xdv_raster_special(id, image, self.transform.concatenate(sizing), clip)
PdfImageUse::new_xdv_raster_special(
id, image, self.transform.concatenate(sizing), annotation_box, self.clip,
)
}
}
fn number(word: Option<&str>) -> Result<f64, &'static str> {
pub(super) fn number(word: Option<&str>) -> Result<f64, &'static str> {
word.and_then(|word| word.parse::<f64>().ok())
.filter(|value| value.is_finite())
.ok_or("invalid XDV image number")
}
fn length(
pub(super) fn length(
words: &mut Peekable<SplitAsciiWhitespace<'_>>,
magnification: i32,
) -> Result<f64, &'static str> {
@@ -4,9 +4,11 @@ use std::collections::BTreeMap;
use lopdf::Object;
use serde::{Deserialize, Serialize};
use super::page_resources::{encode_value, parse_value};
use super::page_resources::parse_value;
use super::xdv_annotation::Order;
use super::xdv_object::{
Dictionary, Position, Value, atom, dictionary, output_dictionary, trim_pdf,
Dictionary, Position, Value, atom, dictionary, encode_device_value, output_dictionary,
output_with_destination, target_name, trim_pdf,
};
#[derive(Clone, Debug, Default, PartialEq, Eq, Hash, Serialize, Deserialize)]
@@ -19,6 +21,7 @@ pub(crate) struct Navigation {
#[derive(Clone, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)]
struct Outline {
order: Order,
depth: usize,
force_open: bool,
fields: Dictionary,
@@ -48,6 +51,7 @@ impl Navigation {
&mut self,
bytes: &[u8],
position: Position,
order: Order,
limit: usize,
) -> Result<Vec<String>, String> {
let (force_open, rest) = match trim_pdf(bytes) {
@@ -72,6 +76,7 @@ impl Navigation {
self.add_payload(bytes.len(), limit)?;
self.lowest_level = Some(lowest);
self.outlines.push(Outline {
order,
depth: depth as usize,
force_open,
fields,
@@ -108,19 +113,24 @@ impl Navigation {
_ => catalog.set(key.clone(), value.clone()),
}
}
encode_value(Object::Dictionary(catalog))
encode_device_value(Object::Dictionary(catalog))
}
pub(crate) fn named_references(&self) -> impl Iterator<Item = (Order, &[u8])> {
self.outlines
.iter()
.filter_map(|outline| target_name(&outline.fields).map(|name| (outline.order, name)))
}
pub(crate) fn write_outlines(
&self,
pages: &[usize],
objects: &mut Vec<Vec<u8>>,
keep_destinations: bool,
names: &BTreeMap<Vec<u8>, Vec<u8>>,
open_depth: usize,
) -> Result<(Option<usize>, BTreeMap<Vec<u8>, Vec<u8>>), String> {
let mut names = BTreeMap::new();
) -> Result<Option<usize>, String> {
if self.outlines.is_empty() {
return Ok((None, names));
return Ok(None);
}
let root = objects.len() + 1;
let mut entries: Vec<_> = (0..=self.outlines.len())
@@ -168,13 +178,10 @@ impl Navigation {
let mut fields = lopdf::Dictionary::new();
links(&mut fields, &entries[0]);
fields.set("Count", entries[0].count);
objects.push(encode_value(Object::Dictionary(fields))?);
objects.push(encode_device_value(Object::Dictionary(fields))?);
for (offset, outline) in self.outlines.iter().enumerate() {
let entry = &entries[offset + 1];
let mut fields = output_dictionary(&outline.fields, pages)?;
if !keep_destinations {
remap_outline_destination(&mut fields, &mut names);
}
let mut fields = output_with_destination(&outline.fields, pages, names)?;
fields.set("Parent", object(entry.parent));
for field in [b"Prev".as_slice(), b"Next", b"First", b"Last", b"Count"] {
fields.remove(field);
@@ -188,9 +195,9 @@ impl Navigation {
};
fields.set("Count", sign * entry.count);
}
objects.push(encode_value(Object::Dictionary(fields))?);
objects.push(encode_device_value(Object::Dictionary(fields))?);
}
Ok((Some(root), names))
Ok(Some(root))
}
}
@@ -204,7 +211,10 @@ struct OutlineLinks {
count: i64,
}
fn read_fields(bytes: &[u8], position: Position) -> Result<(Dictionary, Vec<String>), String> {
pub(super) fn read_fields(
bytes: &[u8],
position: Position,
) -> Result<(Dictionary, Vec<String>), String> {
let mut fields = dictionary(bytes, position)?;
let mut warnings = Vec::new();
for (key, value) in &mut fields {
@@ -212,26 +222,3 @@ fn read_fields(bytes: &[u8], position: Position) -> Result<(Dictionary, Vec<Stri
}
Ok((fields, warnings))
}
fn remap_outline_destination(
fields: &mut lopdf::Dictionary,
names: &mut BTreeMap<Vec<u8>, Vec<u8>>,
) {
let named = if fields.has(b"Dest") && !fields.has(b"A") {
fields.get_mut(b"Dest").ok()
} else if !fields.has(b"Dest")
&& let Ok(Object::Dictionary(action)) = fields.get_mut(b"A")
&& action.get(b"S").ok().and_then(|kind| kind.as_name().ok()) == Some(b"GoTo".as_slice())
{
action.get_mut(b"D").ok()
} else {
None
};
if let Some(Object::String(name, _)) = named {
let index = names.len();
*name = names
.entry(name.clone())
.or_insert_with(|| format!("{index:x}").into_bytes())
.clone();
}
}
@@ -1,9 +1,9 @@
//! PDF objects in XDV specials, including typed references to shipped pages.
use lopdf::{Object, StringFormat};
use serde::{Deserialize, Serialize};
use std::collections::BTreeMap;
use std::{collections::BTreeMap, io::Write as _};
use super::page_resources::{parse_name, parse_value};
use super::page_resources::{encode_value, parse_name, parse_value};
use super::{magnify, print_sp};
pub(super) fn trim_pdf(mut bytes: &[u8]) -> &[u8] {
@@ -268,3 +268,76 @@ impl Value {
}
}
}
/// Return a local string destination, shared by bookmark and link export.
pub(super) fn target_name(fields: &Dictionary) -> Option<&[u8]> {
if fields
.get(b"Subtype".as_slice())
.is_some_and(|subtype| !matches!(subtype, Value::Name(name) if name == b"Link"))
{
return None;
}
let target = match (fields.get(b"Dest".as_slice()), fields.get(b"A".as_slice())) {
(Some(target), None) => Some(target),
(None, Some(Value::Dictionary(action))) if matches!(action.get(b"S".as_slice()), Some(Value::Name(name)) if name == b"GoTo") => {
action.get(b"D".as_slice())
}
_ => None,
};
if let Some(Value::String(name)) = target {
Some(name)
} else {
None
}
}
pub(super) fn output_with_destination(
fields: &Dictionary,
pages: &[usize],
names: &BTreeMap<Vec<u8>, Vec<u8>>,
) -> Result<lopdf::Dictionary, String> {
let mut dictionary = output_dictionary(fields, pages)?;
if let Some(compact) = target_name(fields).and_then(|name| names.get(name)) {
let compact = Object::String(compact.clone(), StringFormat::Hexadecimal);
if dictionary.has(b"Dest") {
dictionary.set("Dest", compact);
} else if let Ok(Object::Dictionary(action)) = dictionary.get_mut(b"A") {
action.set("D", compact);
}
}
Ok(dictionary)
}
/// The shared resource encoder limits real numbers to two fractional digits.
/// XDV geometry and caller-provided PDF objects require their full precision.
pub(super) fn encode_device_value(object: Object) -> Result<Vec<u8>, String> {
fn append(bytes: &mut Vec<u8>, object: Object) -> Result<(), String> {
match object {
Object::Real(value) if value.is_finite() => write!(bytes, "{value}").unwrap(),
Object::Real(_) => return Err("non-finite number in XDV PDF object".into()),
Object::Array(values) => {
bytes.push(b'[');
for value in values {
append(bytes, value)?;
bytes.push(b' ');
}
bytes.push(b']');
}
Object::Dictionary(entries) => {
bytes.extend_from_slice(b"<<");
for (name, value) in &entries {
bytes.extend(encode_value(Object::Name(name.clone()))?);
bytes.push(b' ');
append(bytes, value.clone())?;
bytes.push(b' ');
}
bytes.extend_from_slice(b">>");
}
_ => bytes.extend(encode_value(object)?),
}
Ok(())
}
let mut bytes = Vec::new();
append(&mut bytes, object)?;
Ok(bytes)
}