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.
+170 -3
View File
@@ -13,6 +13,10 @@ use flate2::write::ZlibEncoder;
use rusttype::Font;
use crate::cmr10::Cmr10Metrics;
use crate::pdf_device::{
catalog::{CatalogAction, CatalogTarget},
links::DestinationId,
};
use crate::render::{DisplayItem, DisplayList, FontFace};
use crate::type1::Type1Font;
#[path = "pdf_text.rs"]
@@ -1459,6 +1463,137 @@ fn write_native_font(
id
}
fn pdf_file_specification(out: &mut Vec<u8>, file: &[u8]) {
out.extend_from_slice(b"/F ");
if file.starts_with(b"(") && file.ends_with(b")") {
out.extend_from_slice(file);
} else {
out.push(b'(');
for &byte in file {
if matches!(byte, b'(' | b')' | b'\\') {
out.push(b'\\');
}
out.push(byte);
}
out.push(b')');
}
out.push(b' ');
}
fn write_catalog_action(
action: &CatalogAction,
page_ids: &[usize],
destinations: &mut BTreeMap<String, String>,
numbers: &BTreeMap<i32, usize>,
objects: &mut Vec<Vec<u8>>,
diagnostics: &mut Vec<String>,
) -> (usize, Option<usize>) {
let mut output = b"<< ".to_vec();
let mut threads = None;
match action {
CatalogAction::User(object) => output.clone_from(object),
CatalogAction::GoTo {
target,
file,
window,
structure,
} => {
if let Some(file) = file {
pdf_file_specification(&mut output, file);
if let Some(window) = window {
write!(&mut output, "/NewWindow {window} ").unwrap();
}
output.extend_from_slice(b"/S /GoToR /D ");
} else {
output.extend_from_slice(b"/S /GoTo /D ");
}
match target {
CatalogTarget::Destination(DestinationId::Name(name)) => {
if file.is_none() && !destinations.contains_key(name) {
diagnostics.push(format!(
"destination name{{{name}}} has been referenced but does not exist, replaced by a fixed one"
));
destinations.insert(name.clone(), format!("[{} 0 R /Fit]", page_ids[0]));
}
output.extend_from_slice(pdf_text(name).as_bytes());
}
CatalogTarget::Destination(DestinationId::Number(number)) => {
let id = numbers.get(number).copied().unwrap_or_else(|| {
diagnostics.push(format!(
"destination num{number} has been referenced but does not exist, replaced by a fixed one"
));
objects.push(format!("[{} 0 R /Fit]", page_ids[0]).into_bytes());
objects.len()
});
write!(&mut output, "{id} 0 R").unwrap();
}
CatalogTarget::Page { number, view } => {
let index = (*number - 1) as usize;
if file.is_some() {
write!(&mut output, "[{index} ").unwrap();
} else {
let page = page_ids.get(index).copied().unwrap_or_else(|| {
diagnostics.push(format!(
"page {number} has been referenced but does not exist"
));
objects.push(Vec::new());
objects.len()
});
write!(&mut output, "[{page} 0 R ").unwrap();
}
output.extend_from_slice(view);
output.push(b']');
}
}
if let Some(structure) = structure {
output.extend_from_slice(b" /SD ");
output.extend_from_slice(structure);
}
output.extend_from_slice(b"\n>>");
}
CatalogAction::Thread { destination, file } => {
let mut local_id = None;
if let Some(file) = file {
pdf_file_specification(&mut output, file);
} else {
let (title, identifier) = match destination {
DestinationId::Name(name) => (name.clone(), format!("name{{{name}}}")),
DestinationId::Number(number) => (number.to_string(), format!("num{number}")),
};
diagnostics.push(format!(
"thread destination {identifier} has been referenced but does not exist, replaced by a fixed one"
));
// There are no thread definitions yet. As pdfTeX does for an
// undefined thread, link its single empty bead to the first page.
let thread = objects.len() + 1;
let bead = thread + 1;
objects.push(format!("<< /I << /Title {} >> /F {bead} 0 R >>", pdf_text(&title)).into_bytes());
objects.push(format!(
"<< /T {thread} 0 R /V {bead} 0 R /N {bead} 0 R /P {} 0 R /R [0 0 0 0] >>",
page_ids[0]
).into_bytes());
objects.push(format!("[{thread} 0 R]").into_bytes());
local_id = Some(thread);
threads = Some(objects.len());
}
output.extend_from_slice(b"/S /Thread /D ");
match destination {
DestinationId::Name(name) => output.extend_from_slice(pdf_text(name).as_bytes()),
DestinationId::Number(number) => {
if let Some(id) = local_id {
write!(&mut output, "{id} 0 R").unwrap();
} else {
write!(&mut output, "{number}").unwrap();
}
}
}
output.extend_from_slice(b" >>");
}
}
objects.push(output);
(objects.len(), threads)
}
fn write_pdf(
pages: &[DisplayList],
page_width: i64,
@@ -1718,6 +1853,7 @@ fn write_pdf(
let mut kids = Vec::new();
let mut page_ids: Vec<usize> = Vec::new();
let mut destinations = BTreeMap::new();
let mut numbers = BTreeMap::new();
let mut form_ids = BTreeMap::new();
for list in pages {
for item in &list.items {
@@ -1935,7 +2071,18 @@ fn write_pdf(
DestinationView::FitBH => format!("/FitBH {y}"),
DestinationView::FitBV => format!("/FitBV {x}"),
};
destinations.entry(destination.name.clone()).or_insert_with(|| format!("[{page_id} 0 R {view}]"));
let object = || format!("[{page_id} 0 R {view}]");
match &destination.destination {
DestinationId::Name(name) => {
destinations.entry(name.clone()).or_insert_with(object);
}
DestinationId::Number(number) => {
numbers.entry(*number).or_insert_with(|| {
objects.push(object().into_bytes());
objects.len()
});
}
}
}
}
objects[1] = format!(
@@ -2025,6 +2172,15 @@ fn write_pdf(
.into_bytes();
catalog.push_str(&format!(" /Outlines {root_id} 0 R"));
}
let extra = unicode.and_then(|options| options.catalog);
let action = extra.and_then(|extra| extra.open_action.as_ref()).map(|action| {
write_catalog_action(
action, &page_ids, &mut destinations, &numbers, &mut objects, diagnostics,
)
});
if let Some((_, Some(threads))) = action {
catalog.push_str(&format!(" /Threads {threads} 0 R"));
}
if !destinations.is_empty() {
let mut entries = Vec::with_capacity(destinations.len());
let first = pdf_text(destinations.first_key_value().unwrap().0);
@@ -2037,8 +2193,19 @@ fn write_pdf(
entries.join(" ")).into_bytes());
catalog.push_str(&format!(" /Names << /Dests {} 0 R >>", objects.len()));
}
catalog.push_str(" >>");
objects[0] = catalog.into_bytes();
let mut catalog = catalog.into_bytes();
if let Some(extra) = extra {
if !extra.entries.is_empty() {
catalog.push(b'\n');
catalog.extend_from_slice(&extra.entries);
catalog.push(b'\n');
}
if let Some((id, _)) = action {
write!(&mut catalog, " /OpenAction {id} 0 R").unwrap();
}
}
catalog.extend_from_slice(b" >>");
objects[0] = catalog;
let info_ref = match metadata_object(metadata) {
Some(object) => {
+1
View File
@@ -74,4 +74,5 @@ pub(crate) use color::{ColorResult, PdfColorStacks};
pub use color::{PdfColorProgram, PdfColorStackAction};
pub(crate) use graphics::Affine;
pub use graphics::{PdfGraphics, PdfMatrix};
pub mod catalog;
pub mod links;
@@ -0,0 +1,29 @@
//! Job-global additions to the PDF catalog and its initial action.
use super::links::DestinationId;
#[derive(Clone, Debug, Default, PartialEq, Eq, Hash, serde::Serialize, serde::Deserialize)]
pub struct PdfCatalog {
pub(crate) entries: Vec<u8>,
pub(crate) open_action: Option<CatalogAction>,
}
#[derive(Clone, Debug, PartialEq, Eq, Hash, serde::Serialize, serde::Deserialize)]
pub(crate) enum CatalogAction {
User(Vec<u8>),
GoTo {
target: CatalogTarget,
file: Option<Vec<u8>>,
window: Option<bool>,
structure: Option<Vec<u8>>,
},
Thread {
destination: DestinationId<String>,
file: Option<Vec<u8>>,
},
}
#[derive(Clone, Debug, PartialEq, Eq, Hash, serde::Serialize, serde::Deserialize)]
pub(crate) enum CatalogTarget {
Destination(DestinationId<String>),
Page { number: i32, view: Vec<u8> },
}
+10 -2
View File
@@ -27,12 +27,20 @@ pub enum DestinationView {
FitBV,
}
#[derive(
Clone, Debug, PartialEq, Eq, PartialOrd, Ord, Hash, serde::Serialize, serde::Deserialize,
)]
pub enum DestinationId<T> {
Name(T),
Number(i32),
}
#[derive(Clone, Debug, PartialEq, Eq, Hash, serde::Serialize, serde::Deserialize)]
pub enum LinkNode {
Start(LinkStart),
End,
Destination {
name: Vec<Token>,
destination: DestinationId<Vec<Token>>,
view: DestinationView,
},
}
@@ -53,7 +61,7 @@ pub struct LinkAnnotation {
#[derive(Clone, Debug, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
pub struct PageDestination {
pub name: String,
pub destination: DestinationId<String>,
pub point: [i64; 2],
pub view: DestinationView,
}
+18 -7
View File
@@ -32,9 +32,16 @@ pub(super) fn serialize(
let mut pdf = format!("%PDF-{}.{}\n", options.major, options.minor).into_bytes();
let mut offsets = vec![0u64; objects.len() + 1];
let mut packed = vec![None; objects.len() + 1];
let mut free = vec![None; objects.len() + 1];
let mut last_free = 0;
let mut groups: Vec<Vec<usize>> = Vec::new();
for (i, body) in objects.iter().enumerate() {
let id = i + 1;
if body.is_empty() {
free[last_free] = Some(id);
last_free = id;
continue;
}
let level = if Some(id) == info {
3
} else if body.windows(19).any(|s| s == b"/Subtype /TrueType ")
@@ -61,6 +68,7 @@ pub(super) fn serialize(
pdf.extend_from_slice(b"\nendobj\n");
}
}
free[last_free] = Some(0);
for (i, ids) in groups.iter().enumerate() {
let id = objects.len() + 1 + i;
offsets.push(pdf.len() as u64);
@@ -86,11 +94,14 @@ pub(super) fn serialize(
let info_ref = info.map_or_else(String::new, |id| format!(" /Info {id} 0 R"));
let xref = pdf.len();
if options.object_compression == 0 {
pdf.extend_from_slice(
format!("xref\n0 {}\n0000000000 65535 f \n", objects.len() + 1).as_bytes(),
);
for off in offsets.iter().skip(1) {
pdf.extend_from_slice(format!("{off:010} 00000 n \n").as_bytes());
pdf.extend_from_slice(format!("xref\n0 {}\n", objects.len() + 1).as_bytes());
for (id, (offset, next)) in offsets.iter().zip(&free).enumerate() {
if let Some(next) = next {
let generation = if id == 0 { 65535 } else { 0 };
pdf.extend_from_slice(format!("{next:010} {generation:05} f \n").as_bytes());
} else {
pdf.extend_from_slice(format!("{offset:010} 00000 n \n").as_bytes());
}
}
pdf.extend_from_slice(
format!(
@@ -104,8 +115,8 @@ pub(super) fn serialize(
offsets.push(xref as u64);
let mut entries = Vec::new();
for (obj, offset) in offsets.iter().enumerate() {
let (kind, a, b) = if obj == 0 {
(0u8, 0u64, 65535u32)
let (kind, a, b) = if let Some(Some(next)) = free.get(obj) {
(0u8, *next as u64, if obj == 0 { 65535 } else { 0 })
} else if let Some(Some((stm, index))) = packed.get(obj) {
(2, *stm as u64, *index as u32)
} else {
+2 -1
View File
@@ -122,12 +122,13 @@ impl GlyphUnicodeMap {
}
}
/// Parameters consumed when final font objects are written, after all shipouts.
/// Parameters and job data consumed by the PDF writer after all shipouts.
#[derive(Clone, Copy)]
pub struct PdfFinalOptions<'a> {
pub compression: i32,
pub generate_unicode: i32,
pub glyph_unicode: &'a GlyphUnicodeMap,
pub catalog: Option<&'a crate::pdf_device::catalog::PdfCatalog>,
}
#[cfg(test)]
@@ -246,7 +246,7 @@ fn genuine_fraction_primitives_and_retained_boxes_survive_format_roundtrip() {
let envelope: serde_json::Value = serde_json::from_slice(&bytes).unwrap();
let payload: serde_json::Value =
serde_json::from_str(envelope["payload"].as_str().unwrap()).unwrap();
assert_eq!(payload["schema"], 22);
assert_eq!(payload["schema"], 23);
let state = State::initex().with_etex();
let loaded = FormatImage::decode(&bytes)
.unwrap()
@@ -0,0 +1,332 @@
use lopdf::{Dictionary, Document, Object};
use std::{
fs,
process::Command,
sync::atomic::{AtomicUsize, Ordering},
};
use texrra_tex_core::{
execution::{
Error, Execution, Executor, FormatImage, InputProfile, JobTime, Limits, Profile,
SourceFile, SourceProvider, State,
},
pdf::{NativePdfDocument, shipout_lists_to_native_pdf_document},
};
const SETUP: &str = r"\catcode123=1 \catcode125=2 \catcode94=7 \pdfoutput=1 \pdfobjcompresslevel=0 \pdfcompresslevel=0 \pdfpkresolution=600 ";
const PAGE: &str = r"\shipout\hbox{\vrule width8pt height6pt}";
struct RulesOnly;
impl SourceProvider for RulesOnly {
fn read(&mut self, name: &str, _: &str) -> Result<SourceFile, String> {
Err(format!("unexpected input {name}"))
}
}
fn run_native(source: &str) -> Result<Execution, Error> {
Executor::new(
State::initex()
.with_etex()
.with_input_profile(InputProfile::TeX8Bit),
Limits::default(),
)
.with_native_pages()
.run(
SourceFile {
name: "catalog.tex".into(),
data: source.as_bytes().to_vec(),
},
&mut RulesOnly,
)
}
fn export_native(execution: &Execution) -> NativePdfDocument {
shipout_lists_to_native_pdf_document(
&execution.shipout_display_lists().unwrap(),
execution.state.pdf_final_options(),
)
.unwrap()
}
fn pair(body: &str) -> (Document, Document, Vec<String>) {
let source = format!("{SETUP}{body}\\end\n");
static NEXT: AtomicUsize = AtomicUsize::new(0);
let work = std::env::temp_dir().join(format!(
"texrra-pdf-catalog-{}-{}",
std::process::id(),
NEXT.fetch_add(1, Ordering::Relaxed)
));
fs::create_dir_all(&work).unwrap();
fs::write(work.join("catalog.tex"), &source).unwrap();
let reference = Command::new("pdftex")
.args([
"-ini",
"-etex",
"-interaction=nonstopmode",
"-halt-on-error",
"catalog.tex",
])
.current_dir(&work)
.output()
.unwrap();
assert!(
reference.status.success(),
"{}",
String::from_utf8_lossy(&reference.stdout)
);
let reference = Document::load(work.join("catalog.pdf")).unwrap();
fs::remove_dir_all(work).unwrap();
let native = export_native(&run_native(&source).unwrap());
(
reference,
Document::load_mem(&native.bytes).unwrap(),
native.diagnostics,
)
}
fn get<'a>(doc: &'a Document, dictionary: &'a Dictionary, key: &[u8]) -> &'a Object {
let value = dictionary.get(key).unwrap();
if let Object::Reference(id) = value {
doc.get_object(*id).unwrap()
} else {
value
}
}
fn comparable(object: &Object) -> String {
match object {
Object::Dictionary(dictionary) => comparable_dictionary(dictionary),
Object::Array(items) => format!(
"array {:?}",
items.iter().map(comparable).collect::<Vec<_>>()
),
Object::String(bytes, _) => format!("string {bytes:?}"),
_ => format!("{object:?}"),
}
}
fn comparable_dictionary(dictionary: &Dictionary) -> String {
let entries: std::collections::BTreeMap<_, _> = dictionary
.iter()
.map(|(key, value)| (key, comparable(value)))
.collect();
format!("dictionary {entries:?}")
}
fn action(doc: &Document) -> &Dictionary {
let catalog = doc.catalog().unwrap();
assert!(matches!(
catalog.get(b"OpenAction"),
Ok(Object::Reference(_))
));
get(doc, catalog, b"OpenAction").as_dict().unwrap()
}
#[test]
fn catalog_appends_expanded_lists_and_prints_with_final_token_settings() {
let (reference, native, _) = pair(&format!(
r"\def\language{{en-GB}}{{\pdfcatalog{{/Lang (\language) /Raw (^^e9)}}}}
\pdfcatalog{{/ViewerPreferences << /HideToolbar true >> /Custom (\noexpand\literal)}}
\def\language{{en-US}}\escapechar=33 {PAGE}"
));
for key in [b"Lang".as_slice(), b"Raw", b"ViewerPreferences", b"Custom"] {
let original = reference.catalog().unwrap().get(key).unwrap();
let actual = native.catalog().unwrap().get(key).unwrap();
assert_eq!(comparable(original), comparable(actual));
}
assert!(native.catalog().unwrap().get(b"OpenAction").is_err());
}
#[test]
fn open_actions_use_the_actual_objects_and_page_references() {
for command in [
r"user {<< /S /URI /URI (https://example.org/paper) >>}",
r"goto file {paper.pdf} page 3 {/Fit} newwindow ",
r"goto file {(paper.pdf)} name {chapter} nonewwindow ",
r"goto file {paper.pdf} struct {[5 /Fit]} name {chapter}",
r"thread file {paper.pdf} num 3 ",
] {
let (reference, native, _) = pair(&format!("\\pdfcatalog{{}} openaction {command}{PAGE}"));
assert_eq!(
comparable_dictionary(action(&reference)),
comparable_dictionary(action(&native)),
"{command}"
);
}
let (reference, native, _) = pair(&format!(
"\\pdfcatalog{{}} openaction goto page 2 {{/FitH 700}}{PAGE}{PAGE}"
));
for pdf in [&reference, &native] {
let target = action(pdf).get(b"D").unwrap().as_array().unwrap();
assert_eq!(target[0].as_reference().unwrap(), pdf.get_pages()[&2]);
assert_eq!(target[1].as_name().unwrap(), b"FitH");
assert_eq!(target[2].as_i64().unwrap(), 700);
}
let (reference, native, _) = pair(
r"\pdfcatalog{} openaction goto num 9
\shipout\hbox{\pdfdest num 9 fit\vrule width8pt height6pt}",
);
for pdf in [&reference, &native] {
let target = get(pdf, action(pdf), b"D").as_array().unwrap();
assert_eq!(target[0].as_reference().unwrap(), pdf.get_pages()[&1]);
assert_eq!(target[1].as_name().unwrap(), b"Fit");
}
}
#[test]
fn absent_targets_follow_reference_destination_and_xref_behavior() {
let (reference, native, messages) = pair(&format!(
"\\pdfcatalog{{}} openaction goto name {{missing}}{PAGE}"
));
assert_eq!(
comparable_dictionary(action(&reference)),
comparable_dictionary(action(&native))
);
assert!(
messages
.iter()
.any(|message| message.contains("name{missing}"))
);
for pdf in [&reference, &native] {
let names = get(pdf, pdf.catalog().unwrap(), b"Names")
.as_dict()
.unwrap();
let dests = get(pdf, names, b"Dests").as_dict().unwrap();
let entries = dests.get(b"Names").unwrap().as_array().unwrap();
assert_eq!(entries[0].as_str().unwrap(), b"missing");
let target = pdf.get_object(entries[1].as_reference().unwrap()).unwrap();
let target = if let Object::Dictionary(dictionary) = target {
get(pdf, dictionary, b"D")
} else {
target
};
let target = target.as_array().unwrap();
assert_eq!(target[0].as_reference().unwrap(), pdf.get_pages()[&1]);
assert_eq!(target[1].as_name().unwrap(), b"Fit");
}
for compression in [0, 2] {
// pdfTeX inserts diagnostic comments in raw (uncompressed) object
// streams, which this version of lopdf cannot unpack.
let stream_compression = if compression == 0 { 0 } else { 9 };
let (reference, native, messages) = pair(&format!(
"\\pdfminorversion=5 \\pdfobjcompresslevel={compression} \\pdfcompresslevel={stream_compression} \\pdfcatalog{{}} openaction goto page 2 {{/Fit}}{PAGE}"
));
assert!(messages.iter().any(|message| message.contains("page 2")));
for pdf in [&reference, &native] {
let target = action(pdf).get(b"D").unwrap().as_array().unwrap();
assert_eq!(pdf.get_pages().len(), 1);
assert!(pdf.get_object(target[0].as_reference().unwrap()).is_err());
assert_eq!(target[1].as_name().unwrap(), b"Fit");
}
}
}
#[test]
fn format_images_retain_catalog_primitive_and_clear_job_catalog_data() {
let seed = format!("{SETUP}\\pdfcatalog{{/Lang (seed)}}\\dump\n");
let dump = run_native(&seed).unwrap();
assert!(dump.state.pdf_final_options().catalog.is_some());
let image = FormatImage::from_dump(dump, Vec::new(), Vec::new())
.unwrap()
.encode()
.unwrap();
let job = FormatImage::decode(&image)
.unwrap()
.new_job(
Profile::EtexBootstrap,
InputProfile::TeX8Bit,
JobTime::new(2026, 1, 2, 123).unwrap(),
Limits::default(),
|_| Ok(seed.as_bytes().to_vec()),
)
.unwrap()
.with_native_pages()
.run(
SourceFile {
name: "document.tex".into(),
data: format!("\\pdfcatalog{{/PageLayout /SinglePage}}{PAGE}\\end").into_bytes(),
},
&mut RulesOnly,
)
.unwrap();
let doc = Document::load_mem(&export_native(&job).bytes).unwrap();
let catalog = doc.catalog().unwrap();
assert!(catalog.get(b"Lang").is_err());
assert_eq!(
catalog.get(b"PageLayout").unwrap().as_name().unwrap(),
b"SinglePage"
);
}
#[test]
fn missing_local_threads_build_the_reference_fallback_bead() {
for (identifier, title) in [(r"name {chapter}", "chapter"), ("num 2", "2")] {
let (reference, native, messages) = pair(&format!(
"\\pdfcatalog{{}} openaction thread {identifier} {PAGE}"
));
assert!(
messages
.iter()
.any(|message| message.contains("thread destination"))
);
for pdf in [&reference, &native] {
let threads = get(pdf, pdf.catalog().unwrap(), b"Threads")
.as_array()
.unwrap();
assert_eq!(threads.len(), 1);
let thread_id = threads[0].as_reference().unwrap();
let thread = pdf.get_object(thread_id).unwrap().as_dict().unwrap();
let bead_id = thread.get(b"F").unwrap().as_reference().unwrap();
let bead = pdf.get_object(bead_id).unwrap().as_dict().unwrap();
let info = get(pdf, thread, b"I").as_dict().unwrap();
assert_eq!(
info.get(b"Title").unwrap().as_str().unwrap(),
title.as_bytes()
);
assert_eq!(bead.get(b"T").unwrap().as_reference().unwrap(), thread_id);
assert_eq!(bead.get(b"V").unwrap().as_reference().unwrap(), bead_id);
assert_eq!(bead.get(b"N").unwrap().as_reference().unwrap(), bead_id);
assert_eq!(
bead.get(b"P").unwrap().as_reference().unwrap(),
pdf.get_pages()[&1]
);
assert_eq!(action(pdf).get(b"S").unwrap().as_name().unwrap(), b"Thread");
let destination = action(pdf).get(b"D").unwrap();
if identifier.starts_with("name") {
assert_eq!(destination.as_str().unwrap(), title.as_bytes());
} else {
assert_eq!(destination.as_reference().unwrap(), thread_id);
}
}
}
}
#[test]
fn rejects_duplicate_actions_and_freezes_file_options_only_for_an_action() {
let duplicate = format!(
r"{SETUP}\pdfcatalog{{}} openaction goto page 1 {{/Fit}}
\pdfcatalog{{}} openaction goto page 1 {{/Fit}}{PAGE}\end"
);
let error = run_native(&duplicate).unwrap_err();
assert!(error.message.contains("duplicate of openaction"));
let changed = format!(
r"{SETUP}\pdfminorversion=4 \pdfcatalog{{}} openaction goto page 1 {{/Fit}}
\pdfminorversion=5 {PAGE}\end"
);
assert!(
run_native(&changed)
.unwrap_err()
.message
.contains("version cannot change")
);
let (_, native, _) = pair(&format!(
r"\pdfminorversion=4 \pdfcatalog{{/Lang (en)}}\pdfminorversion=5 {PAGE}"
));
assert_eq!(native.version, "1.5");
let (_, native, _) = pair(&format!(
r"\pdfoutput=0 \pdfcatalog{{/Lang (en)}}\pdfoutput=1 {PAGE}"
));
assert!(native.catalog().unwrap().get(b"Lang").is_err());
}
@@ -334,7 +334,7 @@ fn old_schema_and_missing_unicode_state_are_rejected_even_with_valid_checksums()
let envelope: serde_json::Value = serde_json::from_slice(&encoded).unwrap();
let original: serde_json::Value =
serde_json::from_str(envelope["payload"].as_str().unwrap()).unwrap();
assert_eq!(original["schema"], 22);
assert_eq!(original["schema"], 23);
for (schema, expected) in [
(1, "incompatible native format"),
(2, "incompatible native format"),
@@ -357,7 +357,8 @@ fn old_schema_and_missing_unicode_state_are_rejected_even_with_valid_checksums()
(19, "incompatible native format"),
(20, "incompatible native format"),
(21, "incompatible native format"),
(22, "glyph_unicode"),
(22, "incompatible native format"),
(23, "glyph_unicode"),
] {
let mut payload = original.clone();
payload["schema"] = schema.into();
@@ -164,7 +164,7 @@ fn new_format_owns_vcenter_and_boxed_math_without_reinjecting_old_meanings() {
let envelope: serde_json::Value = serde_json::from_slice(&bytes).unwrap();
let payload: serde_json::Value =
serde_json::from_str(envelope["payload"].as_str().unwrap()).unwrap();
assert_eq!(payload["schema"], 22);
assert_eq!(payload["schema"], 23);
let executor = FormatImage::decode(&bytes)
.unwrap()
.new_job(
+5 -1
View File
@@ -94,7 +94,8 @@ schema22 组合版全工作区1591项通过。按470项冻结源码指纹合入
schema23 目录候选实际写出字典、打开动作和目的地引用,519项内核及定向回归
通过。新格式已由真实 LaTeX 启动生成。原样 Springer Nature、Elsevier 单栏和
双栏推进至 `\pdfinfo`,原样 CVPR 推进至 `\firstaid@cref@updatelabeldata`。
七项 article、完整原样矩阵和全工作区回归正在复验。
七项 article 的21轮和全工作区1597项通过。原样出版矩阵参考10/10,
原生生成3/10。已按473项冻结源码指纹合入主线。
检查点宿主的独立候选用真实私有文件隔离 aux、日志和账本,TeX 以原逻辑名
读取暂存内容。组合候选在同一版本门禁内发布检查点续跑的 aux、日志、账本和
@@ -102,6 +103,9 @@ PDF,并暴露完成的结果。实测重放7项宿主调用,当前续跑的
源位置映射等于独立全量编译;过期、取消和外部文件冲突保留已发布文件,
安装中途失败恢复已替换文件并撤销本轮新文件。真实续跑发布和宿主共17项回归通过。
编辑器自动选择、原样 A3 暂存发布、多文件崩溃恢复和实时延迟仍待验收。
共享编译入口的定向复验通过。原样 A3 首轮捕获时,要求输入栈只剩物理源文件
会选中已读入第7页待编辑行的字节472,跳过上一个安全边界411。新候选允许
保留入口上的活动宏与参数游标,并沿同一路径结束 PDF 目录。复验仍在运行。
同一编译结果的差量预览通过37项原生预览与 PK 字体关联回归。原样8页 A3
编辑第7页只发布该页,复用其余7个 SVG,末页来源位置随本轮更新。当前 PDF、
+3 -1
View File
@@ -166,7 +166,9 @@ schema23 候选已对照 PDF 目录和打开动作,包括直接与间接目的
Springer Nature、Elsevier CAS SC 和 CAS DC 的新首处缺失是 `\pdfinfo`。
CVPR 在正文的首个引用处进入实际 LaTeX firstaid 的宏调用,首停
`\firstaid@cref@updatelabeldata`。报告保存在 `target/p3-pdf-catalog`,
完整矩阵待复验完成。
完整矩阵参考10/10、原生生成3/10,报告为
`target/p3-pdf-catalog/publisher-matrix/report.json`。同一冻结候选的全工作区
1597项与七项 article 共21轮通过,schema23 已合入主线。
单纯生成 PDF 或 DVI 只说明编译路径可达。完整验收要在参考环境闭合后比较页数、
双栏位置及跨栏材料、实际字体/字形、图表浮动、引用收敛、词框及墨迹;测试源