3 Commits
13 changed files with 436 additions and 114 deletions

No files matched your search

+33 -11
View File
@@ -151,8 +151,8 @@ pub(super) enum BoxPaint<'a> {
PdfColor,
PdfGraphics,
PdfTextSpace(crate::pdf_device::text_spaces::SpaceOperation),
RowStart(RowLayout),
PdfLink(&'a OutputNode, Option<RowLayout>),
RowStart(BoxLayout),
PdfLink(&'a OutputNode, BoxLayout),
Output(&'a OutputNode),
}
@@ -197,7 +197,8 @@ pub(super) struct LeaderEffects {
}
#[derive(Clone, Copy)]
pub(super) struct RowLayout {
pub(super) struct BoxLayout {
pub horizontal: bool,
pub left: i64,
pub baseline: i64,
pub width: i64,
@@ -802,14 +803,30 @@ impl NativeBox {
match &self.content {
BoxContent::Horizontal(nodes) => {
budget.inside_leader(nodes.len())?;
let row = RowLayout { left: x, baseline: y, width: self.width,
height: self.height, depth: self.depth, level };
let row = BoxLayout {
horizontal: true,
left: x,
baseline: y,
width: self.width,
height: self.height,
depth: self.depth,
level,
};
if links {
emit(x, y, BoxPaint::RowStart(row));
}
walk_row(&self.packed_horizontal().unwrap(), row, links, budget, emit)?;
}
BoxContent::Vertical(nodes) => {
let container = BoxLayout {
horizontal: false,
left: x,
baseline: y,
width: self.width,
height: self.height,
depth: self.depth,
level,
};
let mut cursor = y - self.height;
let (mut cumulative, mut previous) = (0, 0);
for node in nodes {
@@ -872,7 +889,7 @@ impl NativeBox {
cursor += b.depth;
}
NativeVerticalNode::Output(node) => {
walk_output(node, x, cursor, None, links, emit);
walk_output(node, x, cursor, container, links, emit);
if let Some(image) = node.image_box() {
cursor += image.height;
emit(x, cursor, BoxPaint::Box(&image));
@@ -900,7 +917,12 @@ impl NativeBox {
budget.leader_depth += 1;
let result = self.walk_at(x, y, level, links, budget, &mut |x, y, paint| {
if !matches!(paint, BoxPaint::Output(o) if matches!(o.operation,
OutputOperation::Open { .. } | OutputOperation::Write { .. } | OutputOperation::Close { .. })) {
OutputOperation::Open { .. } | OutputOperation::Write { .. } | OutputOperation::Close { .. }))
&& !matches!(paint, BoxPaint::PdfLink(node, _) if matches!(
node.operation,
OutputOperation::PdfLink(crate::pdf_device::links::LinkNode::Destination { .. })
))
{
emit(x, y, paint);
}
});
@@ -917,7 +939,7 @@ pub(super) fn bp(n: i64) -> i64 {
}
fn walk_row(
items: &[PackedHorizontal<'_>],
row: RowLayout,
row: BoxLayout,
links: bool,
budget: &mut WalkBudget<'_>,
emit: &mut dyn FnMut(i64, i64, BoxPaint<'_>),
@@ -958,7 +980,7 @@ fn walk_row(
x += width;
}
PackedHorizontal::Output(node) => {
walk_output(node, x, y, Some(row), links, emit);
walk_output(node, x, y, row, links, emit);
if let Some(image) = node.image_box() {
emit(x, y, BoxPaint::Box(&image));
x += image.width;
@@ -974,7 +996,7 @@ fn walk_output(
node: &OutputNode,
x: i64,
y: i64,
row: Option<RowLayout>,
container: BoxLayout,
links: bool,
emit: &mut dyn FnMut(i64, i64, BoxPaint<'_>),
) {
@@ -986,7 +1008,7 @@ fn walk_output(
} else if let OutputOperation::PdfTextSpace(operation) = node.operation {
emit(x, y, BoxPaint::PdfTextSpace(operation));
} else if links && node.is_pdf_link() {
emit(x, y, BoxPaint::PdfLink(node, row));
emit(x, y, BoxPaint::PdfLink(node, container));
}
}
pub(super) fn box_paragraph(mut b: NativeBox) -> Paragraph {
@@ -618,6 +618,9 @@ impl Printer<'_> {
LinkNode::Running(true) => "pdfrunninglinkon",
LinkNode::Destination { .. } => "pdfdest",
});
if let LinkNode::Destination { structure: Some(object), .. } = node {
self.literal(&format!(" struct{object}"));
}
}
OutputOperation::PdfLiteral { mode, shipout, tokens } => {
use crate::pdf_device::PdfLiteralMode;
@@ -1,6 +1,6 @@
use super::*;
use crate::pdf_device::{
catalog::{CatalogAction, CatalogTarget, PdfOutline},
catalog::{CatalogAction, CatalogTarget, PdfOutline, StructureTarget},
links::DestinationId,
};
@@ -78,7 +78,7 @@ impl Executor {
}
}
fn scan_catalog_action(
pub(super) fn scan_catalog_action(
&mut self,
files: &mut impl SourceProvider,
) -> Result<CatalogAction, Error> {
@@ -95,10 +95,21 @@ impl Executor {
None
};
let structure = if self.keyword("struct", files)? {
if !goto || file.is_none() {
return self.fail("current PDF structure actions require a remote GoTo");
if !goto {
return self.fail("only PDF GoTo actions can target a structure");
}
Some(self.scan_pdf_bytes(files)?)
Some(if file.is_some() {
StructureTarget::Remote(self.scan_pdf_bytes(files)?)
} else if self.keyword("name", files)? {
let name = self.scan_pdf_tokens(files)?;
StructureTarget::Local(DestinationId::Name(self.token_list_text(&name)))
} else if self.keyword("num", files)? {
StructureTarget::Local(DestinationId::Number(
self.positive_pdf_number("structure destination number", files)?,
))
} else {
return self.fail("PDF structure destination identifier type missing");
})
} else {
None
};
@@ -6,7 +6,7 @@ use crate::pdf_device::{
PageDestination, PageLinks,
},
};
use crate::execution::boxes::{BoxPaint, RowLayout};
use crate::execution::boxes::{BoxPaint, BoxLayout};
#[derive(Clone, Copy)]
struct Segment {
@@ -51,7 +51,7 @@ impl ActiveLink {
fn start_segment(
&mut self,
output: &mut PageLinks,
row: RowLayout,
row: BoxLayout,
point: [i64; 2],
transform: (Affine, bool),
margin: i64,
@@ -102,6 +102,23 @@ impl ActiveLink {
}
impl Executor {
fn scan_pdf_rule(&mut self, files: &mut impl SourceProvider) -> Result<[Option<i32>; 3], Error> {
let mut dimensions = [None; 3];
loop {
let index = if self.keyword("width", files)? {
0
} else if self.keyword("height", files)? {
1
} else if self.keyword("depth", files)? {
2
} else {
break;
};
dimensions[index] = Some(self.dimension(false, false, files)?.amount);
}
Ok(dimensions)
}
pub(super) fn scan_pdf_link(
&mut self,
command: Primitive,
@@ -130,19 +147,7 @@ impl Executor {
.get_or_insert_with(Default::default)
.reserve_link(self.limits.tokens)
.map_err(|error| self.error(error, self.current))?;
let (mut width, mut height, mut depth) = (None, None, None);
loop {
let target = if self.keyword("width", files)? {
&mut width
} else if self.keyword("height", files)? {
&mut height
} else if self.keyword("depth", files)? {
&mut depth
} else {
break;
};
*target = Some(self.dimension(false, false, files)?.amount);
}
let [width, height, depth] = self.scan_pdf_rule(files)?;
let attributes = if self.keyword("attr", files)? {
self.scan_pdf_tokens(files)?
} else {
@@ -150,10 +155,8 @@ impl Executor {
};
let action = if self.keyword("user", files)? {
LinkAction::User(self.scan_pdf_tokens(files)?)
} else if self.keyword("goto", files)? && self.keyword("name", files)? {
LinkAction::GotoName(self.scan_pdf_tokens(files)?)
} else {
return self.fail("expected a user or named goto PDF link action");
LinkAction::Catalog(self.scan_catalog_action(files)?)
};
self.state
.pdf_objects
@@ -174,6 +177,11 @@ impl Executor {
LinkNode::Running(command == Primitive::Pdfrunninglinkon)
}
Primitive::Pdfdest => {
let structure = if self.keyword("struct", files)? {
Some(self.positive_pdf_number("structure object number", files)? as u32)
} else {
None
};
let destination = if self.keyword("name", files)? {
DestinationId::Name(self.scan_pdf_tokens(files)?)
} else if self.keyword("num", files)? {
@@ -188,6 +196,8 @@ impl Executor {
None
};
DestinationView::Xyz(zoom)
} else if self.keyword("fitr", files)? {
DestinationView::FitR(self.scan_pdf_rule(files)?)
} else {
let mut view = None;
for (name, candidate) in [
@@ -205,7 +215,7 @@ impl Executor {
}
view.ok_or_else(|| self.error("expected PDF destination view", span))?
};
LinkNode::Destination { destination, view }
LinkNode::Destination { destination, view, structure }
}
_ => unreachable!(),
};
@@ -234,7 +244,7 @@ impl Executor {
b.walk_pdf_links(&mut |x, y, item| {
if failure.is_some() { return; }
let (x, y) = (x + origin_x, y + origin_y);
let absolute_row = |mut row: RowLayout| {
let absolute_row = |mut row: BoxLayout| {
row.left += origin_x;
row.baseline += origin_y;
row
@@ -261,23 +271,25 @@ impl Executor {
link.start_segment(&mut output, absolute_row(row), [x, y], transform, margin);
}
}
BoxPaint::PdfLink(node, row) => {
BoxPaint::PdfLink(node, container) => {
let container = absolute_row(container);
self.current = node.span;
let OutputOperation::PdfLink(link) = &node.operation else { unreachable!() };
match link {
LinkNode::Start(layout) => {
let Some(row) = row.map(absolute_row) else {
if !container.horizontal {
failure = Some(self.error("PDF link start arrived outside a horizontal list", node.span));
return;
};
}
let attributes = self.token_list_text(&layout.attributes);
let action = match &layout.action {
LinkAction::User(tokens) => AnnotationAction::User(self.token_list_text(tokens)),
LinkAction::GotoName(tokens) => AnnotationAction::GotoName(self.token_list_text(tokens)),
LinkAction::Catalog(action) => AnnotationAction::Catalog(action.clone()),
};
let mut start = ActiveLink { layout: layout.clone(), attributes,
action, level: row.level, segment: None };
start.start_segment(&mut output, row, [x, y], transform, margin);
action, level: container.level, segment: None };
start.start_segment(&mut output, container, [x, y], transform, margin);
// The scan-time object number belongs only to the
// initial annotation, never to a continuation row.
output.annotations.last_mut().unwrap().object_number = layout.object_number;
@@ -288,7 +300,7 @@ impl Executor {
failure = Some(self.error("\\pdfendlink used without \\pdfstartlink", node.span));
return;
};
if row.is_none_or(|r| r.level != link.level) {
if !container.horizontal || container.level != link.level {
let result = files.observe_diagnostic(WriteDestination::TerminalAndLog,
"pdfTeX warning: pdftex: \\pdfendlink ended up in different nesting level than \\pdfstartlink\n");
if let Err(error) = result {
@@ -299,13 +311,25 @@ impl Executor {
link.end_segment(&mut output, x, margin);
}
LinkNode::Running(enabled) => self.pdf_running_links = *enabled,
LinkNode::Destination { destination, view } => {
LinkNode::Destination { destination, view, structure } => {
let destination = match destination {
DestinationId::Name(tokens) => DestinationId::Name(self.token_list_text(tokens)),
DestinationId::Number(number) => DestinationId::Number(*number),
};
let view = view.map_rectangle(|[width, height, depth]| {
let margin = i64::from(self.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));
if transform.1 {
link_rect([x, top, right, bottom], transform.0, margin)
} else {
[x - margin, top - margin, right + margin, bottom + margin]
}
});
output.destinations.push(PageDestination {
destination, point: map_point(transform.0, x, y), view: *view,
destination, point: map_point(transform.0, x, y), view,
structure: *structure,
});
}
}
@@ -8,8 +8,10 @@ use std::{
sync::{Arc, Mutex, OnceLock, Weak},
};
const SCHEMA: u32 = 45;
const COMPATIBLE_SCHEMAS: [u32; 14] = [27, 28, 31, 32, 33, 34, 35, 36, 37, 38, 39, 43, 44, SCHEMA];
const SCHEMA: u32 = 47;
const COMPATIBLE_SCHEMAS: [u32; 16] = [
27, 28, 31, 32, 33, 34, 35, 36, 37, 38, 39, 43, 44, 45, 46, SCHEMA,
];
const ENGINE: &str = concat!("texrra-native/", env!("CARGO_PKG_VERSION"));
#[derive(serde::Serialize, serde::Deserialize)]
@@ -35,6 +35,7 @@ pub enum Parameter {
Pdfhorigin,
Pdfvorigin,
Pdflinkmargin,
Pdfdestmargin,
Errorcontextlines,
Showboxbreadth,
Showboxdepth,
@@ -152,6 +153,7 @@ impl Parameter {
Self::Pdfhorigin,
Self::Pdfvorigin,
Self::Pdflinkmargin,
Self::Pdfdestmargin,
Self::Errorcontextlines,
Self::Showboxbreadth,
Self::Showboxdepth,
@@ -245,6 +247,7 @@ impl Parameter {
| Self::Pdfhorigin
| Self::Pdfvorigin
| Self::Pdflinkmargin
| Self::Pdfdestmargin
| Self::Delimitershortfall
| Self::Predisplaysize
| Self::Displaywidth
+120 -62
View File
@@ -14,7 +14,7 @@ use rusttype::Font;
use crate::cmr10::Cmr10Metrics;
use crate::pdf_device::{
catalog::{CatalogAction, CatalogTarget, PdfOutline},
catalog::{CatalogAction, CatalogTarget, PdfOutline, StructureTarget},
links::DestinationId,
};
use crate::render::{DisplayItem, DisplayList, FontFace};
@@ -1393,7 +1393,8 @@ fn native_pdf(
|| !font_attributes.is_empty()
|| !page_tree.is_empty()
|| pages.iter().any(|page| !page.pdf_resources.entries.is_empty()
|| !page.pdf_resources.attributes.is_empty())
|| !page.pdf_resources.attributes.is_empty()
|| page.pdf_links.destinations.iter().any(|destination| destination.structure.is_some()))
{
let (catalog, info) = if raw_objects.is_some() {
(
@@ -1694,15 +1695,29 @@ fn pdf_file_specification(out: &mut Vec<u8>, file: &[u8]) {
out.push(b' ');
}
fn write_catalog_action(
#[derive(Default)]
struct PdfNavigation {
pages: Vec<usize>,
named: BTreeMap<String, String>,
numbered: BTreeMap<i32, usize>,
structures: BTreeMap<DestinationId<String>, usize>,
threads: BTreeMap<DestinationId<String>, usize>,
}
fn destination_identifier(id: &DestinationId<String>) -> String {
match id {
DestinationId::Name(name) => format!("name{{{name}}}"),
DestinationId::Number(number) => format!("num{number}"),
}
}
fn catalog_action_bytes(
action: &CatalogAction,
page_ids: &[usize],
destinations: &mut BTreeMap<String, String>,
numbers: &mut BTreeMap<i32, usize>,
threads: &mut BTreeMap<DestinationId<String>, usize>,
destinations: &mut PdfNavigation,
objects: &mut Vec<Vec<u8>>,
diagnostics: &mut Vec<String>,
) -> usize {
) -> Vec<u8> {
let PdfNavigation { pages, named, numbered, structures, threads } = destinations;
let mut output = b"<< ".to_vec();
match action {
CatalogAction::User(object) => output.clone_from(object),
@@ -1723,20 +1738,20 @@ fn write_catalog_action(
}
match target {
CatalogTarget::Destination(DestinationId::Name(name)) => {
if file.is_none() && !destinations.contains_key(name) {
if file.is_none() && !named.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]));
named.insert(name.clone(), format!("[{} 0 R /Fit]", pages[0]));
}
output.extend_from_slice(pdf_text(name).as_bytes());
}
CatalogTarget::Destination(DestinationId::Number(number)) => {
let id = numbers.entry(*number).or_insert_with(|| {
let id = numbered.entry(*number).or_insert_with(|| {
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.push(format!("[{} 0 R /Fit]", pages[0]).into_bytes());
objects.len()
});
write!(&mut output, "{id} 0 R").unwrap();
@@ -1746,7 +1761,7 @@ fn write_catalog_action(
if file.is_some() {
write!(&mut output, "[{index} ").unwrap();
} else {
let page = page_ids.get(index).copied().unwrap_or_else(|| {
let page = pages.get(index).copied().unwrap_or_else(|| {
diagnostics.push(format!(
"page {number} has been referenced but does not exist"
));
@@ -1759,9 +1774,24 @@ fn write_catalog_action(
output.push(b']');
}
}
if let Some(structure) = structure {
output.extend_from_slice(b" /SD ");
output.extend_from_slice(structure);
match structure {
Some(StructureTarget::Local(destination)) => {
let id = structures.entry(destination.clone()).or_insert_with(|| {
diagnostics.push(format!(
"structure destination {} has been referenced but does not exist",
destination_identifier(destination)
));
// pdfTeX leaves the missing destination in the free list.
objects.push(Vec::new());
objects.len()
});
write!(&mut output, " /SD {id} 0 R").unwrap();
}
Some(StructureTarget::Remote(bytes)) => {
output.extend_from_slice(b" /SD ");
output.extend_from_slice(bytes);
}
None => {}
}
output.extend_from_slice(b"\n>>");
}
@@ -1784,7 +1814,7 @@ fn write_catalog_action(
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]
pages[0]
).into_bytes());
thread
}));
@@ -1803,8 +1833,7 @@ fn write_catalog_action(
output.extend_from_slice(b" >>");
}
}
objects.push(output);
objects.len()
output
}
#[derive(Clone, Default)]
@@ -2180,9 +2209,8 @@ 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 navigation = PdfNavigation::default();
let mut annotation_actions = Vec::new();
let pdf_version = pages
.first()
.and_then(|page| page.pdf.as_ref())
@@ -2342,7 +2370,7 @@ fn write_pdf(
} else {
format!(" /Annots [{annotation_refs}]")
};
page_ids.push(page_id);
navigation.pages.push(page_id);
kids.push(format!("{page_id} 0 R"));
let decorated = !list.pdf_resources.attributes.is_empty();
let mut page = b"<< /Type /Page".to_vec();
@@ -2435,25 +2463,33 @@ fn write_pdf(
use crate::pdf_device::links::AnnotationAction;
let [left, top, right, bottom] = annotation.rect;
let coordinates = [left, height - bottom, right, height - top].map(physical);
let action = match &annotation.action {
AnnotationAction::User(raw) => raw.clone(),
AnnotationAction::GotoName(name) =>
format!("/Subtype /Link /A << /S /GoTo /D {} >>", pdf_text(name)),
};
let entries = remapped.as_ref().and_then(|resources|
resources.annotations[page_index][index].as_deref());
let body = if let Some(entries) = entries {
let mut body = if let Some(entries) = entries {
let mut body = format!("<< /Type /Annot /Rect [{}] ", coordinates.join(" ")).into_bytes();
body.extend_from_slice(entries);
if matches!(annotation.action, AnnotationAction::GotoName(_)) {
body.extend_from_slice(action.as_bytes());
}
body.extend_from_slice(b" >>");
body
} else {
format!("<< /Type /Annot {} /Rect [{}] {} >>",
annotation.attributes, coordinates.join(" "), action).into_bytes()
format!("<< /Type /Annot {} /Rect [{}] ",
annotation.attributes, coordinates.join(" ")).into_bytes()
};
match &annotation.action {
AnnotationAction::User(raw) if entries.is_none() => body.extend_from_slice(raw.as_bytes()),
AnnotationAction::User(_) => {}
AnnotationAction::GotoName(name) => {
write!(&mut body, " /Subtype /Link /A << /S /GoTo /D {} >>", pdf_text(name)).unwrap();
}
AnnotationAction::Catalog(action) => {
// A local action may use a structure or page in a later shipout.
body.extend_from_slice(b" /Subtype /Link /A ");
annotation_actions.push((id, body, action));
if id == objects.len() + 1 {
objects.push(Vec::new());
}
continue;
}
}
body.extend_from_slice(b" >>");
if id == objects.len() + 1 {
objects.push(body);
} else {
@@ -2476,17 +2512,37 @@ fn write_pdf(
DestinationView::FitV => format!("/FitV {x}"),
DestinationView::FitBH => format!("/FitBH {y}"),
DestinationView::FitBV => format!("/FitBV {x}"),
};
let object = || format!("[{page_id} 0 R {view}]");
match &destination.destination {
DestinationId::Name(name) => {
destinations.entry(name.clone()).or_insert_with(object);
DestinationView::FitR([left, top, right, bottom]) => {
let coordinates = [left, height - bottom, right, height - top].map(physical);
format!("/FitR {}", coordinates.join(" "))
}
DestinationId::Number(number) => {
numbers.entry(*number).or_insert_with(|| {
objects.push(object().into_bytes());
objects.len()
});
};
if let Some(number) = destination.structure {
use std::collections::btree_map::Entry;
match navigation.structures.entry(destination.destination.clone()) {
Entry::Vacant(entry) => {
let structure = remapped.as_ref().expect("structure objects were remapped")
.structure_objects[&number];
objects.push(format!("[{structure} 0 R {view}]").into_bytes());
entry.insert(objects.len());
}
Entry::Occupied(entry) => diagnostics.push(format!(
"structure destination with the same identifier ({}) has been already used, duplicate ignored",
destination_identifier(entry.key())
)),
}
} else {
let object = || format!("[{page_id} 0 R {view}]");
match &destination.destination {
DestinationId::Name(name) => {
navigation.named.entry(name.clone()).or_insert_with(object);
}
DestinationId::Number(number) => {
navigation.numbered.entry(*number).or_insert_with(|| {
objects.push(object().into_bytes());
objects.len()
});
}
}
}
}
@@ -2503,6 +2559,11 @@ fn write_pdf(
}
objects[1].extend_from_slice(b" >>");
for (id, mut body, action) in annotation_actions {
body.extend(catalog_action_bytes(action, &mut navigation, &mut objects, diagnostics));
body.extend_from_slice(b" >>");
objects[id - 1] = body;
}
let mut catalog = "<< /Type /Catalog /Pages 2 0 R".to_owned();
if !metadata.outline.is_empty() {
let root_id = objects.len() + 1;
@@ -2538,9 +2599,9 @@ fn write_pdf(
}
for (index, entry) in metadata.outline.iter().enumerate() {
let page_id = page_ids
let page_id = navigation.pages
.get(entry.page)
.or_else(|| page_ids.last())
.or_else(|| navigation.pages.last())
.copied()
.unwrap_or(0);
let parent_id = parents[index].map_or(root_id, |parent| item_ids[parent]);
@@ -2584,30 +2645,27 @@ fn write_pdf(
catalog.push_str(&format!(" /Outlines {root_id} 0 R"));
}
let extra = unicode.and_then(|options| options.catalog);
let mut threads = BTreeMap::new();
let action = extra.and_then(|extra| extra.open_action.as_ref()).map(|action| {
write_catalog_action(
action, &page_ids, &mut destinations, &mut numbers, &mut threads, &mut objects,
diagnostics,
)
});
let mut action_object = |action| {
let body = catalog_action_bytes(action, &mut navigation, &mut objects, diagnostics);
objects.push(body);
objects.len()
};
let action = extra.and_then(|extra| extra.open_action.as_ref()).map(&mut action_object);
if let Some(extra) = extra.filter(|extra| !extra.outlines.is_empty()) {
let action_ids: Vec<_> = extra.outlines.iter().map(|outline| {
write_catalog_action(
&outline.action, &page_ids, &mut destinations, &mut numbers, &mut threads,
&mut objects, diagnostics,
)
}).collect();
let action_ids: Vec<_> = extra.outlines.iter()
.map(|outline| action_object(&outline.action))
.collect();
let outlines = write_pdf_outlines(&extra.outlines, &action_ids, &mut objects);
catalog.push_str(&format!(" /Outlines {outlines} 0 R"));
}
if !threads.is_empty() {
let mut ids: Vec<_> = threads.into_values().collect();
if !navigation.threads.is_empty() {
let mut ids: Vec<_> = navigation.threads.into_values().collect();
ids.sort_unstable_by(|left, right| right.cmp(left));
let references: Vec<_> = ids.iter().map(|id| format!("{id} 0 R")).collect();
objects.push(format!("[{}]", references.join(" ")).into_bytes());
catalog.push_str(&format!(" /Threads {} 0 R", objects.len()));
}
let destinations = navigation.named;
if !destinations.is_empty() {
let mut entries = Vec::with_capacity(destinations.len());
let first = pdf_text(destinations.first_key_value().unwrap().0);
@@ -17,13 +17,13 @@ pub(crate) struct PdfOutline<A> {
}
#[derive(Clone, Debug, PartialEq, Eq, Hash, serde::Serialize, serde::Deserialize)]
pub(crate) enum CatalogAction {
pub enum CatalogAction {
User(Vec<u8>),
GoTo {
target: CatalogTarget,
file: Option<Vec<u8>>,
window: Option<bool>,
structure: Option<Vec<u8>>,
structure: Option<StructureTarget>,
},
Thread {
destination: DestinationId<String>,
@@ -48,7 +48,10 @@ impl CatalogAction {
CatalogTarget::Page { view, .. } => view.len(),
};
target_len + file.as_ref().map_or(0, Vec::len)
+ structure.as_ref().map_or(0, Vec::len)
+ structure.as_ref().map_or(0, |structure| match structure {
StructureTarget::Local(id) => destination_len(id),
StructureTarget::Remote(bytes) => bytes.len(),
})
}
Self::Thread { destination, file } => {
destination_len(destination) + file.as_ref().map_or(0, Vec::len)
@@ -58,7 +61,15 @@ impl CatalogAction {
}
#[derive(Clone, Debug, PartialEq, Eq, Hash, serde::Serialize, serde::Deserialize)]
pub(crate) enum CatalogTarget {
pub enum CatalogTarget {
Destination(DestinationId<String>),
Page { number: i32, view: Vec<u8> },
}
/// Local identifier or explicit remote PDF structure destination.
#[derive(Clone, Debug, PartialEq, Eq, Hash, serde::Serialize, serde::Deserialize)]
#[serde(untagged)]
pub enum StructureTarget {
Local(DestinationId<String>),
Remote(Vec<u8>),
}
+28 -2
View File
@@ -1,10 +1,12 @@
//! Typed link nodes and the annotations produced when TeX ships their lists.
use super::catalog::CatalogAction;
use crate::execution::Token;
#[derive(Clone, Debug, PartialEq, Eq, Hash, serde::Serialize, serde::Deserialize)]
pub enum LinkAction {
User(Vec<Token>),
GotoName(Vec<Token>),
Catalog(CatalogAction),
}
#[derive(Clone, Debug, PartialEq, Eq, Hash, serde::Serialize, serde::Deserialize)]
@@ -19,7 +21,7 @@ pub struct LinkStart {
}
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, serde::Serialize, serde::Deserialize)]
pub enum DestinationView {
pub enum DestinationView<Rectangle = [Option<i32>; 3]> {
Xyz(Option<i32>),
Fit,
FitH,
@@ -27,6 +29,25 @@ pub enum DestinationView {
FitB,
FitBH,
FitBV,
FitR(Rectangle),
}
impl<Rectangle> DestinationView<Rectangle> {
pub(crate) fn map_rectangle<Output>(
self,
map: impl FnOnce(Rectangle) -> Output,
) -> DestinationView<Output> {
match self {
Self::Xyz(zoom) => DestinationView::Xyz(zoom),
Self::Fit => DestinationView::Fit,
Self::FitH => DestinationView::FitH,
Self::FitV => DestinationView::FitV,
Self::FitB => DestinationView::FitB,
Self::FitBH => DestinationView::FitBH,
Self::FitBV => DestinationView::FitBV,
Self::FitR(rectangle) => DestinationView::FitR(map(rectangle)),
}
}
}
#[derive(
@@ -45,6 +66,8 @@ pub enum LinkNode {
Destination {
destination: DestinationId<Vec<Token>>,
view: DestinationView,
#[serde(default, skip_serializing_if = "Option::is_none")]
structure: Option<u32>,
},
}
@@ -52,6 +75,7 @@ pub enum LinkNode {
pub enum AnnotationAction {
User(String),
GotoName(String),
Catalog(CatalogAction),
}
#[derive(Clone, Debug, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
@@ -68,7 +92,9 @@ pub struct LinkAnnotation {
pub struct PageDestination {
pub destination: DestinationId<String>,
pub point: [i64; 2],
pub view: DestinationView,
pub view: DestinationView<[i64; 4]>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub structure: Option<u32>,
}
#[derive(Clone, Debug, Default, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
@@ -427,6 +427,7 @@ pub(crate) struct ResourceOutput {
values: BTreeMap<u32, Object>,
page_references: BTreeMap<u32, u32>,
link_references: BTreeMap<u32, Option<(usize, usize)>>,
structure_references: BTreeSet<u32>,
page_entries: Vec<Dictionary>,
page_attributes: Vec<Dictionary>,
page_tree_attributes: Dictionary,
@@ -443,6 +444,7 @@ pub(crate) struct RemappedResources {
pub fonts: BTreeMap<FontId, Vec<u8>>,
pub page_objects: BTreeMap<usize, usize>,
pub link_objects: BTreeMap<(usize, usize), usize>,
pub structure_objects: BTreeMap<u32, usize>,
pub annotations: Vec<Vec<Option<Vec<u8>>>>,
pub catalog: Option<Vec<u8>>,
pub info: Option<Vec<u8>>,
@@ -537,6 +539,11 @@ impl ResourceOutput {
}
}
}
let structure_references = pages
.iter()
.flat_map(|page| &page.pdf_links.destinations)
.filter_map(|destination| destination.structure)
.collect();
let mut values = BTreeMap::new();
while let Some(number) = pending.pop_first() {
if objects.is_link(number) {
@@ -554,6 +561,7 @@ impl ResourceOutput {
values,
page_references: objects.page_references.clone(),
link_references,
structure_references,
page_entries,
page_attributes,
page_tree_attributes,
@@ -605,6 +613,21 @@ impl ResourceOutput {
remap(&mut object, &ids);
output.push(encode_value(object).expect("valid PDF object in memory"));
}
let structure_objects = self
.structure_references
.into_iter()
.map(|number| {
let id = ids.get(&number).map_or_else(
|| {
// A reference to an unwritten structure keeps a free entry.
output.push(Vec::new());
output.len()
},
|&id| id as usize,
);
(number, id)
})
.collect();
let encode = |dictionary: Dictionary| {
if dictionary.is_empty() {
return Vec::new();
@@ -623,6 +646,7 @@ impl ResourceOutput {
.collect(),
page_objects,
link_objects,
structure_objects,
annotations: self.annotation_entries.into_iter()
.map(|row| row.into_iter().map(|dict| dict.map(&encode)).collect())
.collect(),
+67
View File
@@ -1384,6 +1384,73 @@ DVI 的坐标文件在 PDF 驱动报告 DVI 导出限制前完成,原生 DVI
- `acm-format/receipt.json` 为 `9a2676974b4bfc2d42495ab171b2737ff186253bcb4c6266bc8224a1b0a41e56`。
- `acm-acmtog/receipt.json` 为 `7b135237b60b3e36ea16a464ea3be5dcf55043f837f03f377db7be26b3a59d0e`。
### 本地 PDF 结构目的地
原生 `\pdfdest struct` 在发页时记录结构对象、位置和视图。普通目的地与
结构目的地使用独立的名称和数字空间。书签、文档打开动作和链接共用
本地 GoTo 的扫描和导出。链接可以指向后续页面或后发出的结构目的地。
`/SD` 引用独立的间接数组,数组首项是由真实 PDF 对象表重编号的结构对象。
远程动作仍使用显式 PDF 参数。未发出的结构目的地诊断并保留空闲引用。
重复结构目的地以首个发出的定义为准,leaders 中的目的地被忽略。
[pdfTeX 结构目的地和动作源代码](https://github.com/TeX-Live/texlive-source/blob/trunk/texk/web2c/pdftexdir/pdftex.web)
三个 INITEX 对照验证了名称及数字目的地、远程动作、跨页链接、打开动作、
未发出及重复定义。目标视图的数值和结构树的实际引用匹配 pdfTeX。
比较时解析直接对象及对象引用,消除字典空白及数值尾零的差异。6项 PDF
配置和链接测试通过。保存的链接格式采用 schema46,已用旧 schema45
中真正保存的命名链接盒加载并发页。原有冻结的出版格式可直接加载。
XYZ、Fit 与 FitH/FitV 系列在本阶段覆盖,矩形视图见后续实现。
移动第二页结构位置,续编复用1156步,只重发第二页。第一页链接指向的
结构目标从 9.963 bp 移到 13.948 bp。发布 PDF、SVG 与归一化来源映射
与独立零复用编译一致。
优化版复用原样 schema45、44项源及字体映射,ACM 双栏首次生成7页带标签
的 PDF 2.0。正常 BibTeX 使用原参考文献源,生成的 .bbl 与参考逐字节一致。
原作业连续编译到第5轮,第4/5轮 PDF 与 aux 分别逐字节一致。最终40条
`\bibcite`、12条 `\newlabel` 和29条书签辅助记录均与 pdfTeX 一致。
1049项标签属性的键均相同,其中40项原始结构对象编号不同。
原生最终对象图有1个可解析的本地结构动作和29个缺失,冻结参考有121个
可解析动作。冻结 pdfmanagement 的 pdfTeX 后端以修订号24为结构目的地和
链接的启用门槛,当前原生 profile 为1.40.22。原始版材的标签路由仍不等价。
下一入口按实际差异继续补齐 1.40.23/24 的行为,其中包括 `FitR`、
`\showstream` 与专用字距字体的 `\fontdimen6` 语义,再检验真实后端
选路。矩形视图已于下节完成。
[pdfTeX 发布记录](https://github.com/TeX-Live/texlive-source/blob/trunk/texk/web2c/pdftexdir/NEWS)
[LaTeX 结构目的地启用条件](https://tug.tug.org/pipermail/tex-live-commits/2024-April/029525.html)
回执在 `target/p3-pdf-structure-dest-native`。
- `implementation-receipt.json` 为 `557e7a371eb194a541a1018e5405d0a959aac69c629f31d377d13b651ab626d0`。
- `checkpoint/receipt.json` 为 `6bebb085f684997f1845f3f8e3f917369384ca1efae5d3596768c4de14538a1a`。
- `legacy-link/receipt.json` 为 `eefdee02507881e3901498626f23abf7772e9dad9f1b1e52dcb8a8f5248e7b9e`。
- `related-tests.log` 为 `1c088e4dc5ae755a7f247e5b62be1867f12888b224d455834ddd465b775b62fb`。
- `acm-acmtog/receipt.json` 为 `c9d5bad13a5f9e87f0bd0995053fd0064f9b1bfe7ad568aeea34a4590b538d3d`。
- `acm-bibliography/receipt.json` 为 `6e794ead32c5c55c78864602301f9da8d49650b427ccceff8a6ce49f781e0ad0`。
- `acm-bibliography/comparison.json` 为 `aa358583ee8d0f1857f8a861418e12cb12a0558e8a08247d97eec41c94eb3c6d`。
### PDF 矩形目的地
普通、数字和结构目的地共用 `FitR` 导出。规则尺寸缺省时读取实际
横盒或纵盒的包围尺寸。带图形矩阵的矩形按四角变换计算边界,按
发页时 `\pdfdestmargin` 的局部数值扩边。未变换的有符号尺寸保留
参考端使用的角点顺序。新尺寸参数和拥有型视图进入 schema47。
[pdfTeX 的矩形目的地几何](https://github.com/TeX-Live/texlive-source/blob/trunk/texk/web2c/pdftexdir/pdftex.web)
与 pdfTeX 的五个矩形目的地坐标逐项一致,其中四个实际引用结构元素。
用例包含明确尺寸、横盒和纵盒缺省尺寸、剪切矩阵、负宽度以及按发页实际
分组改变边距。两项 PDF 链接测试通过。只增大第二页目的地边距后续编
复用1156步,实际 PDF 矩形及两页 SVG 和来源映射与独立全量一致。
两页可见绘制均相同,续编没有重发绘制页面。
回执在 `target/p3-pdf-fit-rectangle-native`。
- `receipt.json` 为 `aca26459b723fdc8c6001e933b39619b6a886f161760a9f9377c4c1fad292057`。
- `checkpoint/receipt.json` 为 `9f43c57a440c25faf39f8faa2a1298e45f1e057f481ae818b81a38c60a224e27`。
- `related-tests.log` 为 `d9bb129201a3f82b4ce125bc31d69a5a9d0b30d69868022ccac05790bf852e45`。
### PDF 字面中的矩阵与来源映射
来源映射与 PDF 写入共用设备原点的取整。实际字面中的 `q`、`Q` 和
+14
View File
@@ -643,6 +643,20 @@ acmtog.tex:848 的文档结束处理。首个停止点为 `\tex_mdfivesum:D`,
- `acm-format/receipt.json` 为 `9a2676974b4bfc2d42495ab171b2737ff186253bcb4c6266bc8224a1b0a41e56`。
- `acm-acmtog/receipt.json` 为 `7b135237b60b3e36ea16a464ea3be5dcf55043f837f03f377db7be26b3a59d0e`。
本地结构动作版加载同一冻结 schema45。44项原样输入和字体映射保持相同。
原样 ACM 双栏首次生成7页带标签的 PDF 2.0。BibTeX 成功,.bbl 与冻结参考
逐字节相同。原生第4和第5轮的 PDF 与 aux 分别逐字节收敛。参考对照的40条
文献标签、12条普通标签和29条书签辅助记录完全一致。1049项标签属性在
对象编号归一后内容一致,另外保留原始40个结构对象号的差异。
首次将辅助文件复制到新作业身份的续编被生成文件保护拒绝。正式流程使用原
工作目录和生成文件记录继续,首轮文件归档在 `acm-bibliography/first-publication`。
最终原生有1个可解析的本地结构动作,29个缺失。参考有121个可解析动作。
冻结后端要求 pdfTeX 修订24才启用结构目的地造点与链接。当前 profile 是
1.40.22。出版版面、可访问性及统一验收仍待后续开发验证。
原生比较回执 `target/p3-pdf-structure-dest-native/acm-bibliography/comparison.json`
的 SHA-256 为 `aa358583ee8d0f1857f8a861418e12cb12a0558e8a08247d97eec41c94eb3c6d`。
最终矩阵 `target/publisher-template-matrix/acm-official/matrix-schema29-utf8/report.json`
SHA-256 为 `d914d7c7dfa1ee28dff20e77231fef35e390041cde6180bcc361de83288ec9e1`。其 `preparation/acmart` 保存
DocStrip 记录。同目录的前序依赖失败、补充包指纹和原样源均保留。用现有
+57
View File
@@ -124,3 +124,60 @@ fn real_pdf_link_fragments_and_named_destination_match_pdftex() {
assert_eq!(describe(&compile(&root, source, true)), expected);
fs::remove_dir_all(root).unwrap();
}
#[test]
fn local_structure_action_references_the_shipped_structure_and_later_page() {
let root = std::env::temp_dir().join(format!("texrra-pdf-structure-{}", std::process::id()));
let source = r"\catcode123=1 \catcode125=2
\def\space{ }
\pdfoutput=1 \pdfmajorversion=2 \pdfminorversion=0
\pdfcompresslevel=0 \pdfobjcompresslevel=0
\pdfobj reserveobjnum \count10=\pdflastobj
\pdfobj reserveobjnum \count11=\pdflastobj
\edef\ROOT{\number\count10} \edef\CHILD{\number\count11}
\immediate\pdfobj useobjnum\count11{<< /Type /StructElem /S /Sect /P \ROOT\space 0 R >>}
\immediate\pdfobj useobjnum\count10{<< /Type /StructTreeRoot /K [\CHILD\space 0 R] >>}
\pdfcatalog{/StructTreeRoot \ROOT\space 0 R} openaction goto struct name{anchor} page 2 {/Fit}
\shipout\hbox{\pdfstartlink goto struct name{anchor} name{anchor}
\vrule width10pt height6pt \pdfendlink}
\shipout\hbox{\pdfdest name{anchor} xyz
\pdfdest struct \count11 name{anchor} fitr width4pt height3pt depth2pt \vrule width10pt height6pt}
\end";
let doc = compile(&root, source, true);
let catalog = doc.catalog().unwrap();
let pages = doc.get_pages();
let page = doc.get_object(pages[&1]).unwrap().as_dict().unwrap();
let annotations = resolve(&doc, page.get(b"Annots").unwrap())
.as_array()
.unwrap();
let link = resolve(&doc, &annotations[0]).as_dict().unwrap();
let action = resolve(&doc, link.get(b"A").unwrap()).as_dict().unwrap();
let opener = resolve(&doc, catalog.get(b"OpenAction").unwrap())
.as_dict()
.unwrap();
let page_destination = opener.get(b"D").unwrap().as_array().unwrap();
assert_eq!(page_destination[0].as_reference().unwrap(), pages[&2]);
let structure_destination = opener.get(b"SD").unwrap();
assert_eq!(
action.get(b"SD").unwrap().as_reference().unwrap(),
structure_destination.as_reference().unwrap()
);
let destination = resolve(&doc, structure_destination).as_array().unwrap();
let structure = resolve(&doc, &destination[0]).as_dict().unwrap();
assert_eq!(
structure.get(b"Type").unwrap().as_name().unwrap(),
b"StructElem"
);
assert_eq!(
structure.get(b"P").unwrap().as_reference().unwrap(),
catalog
.get(b"StructTreeRoot")
.unwrap()
.as_reference()
.unwrap()
);
assert_eq!(destination.len(), 6);
assert_eq!(destination[1].as_name().unwrap(), b"FitR");
fs::remove_dir_all(root).unwrap();
}