Write native PDF catalogs and open actions

This commit is contained in:
gloamxun committed 2026-11-19 08:54:04 +08:00
1 parent a53d9c9bf9
commit f4b003bd27
20 files changed
+811 -40

No files matched your search

@@ -22,6 +22,7 @@ mod nesting;
mod page;
mod paragraphs;
mod pdf_color;
mod pdf_catalog;
mod pdf_graphics;
mod pdf_links;
mod pdf_image;
@@ -162,6 +163,7 @@ pub struct Executor {
io: IoState,
pdf_colors: crate::pdf_device::PdfColorStacks,
pdf_link_stack: Vec<pdf_links::ActiveLink>,
pdf_catalog_tokens: Vec<Token>,
pdf_images: Vec<pdf_image::RegisteredImage>,
input_position: Option<(usize, usize)>,
paragraph: Option<super::paragraph::Builder>,
@@ -230,6 +232,7 @@ impl Executor {
io: IoState::default(),
pdf_colors: Default::default(),
pdf_link_stack: Vec::new(),
pdf_catalog_tokens: Vec::new(),
pdf_images: Vec::new(),
input_position: None,
paragraph: None,
@@ -2936,7 +2939,10 @@ impl Executor {
) -> Result<(), Error> {
self.check_cancellation()?;
self.change_interaction_mode(self.interaction_mode, files)?;
if let Err(mut error) = self.run_input(file, files) {
let result = self
.run_input(file, files)
.and_then(|()| self.finish_pdf_catalog());
if let Err(mut error) = result {
if let Err(sink) = files.observe_error(&error) {
error
.message
@@ -3349,6 +3355,7 @@ impl Executor {
Pdfstartlink | Pdfendlink | Pdfdest => {
self.scan_pdf_link(primitive, token.span, files)?;
}
Pdfcatalog => self.scan_pdf_catalog(files)?,
Pdfximage => self.scan_pdf_image(&token, false, files)?,
Pdfrefximage => self.reference_pdf_image(&token, files)?,
_ => {
@@ -550,7 +550,7 @@ impl Executor {
Vcenter => self.box_command(*p, boxes::Destination::Append, token.span, files)?,
Hbox | Vbox | Vtop | Box | Copy | Setbox | Wd | Ht | Dp | Lastbox | Raise
| Lower | Vsplit | Mark | Marks | Vadjust | Insert | Shipout | Openout
| Closeout | Write | Pdfcolorstack | Pdfsave | Pdfsetmatrix | Pdfrestore
| Closeout | Write | Pdfcolorstack | Pdfsave | Pdfsetmatrix | Pdfrestore | Pdfcatalog
| Ignorespaces | Unskip | Unkern | Unpenalty => {
return Ok(false);
}
@@ -0,0 +1,196 @@
use super::*;
use crate::pdf_device::{
catalog::{CatalogAction, CatalogTarget},
links::DestinationId,
};
impl Executor {
pub(super) fn scan_pdf_tokens(
&mut self,
files: &mut impl SourceProvider,
) -> Result<Vec<Token>, Error> {
self.with_scanner(ScannerStatus::Absorbing, |s| {
s.scan_expanded_group_mode(files, false)
})
}
pub(super) fn positive_pdf_number(
&mut self,
description: &str,
files: &mut impl SourceProvider,
) -> Result<i32, Error> {
let number = self.integer(files)?;
if number <= 0 {
return self.fail(format!("PDF {description} must be positive"));
}
Ok(number)
}
fn pdf_token_bytes(&mut self, tokens: &[Token]) -> Result<Vec<u8>, Error> {
let text = self.token_list_text(tokens);
if text.len() > self.limits.tokens {
return self.fail("native PDF token output limit exceeded");
}
if self.state.input_profile() == InputProfile::TeX8Bit {
text.chars()
.map(|character| {
u8::try_from(u32::from(character)).map_err(|_| {
self.error("PDF token is outside the 8-bit profile", self.current)
})
})
.collect()
} else {
Ok(text.into_bytes())
}
}
fn scan_pdf_bytes(&mut self, files: &mut impl SourceProvider) -> Result<Vec<u8>, Error> {
let tokens = self.scan_pdf_tokens(files)?;
self.pdf_token_bytes(&tokens)
}
fn scan_catalog_target(
&mut self,
goto: bool,
remote: bool,
files: &mut impl SourceProvider,
) -> Result<CatalogTarget, Error> {
if self.keyword("page", files)? {
if !goto {
return self.fail("only PDF GoTo actions can target a page");
}
let number = self.positive_pdf_number("page number", files)?;
let view = self.scan_pdf_bytes(files)?;
Ok(CatalogTarget::Page { number, view })
} else if self.keyword("name", files)? {
let tokens = self.scan_pdf_tokens(files)?;
Ok(CatalogTarget::Destination(DestinationId::Name(
self.token_list_text(&tokens),
)))
} else if self.keyword("num", files)? {
if goto && remote {
return self.fail("PDF goto cannot use both file and num");
}
let number = self.positive_pdf_number("destination number", files)?;
Ok(CatalogTarget::Destination(DestinationId::Number(number)))
} else {
self.fail("PDF action destination type missing")
}
}
fn scan_catalog_action(
&mut self,
files: &mut impl SourceProvider,
) -> Result<CatalogAction, Error> {
if self.keyword("user", files)? {
return self.scan_pdf_bytes(files).map(CatalogAction::User);
}
let goto = self.keyword("goto", files)?;
if !goto && !self.keyword("thread", files)? {
return self.fail("PDF action type missing");
}
let file = if self.keyword("file", files)? {
Some(self.scan_pdf_bytes(files)?)
} else {
None
};
let structure = if self.keyword("struct", files)? {
if !goto || file.is_none() {
return self.fail("current PDF structure actions require a remote GoTo");
}
Some(self.scan_pdf_bytes(files)?)
} else {
None
};
let target = self.scan_catalog_target(goto, file.is_some(), files)?;
let window = if self.keyword("newwindow", files)? {
Some(true)
} else if self.keyword("nonewwindow", files)? {
Some(false)
} else {
None
};
if window.is_some() {
if !goto || file.is_none() {
return self.fail("PDF newwindow/nonewwindow requires goto with file");
}
if let Some(next) = self.expanded(files)? {
if !self.is_spacer(&next.token) {
self.unread(next)?;
}
}
}
if goto {
Ok(CatalogAction::GoTo {
target,
file,
window,
structure,
})
} else {
let CatalogTarget::Destination(destination) = target else {
unreachable!("thread page targets were rejected while scanning")
};
Ok(CatalogAction::Thread { destination, file })
}
}
pub(super) fn scan_pdf_catalog(
&mut self,
files: &mut impl SourceProvider,
) -> Result<(), Error> {
let enabled = self.read_parameter(Parameter::Pdfoutput).width() > 0;
if !enabled {
let text = "pdfTeX warning (\\pdfcatalog): not allowed in DVI mode (\\pdfoutput <= 0); ignoring it";
files
.observe_message(text)
.map_err(|error| self.error(error, self.current))?;
self.events.push(Event::Message {
text: text.into(),
span: self.current,
});
}
let tokens = self.scan_pdf_tokens(files)?;
if enabled {
if self.pdf_catalog_tokens.len().saturating_add(tokens.len()) > self.limits.tokens {
return self.fail("native PDF catalog token limit exceeded");
}
self.pdf_catalog_tokens.extend(tokens);
}
if self.keyword("openaction", files)? {
self.reads.insert(Dependency::PdfCatalogState);
if enabled
&& self
.state
.pdf_catalog
.as_ref()
.is_some_and(|catalog| catalog.open_action.is_some())
{
return self.fail("PDF catalog duplicate of openaction");
}
let action = self.scan_catalog_action(files)?;
if enabled {
// An action allocates a PDF object at the command boundary.
self.pdf_page_data(files)?;
self.state
.pdf_catalog
.get_or_insert_with(Default::default)
.open_action = Some(action);
}
}
Ok(())
}
pub(super) fn finish_pdf_catalog(&mut self) -> Result<(), Error> {
if !self.pdf_catalog_tokens.is_empty() {
let tokens = std::mem::take(&mut self.pdf_catalog_tokens);
let bytes = self.pdf_token_bytes(&tokens)?;
self.state
.pdf_catalog
.get_or_insert_with(Default::default)
.entries
.extend(bytes);
}
Ok(())
}
}
@@ -2,7 +2,7 @@ use super::*;
use crate::pdf_device::{
Affine, PdfGraphics,
links::{
AnnotationAction, DestinationView, LinkAction, LinkAnnotation, LinkNode, LinkStart,
AnnotationAction, DestinationId, DestinationView, LinkAction, LinkAnnotation, LinkNode, LinkStart,
PageDestination, PageLinks,
},
};
@@ -100,12 +100,6 @@ impl ActiveLink {
}
impl Executor {
fn link_tokens(&mut self, files: &mut impl SourceProvider) -> Result<Vec<Token>, Error> {
self.with_scanner(ScannerStatus::Absorbing, |s| {
s.scan_expanded_group_mode(files, false)
})
}
pub(super) fn scan_pdf_link(
&mut self,
command: Primitive,
@@ -138,14 +132,14 @@ impl Executor {
*target = Some(self.dimension(false, false, files)?.amount);
}
let attributes = if self.keyword("attr", files)? {
self.link_tokens(files)?
self.scan_pdf_tokens(files)?
} else {
Vec::new()
};
let action = if self.keyword("user", files)? {
LinkAction::User(self.link_tokens(files)?)
LinkAction::User(self.scan_pdf_tokens(files)?)
} else if self.keyword("goto", files)? && self.keyword("name", files)? {
LinkAction::GotoName(self.link_tokens(files)?)
LinkAction::GotoName(self.scan_pdf_tokens(files)?)
} else {
return self.fail("expected a user or named goto PDF link action");
};
@@ -159,10 +153,13 @@ impl Executor {
}
Primitive::Pdfendlink => LinkNode::End,
Primitive::Pdfdest => {
if !self.keyword("name", files)? {
return self.fail("expected a named PDF destination");
}
let name = self.link_tokens(files)?;
let destination = if self.keyword("name", files)? {
DestinationId::Name(self.scan_pdf_tokens(files)?)
} else if self.keyword("num", files)? {
DestinationId::Number(self.positive_pdf_number("destination number", files)?)
} else {
return self.fail("expected a PDF destination identifier");
};
let view = if self.keyword("xyz", files)? {
let zoom = if self.keyword("zoom", files)? {
Some(self.integer(files)?)
@@ -187,7 +184,7 @@ impl Executor {
}
view.ok_or_else(|| self.error("expected PDF destination view", span))?
};
LinkNode::Destination { name, view }
LinkNode::Destination { destination, view }
}
_ => unreachable!(),
};
@@ -276,9 +273,15 @@ impl Executor {
}
link.end_segment(&mut output, x, margin);
}
LinkNode::Destination { name, view } => output.destinations.push(PageDestination {
name: self.token_list_text(name), point: map_point(transform.0, x, y), view: *view,
}),
LinkNode::Destination { destination, view } => {
let destination = match destination {
DestinationId::Name(tokens) => DestinationId::Name(self.token_list_text(tokens)),
DestinationId::Number(number) => DestinationId::Number(*number),
};
output.destinations.push(PageDestination {
destination, point: map_point(transform.0, x, y), view: *view,
});
}
}
}
_ => {}
@@ -71,6 +71,7 @@ impl Executor {
if self.after_assignment.is_some() {
c.usage.token_list_cells += 1;
}
c.usage.token_list_cells += self.pdf_catalog_tokens.len();
for input in &self.inputs {
match input {
InputFrame::Source { mouth, .. } => {
@@ -7,7 +7,7 @@ use std::{
path::Path,
};
const SCHEMA: u32 = 22;
const SCHEMA: u32 = 23;
const ENGINE: &str = concat!("texrra-native/", env!("CARGO_PKG_VERSION"));
#[derive(serde::Serialize, serde::Deserialize)]
@@ -352,6 +352,7 @@ pub enum Dependency {
Parameter(Parameter),
MagnificationState,
PdfFileState,
PdfCatalogState,
PdfImages,
GlyphUnicode,
ResourceStatistics,
@@ -108,6 +108,7 @@ pub enum Primitive {
Pdfstartlink,
Pdfendlink,
Pdfdest,
Pdfcatalog,
Pdfsetmatrix,
Pdfrestore,
Pdfglyphtounicode,
@@ -594,6 +595,8 @@ pub struct State {
pub(super) magnification_set: Option<i32>,
pub(super) output_mode_set: Option<i32>,
pub(super) pdf_file_options: Option<crate::pdf_device::PdfFileOptions>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub(super) pdf_catalog: Option<Box<crate::pdf_device::catalog::PdfCatalog>>,
pub(super) glyph_unicode: crate::pdf_unicode::GlyphUnicodeMap,
pub(super) hyphenation: super::hyphenation::HyphenationData,
}
@@ -634,6 +637,7 @@ impl Default for State {
magnification_set: None,
output_mode_set: None,
pdf_file_options: None,
pdf_catalog: None,
glyph_unicode: crate::pdf_unicode::GlyphUnicodeMap::default(),
hyphenation: super::hyphenation::HyphenationData::default(),
};
@@ -854,6 +858,7 @@ impl Default for State {
("pdfstartlink", Pdfstartlink),
("pdfendlink", Pdfendlink),
("pdfdest", Pdfdest),
("pdfcatalog", Pdfcatalog),
("pdfsetmatrix", Pdfsetmatrix),
("pdfrestore", Pdfrestore),
("pdfglyphtounicode", Pdfglyphtounicode),
@@ -1239,6 +1244,7 @@ impl State {
self.magnification_set = None;
self.output_mode_set = None;
self.pdf_file_options = None;
self.pdf_catalog = None;
self
}
pub fn is_initex(&self) -> bool {
@@ -1251,6 +1257,7 @@ impl State {
compression: self.parameter(Parameter::Pdfcompresslevel).width(),
generate_unicode: self.parameter(Parameter::Pdfgentounicode).width(),
glyph_unicode: &self.glyph_unicode,
catalog: self.pdf_catalog.as_deref(),
}
}
/// Job-wide decoding choice; it is not a scoped TeX assignment.