Ship native PDF annotations with reserved object numbers

This commit is contained in:
gloamxun committed 2026-11-28 15:39:27 +08:00
1 parent 975dbc8060
commit de4bd1fa76
14 files changed
+299 -67

No files matched your search

@@ -1111,7 +1111,8 @@ impl NativeBox {
OutputOperation::Open { .. } | OutputOperation::Write { .. } | OutputOperation::Close { .. }))
&& !matches!(paint, BoxPaint::PdfLink(node, _) if matches!(
node.operation,
OutputOperation::PdfLink(crate::pdf_device::links::LinkNode::Destination { .. })
OutputOperation::PdfLink(crate::pdf_device::links::LinkNode::Destination { .. }
| crate::pdf_device::links::LinkNode::Annotation { .. })
))
{
emit(x, y, paint);
@@ -680,13 +680,28 @@ impl Printer<'_> {
use crate::pdf_device::links::LinkNode;
self.command(match node {
LinkNode::Start(_) => "pdfstartlink",
LinkNode::Annotation { .. } => "pdfannot",
LinkNode::End => "pdfendlink",
LinkNode::Running(false) => "pdfrunninglinkoff",
LinkNode::Running(true) => "pdfrunninglinkon",
LinkNode::Destination { .. } => "pdfdest",
});
if let LinkNode::Destination { structure: Some(object), .. } = node {
self.literal(&format!(" struct{object}"));
match node {
LinkNode::Annotation { dimensions: [width, height, depth], entries, .. } => {
for (separator, dimension) in [("(", height), ("+", depth), (")x", width)] {
self.literal(separator);
if let Some(value) = dimension {
self.number(i64::from(*value));
} else {
self.literal("*");
}
}
self.tokens(entries)?;
}
LinkNode::Destination { structure: Some(object), .. } => {
self.literal(&format!(" struct{object}"));
}
_ => {}
}
}
OutputOperation::PdfLiteral { mode, shipout, tokens } => {
@@ -2463,6 +2463,10 @@ impl Executor {
self.reads.insert(Dependency::PdfLastPosition);
Ok(self.state.pdf_last_position[usize::from(p == Primitive::Pdflastypos)])
}
Meaning::Primitive(Primitive::Pdflastannot) => {
self.reads.insert(Dependency::PdfObjects);
Ok(self.state.pdf_objects.as_deref().map_or(0, |objects| objects.last_annotation()))
}
Meaning::Primitive(Primitive::Pdflastlink) => {
self.reads.insert(Dependency::PdfObjects);
Ok(self
@@ -30,7 +30,7 @@ impl Executor {
Pdfsave | Pdfsetmatrix | Pdfrestore | Pdfliteral => {
self.scan_pdf_graphics(primitive, token.span, files)?
}
Pdfstartlink | Pdfendlink | Pdfdest | Pdfrunninglinkoff | Pdfrunninglinkon => {
Pdfannot | Pdfstartlink | Pdfendlink | Pdfdest | Pdfrunninglinkoff | Pdfrunninglinkon => {
self.scan_pdf_link(primitive, token.span, files)?;
}
Pdfinterwordspaceon | Pdfinterwordspaceoff | Pdffakespace | Pdfspacefont => {
@@ -741,6 +741,14 @@ impl Executor {
}
self.current = current;
if has_link_material && for_form {
let first = outputs.iter().find(|node| node.is_pdf_link());
if let Some(node) = first
&& matches!(node.operation, OutputOperation::PdfLink(
crate::pdf_device::links::LinkNode::Annotation { .. }
))
{
return Err(self.error("annotations cannot be inside an XForm", node.span));
}
return self.fail("PDF page links and destinations require a page shipout");
}
for usage in font_uses {
@@ -41,6 +41,7 @@ pub(super) struct PdfLinkShipout {
page_height: i64,
graphics_index: usize,
output: PageLinks,
direct_annotations: Vec<LinkAnnotation>,
origin: [i64; 2],
margin: i64,
numbered: bool,
@@ -79,6 +80,15 @@ impl NavigationGeometry {
}
}
fn rule_rectangle(row: BoxLayout, [x, y]: [i64; 2], [width, height, depth]: [Option<i32>; 3]) -> [i64; 4] {
[
x,
height.map_or(row.baseline - row.height, |h| y - i64::from(h)),
width.map_or(row.left + row.width, |w| x + i64::from(w)),
depth.map_or(row.baseline + row.depth, |d| y + i64::from(d)),
]
}
impl ActiveLink {
fn start_segment(
&mut self,
@@ -89,19 +99,7 @@ impl ActiveLink {
page_height: i64,
margin: i64,
) {
let [x, y] = point;
let rect = [
x,
self.layout
.height
.map_or(row.baseline - row.height, |h| y - i64::from(h)),
self.layout
.width
.map_or(row.left + row.width, |w| x + i64::from(w)),
self.layout
.depth
.map_or(row.baseline + row.depth, |d| y + i64::from(d)),
];
let rect = rule_rectangle(row, point, [self.layout.width, self.layout.height, self.layout.depth]);
self.segment = Some(output.annotations.len());
output.annotations.push(LinkAnnotation {
object_number: None,
@@ -147,7 +145,11 @@ impl Executor {
files: &mut impl SourceProvider,
) -> Result<(), Error> {
if self.native_page.is_none() || self.read_parameter(Parameter::Pdfoutput).width() <= 0 {
return self.fail("PDF link operation not allowed in DVI mode");
return self.fail(if command == Primitive::Pdfannot {
"\\pdfannot not allowed in DVI mode"
} else {
"PDF link operation not allowed in DVI mode"
});
}
if matches!(command, Primitive::Pdfstartlink | Primitive::Pdfendlink)
&& self.paragraph.is_none()
@@ -160,13 +162,35 @@ impl Executor {
});
}
let operation = match command {
Primitive::Pdfannot => {
self.reads.insert(Dependency::PdfObjects);
let limit = self.limits.tokens;
if self.keyword("reserveobjnum", files)? {
self.state.pdf_objects.get_or_insert_with(Default::default)
.reserve_annotation_number(limit)
.map_err(|error| self.error(error, span))?;
return self.optional_space(files);
}
let requested = if self.keyword("useobjnum", files)? {
Some(self.integer(files)? as u32)
} else {
None
};
let object_number = self.state.pdf_objects.get_or_insert_with(Default::default)
.begin_annotation(requested, limit)
.map_err(|error| self.error(error, span))?;
let dimensions = self.scan_pdf_rule(files)?;
let entries = self.scan_pdf_tokens(files)?;
self.state.pdf_objects.as_mut().unwrap().record_last_annotation(object_number);
LinkNode::Annotation { object_number, dimensions, entries }
}
Primitive::Pdfstartlink => {
self.reads.insert(Dependency::PdfObjects);
let object_number = self
.state
.pdf_objects
.get_or_insert_with(Default::default)
.reserve_link(self.limits.tokens)
.allocate_annotation(self.limits.tokens)
.map_err(|error| self.error(error, self.current))?;
let [width, height, depth] = self.scan_pdf_rule(files)?;
let attributes = if self.keyword("attr", files)? {
@@ -281,10 +305,10 @@ impl Executor {
Ok(())
}
pub(super) fn register_pdf_link(&mut self, number: Option<u32>) -> Result<u32, Error> {
pub(super) fn register_pdf_annotation(&mut self, number: Option<u32>) -> Result<u32, Error> {
self.reads.insert(Dependency::PdfObjects);
self.state.pdf_objects.get_or_insert_with(Default::default)
.ship_link(number, self.limits.tokens)
.ship_annotation(number, self.limits.tokens)
.map_err(|message| self.error(message, self.current))
}
@@ -350,6 +374,7 @@ impl Executor {
page_height: device.page_height,
graphics_index: 0,
output: PageLinks::default(),
direct_annotations: Vec::new(),
origin: [device.horizontal_origin, device.vertical_origin + b.height],
margin: i64::from(self.read_parameter(Parameter::Pdflinkmargin).width()),
numbered,
@@ -403,7 +428,7 @@ impl PdfLinkShipout {
for link in self.active.iter_mut().filter(|link| {
link.level == row.level && link.layout.width.is_none()
}) {
let number = if self.numbered { Some(executor.register_pdf_link(None)?) } else { None };
let number = if self.numbered { Some(executor.register_pdf_annotation(None)?) } else { None };
link.start_segment(&mut self.output, absolute_row(row), [x, y], &mut self.geometry,
self.page_height, self.margin);
self.output.annotations.last_mut().unwrap().object_number = number;
@@ -417,6 +442,16 @@ impl PdfLinkShipout {
let container = absolute_row(container);
executor.current = node.span;
match link {
LinkNode::Annotation { object_number, dimensions, entries } => {
let number = executor.register_pdf_annotation(Some(*object_number))?;
let rect = rule_rectangle(container, [x, y], *dimensions);
self.direct_annotations.push(LinkAnnotation {
object_number: Some(number),
rect: self.geometry.rectangle(rect, self.page_height, 0),
attributes: String::new(),
action: AnnotationAction::Direct(executor.pdf_token_bytes(entries)?),
});
}
LinkNode::Start(layout) => {
if self.active.len() == 10 {
return executor.fail("PDF link stack capacity exceeded");
@@ -425,7 +460,7 @@ impl PdfLinkShipout {
return executor.fail("PDF link start arrived outside a horizontal list");
}
let number = if self.numbered {
Some(executor.register_pdf_link(layout.object_number)?)
Some(executor.register_pdf_annotation(layout.object_number)?)
} else {
layout.object_number
};
@@ -479,12 +514,10 @@ impl PdfLinkShipout {
point
}
});
let view = view.map_rectangle(|[width, height, depth]| {
let view = view.map_rectangle(|dimensions| {
let margin = i64::from(executor.read_parameter(Parameter::Pdfdestmargin).width());
let top = height.map_or(container.baseline - container.height, |h| y - i64::from(h));
let right = width.map_or(container.left + container.width, |w| x + i64::from(w));
let bottom = depth.map_or(container.baseline + container.depth, |d| y + i64::from(d));
self.geometry.rectangle([x, top, right, bottom], self.page_height, margin)
let rect = rule_rectangle(container, [x, y], dimensions);
self.geometry.rectangle(rect, self.page_height, margin)
});
self.output.destinations.push(PageDestination {
object_number, destination, point, view,
@@ -516,6 +549,10 @@ impl PdfLinkShipout {
if self.numbered {
executor.pdf_navigation_geometry = self.geometry;
}
if !self.direct_annotations.is_empty() {
self.direct_annotations.append(&mut self.output.annotations);
self.output.annotations = self.direct_annotations;
}
Ok(self.output)
}
}
@@ -220,6 +220,7 @@ impl Executor {
| Primitive::Pdfrandomseed
| Primitive::Pdflastobj
| Primitive::Pdflastlink
| Primitive::Pdflastannot
| Primitive::Pdflastxform
| Primitive::Pdflastximage
| Primitive::Pdflastximagepages
@@ -16,9 +16,9 @@ use std::{
sync::{Arc, Mutex, OnceLock, Weak},
};
const SCHEMA: u32 = 103;
const COMPATIBLE_SCHEMAS: [u32; 69] = [
27, 28, 31, 32, 33, 34, 35, 36, 37, 38, 39, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, 80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 91, 92, 93, 94, 95, 96, 97, 98, 99, 100, 101, 102, SCHEMA,
const SCHEMA: u32 = 104;
const COMPATIBLE_SCHEMAS: [u32; 70] = [
27, 28, 31, 32, 33, 34, 35, 36, 37, 38, 39, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, 80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 91, 92, 93, 94, 95, 96, 97, 98, 99, 100, 101, 102, 103, SCHEMA,
];
const ENGINE: &str = concat!("texrra-native/", env!("CARGO_PKG_VERSION"));
@@ -223,6 +223,9 @@ impl FormatImage {
if image.schema < 103 {
image.state.restore_legacy_pdf_parameters(&[Parameter::Pdfsuppresswarningdupdest]);
}
if image.schema < 104 {
image.state.install_pdf_annotation_commands();
}
let pdf_objects = image.state.pdf_objects.as_deref();
let mut numbered_images = 0;
for (index, saved) in image.pdf_images.iter().enumerate() {
@@ -116,6 +116,7 @@ pub enum Primitive {
Pdfcolorstack,
Pdfsave,
Pdfstartlink,
Pdfannot,
Pdfendlink,
Pdfrunninglinkoff,
Pdfrunninglinkon,
@@ -366,6 +367,7 @@ pub enum Primitive {
Leftmarginkern,
Rightmarginkern,
Pdflastlink,
Pdflastannot,
Special,
Umathcode,
Umathcodenum,
@@ -958,6 +960,7 @@ const PDFTEX_ONLY_PRIMITIVES: &[(&str, Primitive)] = {
("pdfrefobj", Pdfrefobj),
("pdflastobj", Pdflastobj),
("pdflastlink", Pdflastlink),
("pdflastannot", Pdflastannot),
("pdfrandomseed", Pdfrandomseed),
("pdfsetrandomseed", Pdfsetrandomseed),
("pdfuniformdeviate", Pdfuniformdeviate),
@@ -968,6 +971,7 @@ const PDFTEX_ONLY_PRIMITIVES: &[(&str, Primitive)] = {
("pdfcolorstack", Pdfcolorstack),
("pdfsave", Pdfsave),
("pdfstartlink", Pdfstartlink),
("pdfannot", Pdfannot),
("pdfendlink", Pdfendlink),
("pdfrunninglinkoff", Pdfrunninglinkoff),
("pdfrunninglinkon", Pdfrunninglinkon),
@@ -1975,6 +1979,16 @@ impl State {
}
}
pub(super) fn install_pdf_annotation_commands(&mut self) {
let enabled = self.input_profile != super::InputProfile::XeTeX;
for (name, primitive) in [
("pdfannot", Primitive::Pdfannot),
("pdflastannot", Primitive::Pdflastannot),
] {
self.update_profile_command(name, Meaning::Primitive(primitive), enabled);
}
}
fn install_pdftex_primitives(&mut self) {
let enabled = self.input_profile != super::InputProfile::XeTeX;
for &(name, primitive) in PDFTEX_ONLY_PRIMITIVES {