Ship XDV annotations from measured page ranges
This commit is contained in:
1 parent
515dbe6181
commit
20986b2fd5
16 files changed
+873
-54
No files matched your search
@@ -164,6 +164,8 @@ pub(super) enum BoxPaint<'a> {
|
||||
PdfGraphics,
|
||||
PdfTextSpace(crate::pdf_device::text_spaces::SpaceOperation),
|
||||
RowStart(BoxLayout),
|
||||
ScopeStart(usize),
|
||||
ScopeEnd(usize),
|
||||
PdfLink(&'a OutputNode, BoxLayout),
|
||||
Output(&'a OutputNode),
|
||||
}
|
||||
@@ -172,6 +174,7 @@ struct WalkBudget<'a> {
|
||||
remaining: usize,
|
||||
cancellation: Option<&'a Cancellation>,
|
||||
leader_depth: usize,
|
||||
xdv_annotations: bool,
|
||||
}
|
||||
|
||||
impl WalkBudget<'_> {
|
||||
@@ -180,6 +183,7 @@ impl WalkBudget<'_> {
|
||||
remaining: usize::MAX,
|
||||
cancellation: None,
|
||||
leader_depth: 0,
|
||||
xdv_annotations: false,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -284,6 +288,7 @@ impl NativeBox {
|
||||
remaining: limit,
|
||||
cancellation,
|
||||
leader_depth: 0,
|
||||
xdv_annotations: false,
|
||||
};
|
||||
self.walk_at(0, 0, 0, false, false, &mut budget, &mut |x, y, item| {
|
||||
if let BoxPaint::Output(o) = item {
|
||||
@@ -782,7 +787,8 @@ impl NativeBox {
|
||||
emit(GeometryItem::Output);
|
||||
return;
|
||||
}
|
||||
BoxPaint::RowStart(_) | BoxPaint::PdfLink(_, _) => return,
|
||||
BoxPaint::RowStart(_) | BoxPaint::ScopeStart(_) | BoxPaint::ScopeEnd(_)
|
||||
| BoxPaint::PdfLink(_, _) => return,
|
||||
};
|
||||
if let Some(child) = &b.math_geometry {
|
||||
for p in &child.items {
|
||||
@@ -851,6 +857,19 @@ impl NativeBox {
|
||||
.expect("link traversal of an already measured list");
|
||||
}
|
||||
|
||||
pub(super) fn walk_xdv_annotations(
|
||||
&self,
|
||||
cancellation: Option<&Cancellation>,
|
||||
emit: &mut dyn FnMut(i64, i64, BoxPaint<'_>),
|
||||
) -> Result<(), &'static str> {
|
||||
let mut budget = WalkBudget {
|
||||
cancellation,
|
||||
xdv_annotations: true,
|
||||
..WalkBudget::for_geometry()
|
||||
};
|
||||
self.walk_at(0, 0, 0, false, false, &mut budget, emit)
|
||||
}
|
||||
|
||||
fn walk_at(
|
||||
&self,
|
||||
x: i64,
|
||||
@@ -864,6 +883,10 @@ impl NativeBox {
|
||||
if self.kind.is_unset() {
|
||||
return Ok(());
|
||||
}
|
||||
if budget.xdv_annotations {
|
||||
budget.charge(1)?;
|
||||
emit(x, y, BoxPaint::ScopeStart(level));
|
||||
}
|
||||
match &self.content {
|
||||
BoxContent::Horizontal(nodes) => {
|
||||
budget.inside_leader(nodes.len())?;
|
||||
@@ -975,6 +998,9 @@ impl NativeBox {
|
||||
}
|
||||
}
|
||||
}
|
||||
if budget.xdv_annotations {
|
||||
emit(x, y, BoxPaint::ScopeEnd(level));
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
|
||||
@@ -38,6 +38,7 @@ mod scanning;
|
||||
mod scheduling;
|
||||
mod specials;
|
||||
mod statistics;
|
||||
mod xdv_annotation;
|
||||
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
|
||||
pub struct Limits {
|
||||
@@ -226,6 +227,7 @@ pub struct Executor {
|
||||
io: IoState,
|
||||
pdf_colors: crate::pdf_device::PdfColorStacks,
|
||||
xdv_colors: crate::pdf_device::xdv_color::ColorState,
|
||||
xdv_annotations: crate::pdf_device::xdv_annotation::AnnotationState,
|
||||
pdf_link_stack: Vec<pdf_links::ActiveLink>,
|
||||
pdf_running_links: bool,
|
||||
pdf_interword_spaces: bool,
|
||||
@@ -401,6 +403,7 @@ impl Executor {
|
||||
io: IoState::default(),
|
||||
pdf_colors: Default::default(),
|
||||
xdv_colors: Default::default(),
|
||||
xdv_annotations: Default::default(),
|
||||
pdf_link_stack: Vec::new(),
|
||||
pdf_running_links: true,
|
||||
pdf_interword_spaces: false,
|
||||
|
||||
@@ -400,6 +400,7 @@ impl Executor {
|
||||
let mut has_space_nodes = false;
|
||||
let mut has_explicit_space = false;
|
||||
let mut pdf_objects = Vec::new();
|
||||
let mut xdv_annotations = std::collections::BTreeMap::new();
|
||||
for (index, output) in outputs.into_iter().enumerate() {
|
||||
while font_uses.peek().is_some_and(|usage| usage.before_output == index) {
|
||||
self.current = current;
|
||||
@@ -461,6 +462,9 @@ impl Executor {
|
||||
shipout.xdv_color_steps.insert(graphics_step, program);
|
||||
}
|
||||
None
|
||||
} else if xdv && crate::pdf_device::xdv_annotation::Command::recognize(&special.bytes).is_some() {
|
||||
xdv_annotations.insert(graphics_step, shipout.specials.len());
|
||||
None
|
||||
} else if xdv && self.xdv_page_special(
|
||||
&special,
|
||||
crate::pdf_device::xdv_object::Position {
|
||||
@@ -469,6 +473,7 @@ impl Executor {
|
||||
height: device.page_height,
|
||||
magnification: device.magnification,
|
||||
},
|
||||
graphics_step,
|
||||
&mut shipout.pdf_links,
|
||||
files,
|
||||
)? {
|
||||
@@ -633,6 +638,9 @@ impl Executor {
|
||||
links.xdv_destinations = std::mem::take(&mut shipout.pdf_links.xdv_destinations);
|
||||
shipout.pdf_links = links;
|
||||
}
|
||||
if xdv && (!xdv_annotations.is_empty() || self.xdv_annotations.is_active()) {
|
||||
shipout.pdf_links.xdv_annotations = self.ship_xdv_annotations(&shipout, &xdv_annotations, files)?;
|
||||
}
|
||||
if let Some(pdf) = &mut shipout.device.pdf && xdv {
|
||||
shipout.pdf_background = self.xdv_colors.background();
|
||||
self.state.xdv_setup.apply_version(&mut pdf.file);
|
||||
|
||||
@@ -53,6 +53,7 @@ impl Executor {
|
||||
&mut self,
|
||||
special: &ShipoutSpecial,
|
||||
position: crate::pdf_device::xdv_object::Position,
|
||||
graphics_step: usize,
|
||||
links: &mut crate::pdf_device::links::PageLinks,
|
||||
files: &mut impl SourceProvider,
|
||||
) -> Result<bool, Error> {
|
||||
@@ -82,7 +83,7 @@ impl Executor {
|
||||
let warnings = if catalog.is_some() {
|
||||
navigation.merge_catalog(operands, position, self.limits.tokens)
|
||||
} else {
|
||||
navigation.add_outline(operands, position, self.limits.tokens)
|
||||
navigation.add_outline(operands, position, (position.page, graphics_step, 1), self.limits.tokens)
|
||||
}.map_err(|error| self.error(error, special.span))?;
|
||||
for warning in warnings {
|
||||
files.observe_diagnostic(WriteDestination::TerminalAndLog, &warning)
|
||||
|
||||
@@ -0,0 +1,244 @@
|
||||
//! Measure XDV annotation ranges from the packed lists actually shipped.
|
||||
use super::*;
|
||||
use crate::{
|
||||
execution::boxes::BoxPaint,
|
||||
math_engine_tex::{MathItem, PositionedItem},
|
||||
native_font::VirtualGlyphs,
|
||||
pdf_device::{
|
||||
Affine, PdfGraphics,
|
||||
xdv_annotation::{Annotation, Bounds, Command, Page},
|
||||
xdv_object::Position,
|
||||
},
|
||||
};
|
||||
use std::collections::BTreeMap;
|
||||
|
||||
impl Executor {
|
||||
pub(super) fn ship_xdv_annotations(
|
||||
&mut self,
|
||||
shipout: &NativeShipout,
|
||||
commands: &BTreeMap<usize, usize>,
|
||||
files: &mut impl SourceProvider,
|
||||
) -> Result<Vec<Annotation>, Error> {
|
||||
let mut state = self.xdv_annotations.clone();
|
||||
let mut page = state.page();
|
||||
let page_number = self.shipped_pages + 1;
|
||||
let device = &shipout.device;
|
||||
let origin = [
|
||||
device.horizontal_origin,
|
||||
device.vertical_origin + shipout.box_node.height,
|
||||
];
|
||||
let mut frame = Frame {
|
||||
transform: Affine::IDENTITY,
|
||||
height: device.page_height,
|
||||
magnification: device.magnification,
|
||||
};
|
||||
let mut saved = Vec::new();
|
||||
let mut graphics = 0;
|
||||
let mut span = shipout.box_node.span;
|
||||
let mut failure = None;
|
||||
shipout
|
||||
.box_node
|
||||
.walk_xdv_annotations(self.cancellation.as_ref(), &mut |x, y, node| {
|
||||
if failure.is_some() {
|
||||
return;
|
||||
}
|
||||
let point = [(x + origin[0]) as f64, (y + origin[1]) as f64];
|
||||
let result = match node {
|
||||
BoxPaint::ScopeStart(level) => {
|
||||
page.enter(level);
|
||||
Ok(())
|
||||
}
|
||||
BoxPaint::ScopeEnd(level) => {
|
||||
page.leave(level, (page_number, graphics, 0));
|
||||
Ok(())
|
||||
}
|
||||
BoxPaint::PdfGraphics => {
|
||||
let step = graphics;
|
||||
graphics += 1;
|
||||
if let Some(&index) = commands.get(&step) {
|
||||
let special = &shipout.specials[index];
|
||||
span = special.span;
|
||||
let (command, operands) =
|
||||
Command::recognize(&special.bytes).expect("annotation special");
|
||||
let position = Position {
|
||||
page: page_number,
|
||||
coordinates: frame
|
||||
.transform
|
||||
.point(point[0], point[1])
|
||||
.map(|value| value.round() as i64),
|
||||
height: frame.height,
|
||||
magnification: frame.magnification,
|
||||
};
|
||||
page.apply(
|
||||
command,
|
||||
operands,
|
||||
point,
|
||||
frame.transform,
|
||||
position,
|
||||
(page_number, step, 1),
|
||||
)
|
||||
.and_then(|warnings| {
|
||||
for warning in warnings {
|
||||
files.observe_diagnostic(
|
||||
WriteDestination::TerminalAndLog,
|
||||
&warning,
|
||||
)?;
|
||||
}
|
||||
Ok(())
|
||||
})
|
||||
} else if let Some(operation) = shipout.pdf_graphics_steps.get(step) {
|
||||
match operation {
|
||||
Some(PdfGraphics::Save) => saved.push(frame.transform),
|
||||
Some(
|
||||
operation @ (PdfGraphics::SaveMatrix(matrix)
|
||||
| PdfGraphics::Matrix(matrix)),
|
||||
) => {
|
||||
if matches!(operation, PdfGraphics::SaveMatrix(_)) {
|
||||
saved.push(frame.transform);
|
||||
}
|
||||
frame.transform = frame
|
||||
.transform
|
||||
.concatenate(matrix.about(point[0], point[1], true));
|
||||
}
|
||||
Some(PdfGraphics::Restore { .. }) => {
|
||||
frame.transform =
|
||||
saved.pop().expect("validated graphics stack");
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
if page.tracking()
|
||||
&& let Some((image, _)) = shipout.pdf_special_images.get(&step)
|
||||
{
|
||||
frame.raster(&mut page, point, image);
|
||||
}
|
||||
Ok(())
|
||||
} else {
|
||||
Err("missing XDV annotation graphic position".into())
|
||||
}
|
||||
}
|
||||
BoxPaint::Box(material) if page.tracking() => {
|
||||
if let Some(geometry) = &material.math_geometry {
|
||||
frame.material(
|
||||
&mut page,
|
||||
point,
|
||||
&geometry.items,
|
||||
shipout.virtual_glyphs.as_ref(),
|
||||
)
|
||||
} else {
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
_ => Ok(()),
|
||||
};
|
||||
failure = result.err();
|
||||
})
|
||||
.map_err(|error| self.error(error, span))?;
|
||||
if let Some(error) = failure {
|
||||
return Err(self.error(error, span));
|
||||
}
|
||||
if graphics != shipout.pdf_graphics_steps.len() {
|
||||
return Err(self.error("XDV annotation order does not match its packed list", span));
|
||||
}
|
||||
let annotations = page.finish();
|
||||
self.xdv_annotations = state;
|
||||
Ok(annotations)
|
||||
}
|
||||
}
|
||||
|
||||
struct Frame {
|
||||
transform: Affine,
|
||||
height: i64,
|
||||
magnification: i32,
|
||||
}
|
||||
|
||||
impl Frame {
|
||||
fn expand(&self, page: &mut Page<'_>, [x, y]: [f64; 2], width: i64, height: i64, depth: i64) {
|
||||
page.expand(Bounds::from_logical(
|
||||
[x, y - height as f64, x + width as f64, y + depth as f64],
|
||||
self.transform,
|
||||
self.height,
|
||||
self.magnification,
|
||||
));
|
||||
}
|
||||
|
||||
fn raster(&self, page: &mut Page<'_>, [x, y]: [f64; 2], image: &crate::pdf_image::PdfImageUse) {
|
||||
let placement = image.xdv.as_ref().expect("XDV special image placement");
|
||||
// The driver obtains the link rectangle by converting the lower
|
||||
// corner and each extent to DVI units before the image transform.
|
||||
let unit = f64::from(self.magnification) / 1000.0 * (800.0 / 803.0) / 65536.0;
|
||||
let [left, bottom, width, height] = placement
|
||||
.annotation_box()
|
||||
.map(|coordinate| (coordinate / unit).round() * unit);
|
||||
let [right, top] = [left + width, bottom + height];
|
||||
let placement = Affine(placement.paint_matrix());
|
||||
let corners = [[left, bottom], [left, top], [right, bottom], [right, top]].map(|[u, v]| {
|
||||
let [dx, dy] = placement.point(u, v);
|
||||
[
|
||||
x + dx * 65536.0 * 803.0 / 800.0,
|
||||
y - dy * 65536.0 * 803.0 / 800.0,
|
||||
]
|
||||
});
|
||||
page.expand(Bounds::from_corners(
|
||||
corners,
|
||||
self.transform,
|
||||
self.height,
|
||||
self.magnification,
|
||||
));
|
||||
}
|
||||
|
||||
fn material(
|
||||
&self,
|
||||
page: &mut Page<'_>,
|
||||
[origin_x, origin_y]: [f64; 2],
|
||||
items: &[PositionedItem],
|
||||
virtuals: Option<&VirtualGlyphs>,
|
||||
) -> Result<(), String> {
|
||||
for item in items {
|
||||
let [x, y] = [origin_x + item.x as f64, origin_y + item.y as f64];
|
||||
match &item.item {
|
||||
MathItem::NativeGlyph { font, slot, .. } => {
|
||||
if let Some(packet) = virtuals
|
||||
.and_then(|fonts| fonts.get(&font.id))
|
||||
.and_then(|glyphs| glyphs.get(slot))
|
||||
{
|
||||
self.material(page, [x, y], packet, None)?;
|
||||
} else {
|
||||
let character = char::from(*slot);
|
||||
let metrics = font.metrics();
|
||||
self.expand(
|
||||
page,
|
||||
[x, y],
|
||||
font.advance(*slot),
|
||||
metrics.height(character),
|
||||
metrics.depth(character),
|
||||
);
|
||||
}
|
||||
}
|
||||
MathItem::OpenType(run) => {
|
||||
let face = run.font.face()?;
|
||||
let hhea = face.tables().hhea;
|
||||
let scale = |value| {
|
||||
(run.font.size as f64 * (f64::from(value) / f64::from(face.units_per_em())))
|
||||
as i64
|
||||
};
|
||||
let height = scale(i32::from(hhea.ascender));
|
||||
let depth = -scale(i32::from(hhea.descender));
|
||||
for glyph in &run.glyphs {
|
||||
let width = face
|
||||
.glyph_hor_advance(rustybuzz::ttf_parser::GlyphId(glyph.id))
|
||||
.unwrap_or(0);
|
||||
self.expand(
|
||||
page,
|
||||
[x + glyph.x as f64, y + glyph.y as f64],
|
||||
scale(i32::from(width)),
|
||||
height,
|
||||
depth,
|
||||
);
|
||||
}
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
@@ -2295,6 +2295,7 @@ fn write_pdf(
|
||||
let mut kids = Vec::new();
|
||||
let mut navigation = PdfNavigation::default();
|
||||
let mut annotation_actions = Vec::new();
|
||||
let mut xdv_annotations = Vec::new();
|
||||
let pdf_version = pages
|
||||
.first()
|
||||
.and_then(|page| page.pdf.as_ref())
|
||||
@@ -2453,8 +2454,10 @@ fn write_pdf(
|
||||
})
|
||||
})
|
||||
.collect();
|
||||
let xdv_annotation_ids = next_annotation..next_annotation + list.pdf_links.xdv_annotations.len();
|
||||
let annotation_refs = (annotation_base..native_annotation_base)
|
||||
.chain(native_annotation_ids.iter().copied())
|
||||
.chain(xdv_annotation_ids.clone())
|
||||
.map(|id| format!("{id} 0 R"))
|
||||
.collect::<Vec<_>>()
|
||||
.join(" ");
|
||||
@@ -2590,6 +2593,11 @@ fn write_pdf(
|
||||
objects[id - 1] = body;
|
||||
}
|
||||
}
|
||||
for (id, annotation) in xdv_annotation_ids.zip(&list.pdf_links.xdv_annotations) {
|
||||
debug_assert_eq!(id, objects.len() + 1);
|
||||
xdv_annotations.push((id, annotation));
|
||||
objects.push(Vec::new());
|
||||
}
|
||||
for destination in &list.pdf_links.destinations {
|
||||
use crate::pdf_device::links::DestinationView;
|
||||
let x = physical(destination.point[0]);
|
||||
@@ -2755,15 +2763,26 @@ fn write_pdf(
|
||||
let xdv = unicode.and_then(|options| options.xdv_navigation);
|
||||
let keep_xdv_destinations = unicode.is_some_and(|options| options.xdv_keep_destinations);
|
||||
let mut xdv_names = BTreeMap::new();
|
||||
if !keep_xdv_destinations {
|
||||
let mut references: Vec<_> = xdv.into_iter().flat_map(|view| view.named_references())
|
||||
.chain(xdv_annotations.iter().filter_map(|(_, annotation)| annotation.named_reference()))
|
||||
.collect();
|
||||
references.sort_unstable_by_key(|(order, _)| *order);
|
||||
for (_, name) in references {
|
||||
let index = xdv_names.len();
|
||||
xdv_names.entry(name.to_vec()).or_insert_with(|| format!("{index:x}").into_bytes());
|
||||
}
|
||||
}
|
||||
for (id, annotation) in xdv_annotations {
|
||||
objects[id - 1] = annotation.pdf(&navigation.pages, &xdv_names)?;
|
||||
}
|
||||
if let Some(xdv) = xdv {
|
||||
let open_depth = unicode.unwrap().xdv_outline_open_depth;
|
||||
let (outlines, names) = xdv.write_outlines(
|
||||
&navigation.pages, &mut objects, keep_xdv_destinations, open_depth,
|
||||
)?;
|
||||
if let Some(outlines) = outlines {
|
||||
if let Some(outlines) = xdv.write_outlines(
|
||||
&navigation.pages, &mut objects, &xdv_names, open_depth,
|
||||
)? {
|
||||
catalog.push_str(&format!(" /Outlines {outlines} 0 R"));
|
||||
}
|
||||
xdv_names = names;
|
||||
}
|
||||
if !navigation.threads.is_empty() {
|
||||
let mut ids: Vec<_> = navigation.threads.into_values().collect();
|
||||
|
||||
@@ -97,6 +97,7 @@ pub fn print_sp(value: i64, digits: u8) -> String {
|
||||
}
|
||||
}
|
||||
mod color;
|
||||
pub(crate) mod xdv_annotation;
|
||||
pub(crate) mod xdv_color;
|
||||
pub(crate) mod xdv_destination;
|
||||
pub(crate) mod xdv_document;
|
||||
|
||||
@@ -103,10 +103,15 @@ pub struct PageLinks {
|
||||
pub destinations: Vec<PageDestination>,
|
||||
#[serde(default, skip_serializing_if = "Vec::is_empty")]
|
||||
pub(crate) xdv_destinations: Vec<super::xdv_destination::Destination>,
|
||||
#[serde(default, skip_serializing_if = "Vec::is_empty")]
|
||||
pub(crate) xdv_annotations: Vec<super::xdv_annotation::Annotation>,
|
||||
}
|
||||
|
||||
impl PageLinks {
|
||||
pub(crate) fn is_empty(&self) -> bool {
|
||||
self.annotations.is_empty() && self.destinations.is_empty() && self.xdv_destinations.is_empty()
|
||||
self.annotations.is_empty()
|
||||
&& self.destinations.is_empty()
|
||||
&& self.xdv_destinations.is_empty()
|
||||
&& self.xdv_annotations.is_empty()
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,339 @@
|
||||
//! Link and explicit annotation geometry produced by the XDV page device.
|
||||
use std::{collections::BTreeMap, sync::Arc};
|
||||
|
||||
use lopdf::Object;
|
||||
|
||||
use super::xdv_navigation::read_fields;
|
||||
use super::xdv_object::{
|
||||
Dictionary, Position, atom, encode_device_value, output_with_destination, target_name, trim_pdf,
|
||||
};
|
||||
use super::{Affine, xdv_image};
|
||||
|
||||
pub(crate) type Order = (usize, usize, u8);
|
||||
|
||||
#[derive(Clone, Copy)]
|
||||
pub(crate) enum Command {
|
||||
Begin,
|
||||
End,
|
||||
Expand,
|
||||
Explicit,
|
||||
Link(bool),
|
||||
}
|
||||
|
||||
impl Command {
|
||||
pub(crate) fn recognize(input: &[u8]) -> Option<(Self, &[u8])> {
|
||||
let body = trim_pdf(input).strip_prefix(b"pdf:").map(trim_pdf)?;
|
||||
let (word, rest) = atom(body);
|
||||
let command = match word {
|
||||
b"bannot" | b"beginann" | b"bann" => Self::Begin,
|
||||
b"eannot" | b"endann" | b"eann" => Self::End,
|
||||
b"xannot" | b"extendann" | b"xann" => Self::Expand,
|
||||
b"annotation" | b"annotate" | b"annot" | b"ann" => Self::Explicit,
|
||||
b"link" => Self::Link(true),
|
||||
b"nolink" => Self::Link(false),
|
||||
_ => return None,
|
||||
};
|
||||
Some((command, trim_pdf(rest)))
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
|
||||
pub(crate) struct Annotation {
|
||||
pub(crate) order: Order,
|
||||
fields: Arc<Dictionary>,
|
||||
/// Physical PDF coordinates in thousandths of a big point.
|
||||
rect: [i64; 4],
|
||||
}
|
||||
|
||||
impl Annotation {
|
||||
pub(crate) fn named_reference(&self) -> Option<(Order, &[u8])> {
|
||||
target_name(&self.fields).map(|name| (self.order, name))
|
||||
}
|
||||
|
||||
pub(crate) fn pdf(
|
||||
&self,
|
||||
pages: &[usize],
|
||||
names: &BTreeMap<Vec<u8>, Vec<u8>>,
|
||||
) -> Result<Vec<u8>, String> {
|
||||
let mut dictionary = output_with_destination(&self.fields, pages, names)?;
|
||||
dictionary.set(
|
||||
"Rect",
|
||||
Object::Array(
|
||||
self.rect
|
||||
.map(|value| Object::Real(value as f64 / 1000.0))
|
||||
.to_vec(),
|
||||
),
|
||||
);
|
||||
encode_device_value(Object::Dictionary(dictionary))
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Clone)]
|
||||
struct Active {
|
||||
fields: Arc<Dictionary>,
|
||||
depth: usize,
|
||||
}
|
||||
|
||||
#[derive(Clone)]
|
||||
pub(crate) struct AnnotationState {
|
||||
active: Option<Active>,
|
||||
bounds: Option<Bounds>,
|
||||
enabled: bool,
|
||||
}
|
||||
|
||||
impl Default for AnnotationState {
|
||||
fn default() -> Self {
|
||||
Self {
|
||||
active: None,
|
||||
bounds: None,
|
||||
enabled: true,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl AnnotationState {
|
||||
pub(crate) fn is_active(&self) -> bool {
|
||||
self.active.is_some()
|
||||
}
|
||||
|
||||
pub(crate) fn page(&mut self) -> Page<'_> {
|
||||
Page {
|
||||
state: self,
|
||||
depth: 0,
|
||||
annotations: Vec::new(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) struct Page<'a> {
|
||||
state: &'a mut AnnotationState,
|
||||
depth: usize,
|
||||
annotations: Vec<Annotation>,
|
||||
}
|
||||
|
||||
impl Page<'_> {
|
||||
pub(crate) fn tracking(&self) -> bool {
|
||||
self.state.enabled
|
||||
&& self
|
||||
.state
|
||||
.active
|
||||
.as_ref()
|
||||
.is_some_and(|active| self.depth >= active.depth)
|
||||
}
|
||||
|
||||
pub(crate) fn enter(&mut self, depth: usize) {
|
||||
self.depth = depth;
|
||||
}
|
||||
|
||||
pub(crate) fn leave(&mut self, depth: usize, order: Order) {
|
||||
if depth != 0
|
||||
&& self.state.enabled
|
||||
&& self
|
||||
.state
|
||||
.active
|
||||
.as_ref()
|
||||
.is_some_and(|active| active.depth == depth)
|
||||
{
|
||||
self.flush(order);
|
||||
}
|
||||
self.depth = depth.saturating_sub(1);
|
||||
}
|
||||
|
||||
pub(crate) fn apply(
|
||||
&mut self,
|
||||
command: Command,
|
||||
operands: &[u8],
|
||||
point: [f64; 2],
|
||||
transform: Affine,
|
||||
position: Position,
|
||||
order: Order,
|
||||
) -> Result<Vec<String>, String> {
|
||||
match command {
|
||||
Command::Begin => {
|
||||
if self.state.active.is_some() {
|
||||
return Ok(vec![
|
||||
"xdvipdfmx: warning: Can't begin an annotation when one is pending.\n"
|
||||
.into(),
|
||||
]);
|
||||
}
|
||||
let (fields, warnings) = read_fields(operands, position)?;
|
||||
self.state.active = Some(Active {
|
||||
fields: Arc::new(fields),
|
||||
depth: self.depth,
|
||||
});
|
||||
Ok(warnings)
|
||||
}
|
||||
Command::End => {
|
||||
if self.state.active.is_none() {
|
||||
return Ok(vec![
|
||||
"xdvipdfmx: warning: Tried to end an annotation without starting one!\n"
|
||||
.into(),
|
||||
]);
|
||||
}
|
||||
self.flush(order);
|
||||
self.state.active = None;
|
||||
Ok(Vec::new())
|
||||
}
|
||||
Command::Expand if !self.tracking() => Ok(Vec::new()),
|
||||
Command::Expand | Command::Explicit => {
|
||||
let dictionary = operands
|
||||
.windows(2)
|
||||
.position(|window| window == b"<<")
|
||||
.unwrap_or(operands.len());
|
||||
let bounds = Dimensions::read(&operands[..dictionary], position.magnification)?
|
||||
.bounds(point, transform, position);
|
||||
if matches!(command, Command::Expand) {
|
||||
self.expand(bounds);
|
||||
return Ok(Vec::new());
|
||||
}
|
||||
let (fields, warnings) = read_fields(&operands[dictionary..], position)?;
|
||||
self.annotations.push(Annotation {
|
||||
order,
|
||||
fields: Arc::new(fields),
|
||||
rect: bounds.quantized(),
|
||||
});
|
||||
Ok(warnings)
|
||||
}
|
||||
Command::Link(enabled) => {
|
||||
self.state.enabled = enabled;
|
||||
Ok(Vec::new())
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn expand(&mut self, bounds: Bounds) {
|
||||
self.state.bounds = Some(self.state.bounds.map_or(bounds, |old| old.union(bounds)));
|
||||
}
|
||||
|
||||
fn flush(&mut self, order: Order) {
|
||||
if let Some(bounds) = self.state.bounds.take()
|
||||
&& let Some(active) = &self.state.active
|
||||
{
|
||||
self.annotations.push(Annotation {
|
||||
order,
|
||||
fields: active.fields.clone(),
|
||||
rect: bounds.quantized(),
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn finish(self) -> Vec<Annotation> {
|
||||
self.annotations
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy)]
|
||||
pub(crate) struct Bounds([f64; 4]);
|
||||
|
||||
impl Bounds {
|
||||
pub(crate) fn from_logical(
|
||||
[left, top, right, bottom]: [f64; 4],
|
||||
transform: Affine,
|
||||
height: i64,
|
||||
magnification: i32,
|
||||
) -> Self {
|
||||
Self::from_corners(
|
||||
[[left, top], [right, top], [left, bottom], [right, bottom]],
|
||||
transform,
|
||||
height,
|
||||
magnification,
|
||||
)
|
||||
}
|
||||
|
||||
pub(crate) fn from_corners(
|
||||
corners: [[f64; 2]; 4],
|
||||
transform: Affine,
|
||||
height: i64,
|
||||
magnification: i32,
|
||||
) -> Self {
|
||||
let scale = bp_per_sp(magnification);
|
||||
let mut bounds = [
|
||||
f64::INFINITY,
|
||||
f64::INFINITY,
|
||||
f64::NEG_INFINITY,
|
||||
f64::NEG_INFINITY,
|
||||
];
|
||||
for [x, y] in corners {
|
||||
let [x, y] = transform.point(x, y);
|
||||
let [x, y] = [x * scale, (height as f64 - y) * scale];
|
||||
bounds = [
|
||||
bounds[0].min(x),
|
||||
bounds[1].min(y),
|
||||
bounds[2].max(x),
|
||||
bounds[3].max(y),
|
||||
];
|
||||
}
|
||||
Self(bounds)
|
||||
}
|
||||
|
||||
fn union(self, other: Self) -> Self {
|
||||
let [a, b, c, d] = self.0;
|
||||
let [x, y, u, v] = other.0;
|
||||
Self([a.min(x), b.min(y), c.max(u), d.max(v)])
|
||||
}
|
||||
|
||||
fn quantized(self) -> [i64; 4] {
|
||||
self.0.map(|value| (value * 1000.0).round() as i64)
|
||||
}
|
||||
}
|
||||
|
||||
fn bp_per_sp(magnification: i32) -> f64 {
|
||||
f64::from(magnification) / 1000.0 * (800.0 / 803.0) / 65536.0
|
||||
}
|
||||
|
||||
#[derive(Default)]
|
||||
struct Dimensions {
|
||||
sizes: [Option<f64>; 3],
|
||||
bbox: Option<[f64; 4]>,
|
||||
}
|
||||
|
||||
impl Dimensions {
|
||||
fn read(operands: &[u8], magnification: i32) -> Result<Self, String> {
|
||||
let text =
|
||||
std::str::from_utf8(operands).map_err(|_| "invalid XDV annotation dimensions")?;
|
||||
let mut words = text.split_ascii_whitespace().peekable();
|
||||
let mut dimensions = Self::default();
|
||||
while let Some(command) = words.next() {
|
||||
match command {
|
||||
"width" => {
|
||||
dimensions.sizes[0] = Some(xdv_image::length(&mut words, magnification)?)
|
||||
}
|
||||
"height" => {
|
||||
dimensions.sizes[1] = Some(xdv_image::length(&mut words, magnification)?)
|
||||
}
|
||||
"depth" => {
|
||||
dimensions.sizes[2] = Some(xdv_image::length(&mut words, magnification)?)
|
||||
}
|
||||
"bbox" => {
|
||||
let mut bounds = [0.0; 4];
|
||||
for value in &mut bounds {
|
||||
*value = xdv_image::number(words.next())?;
|
||||
}
|
||||
dimensions.bbox = Some(bounds);
|
||||
}
|
||||
_ => return Err(format!("unsupported XDV annotation dimension {command}")),
|
||||
}
|
||||
}
|
||||
if dimensions.bbox.is_some() && dimensions.sizes.iter().any(Option::is_some) {
|
||||
return Err("XDV annotation bbox conflicts with width, height or depth".into());
|
||||
}
|
||||
Ok(dimensions)
|
||||
}
|
||||
|
||||
fn bounds(self, [x, y]: [f64; 2], transform: Affine, position: Position) -> Bounds {
|
||||
let [left, bottom, right, top] = if let Some(bbox) = self.bbox {
|
||||
bbox.map(|value| value / bp_per_sp(position.magnification))
|
||||
} else {
|
||||
let [width, height, depth] = self
|
||||
.sizes
|
||||
.map(|value| value.unwrap_or_default() / bp_per_sp(1000));
|
||||
[0.0, -depth, width, height]
|
||||
};
|
||||
Bounds::from_logical(
|
||||
[x + left, y - top, x + right, y - bottom],
|
||||
transform,
|
||||
position.height,
|
||||
position.magnification,
|
||||
)
|
||||
}
|
||||
}
|
||||
@@ -191,23 +191,25 @@ impl ImageSpecial {
|
||||
-left * width / natural_w,
|
||||
-bottom * height / natural_h - depth,
|
||||
]);
|
||||
let clip = (self.clip && self.bbox.is_some()).then_some([
|
||||
let annotation_box = self.bbox.is_some().then_some([
|
||||
left / natural_w,
|
||||
bottom / natural_h,
|
||||
box_w / natural_w,
|
||||
box_h / natural_h,
|
||||
]);
|
||||
PdfImageUse::new_xdv_raster_special(id, image, self.transform.concatenate(sizing), clip)
|
||||
PdfImageUse::new_xdv_raster_special(
|
||||
id, image, self.transform.concatenate(sizing), annotation_box, self.clip,
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
fn number(word: Option<&str>) -> Result<f64, &'static str> {
|
||||
pub(super) fn number(word: Option<&str>) -> Result<f64, &'static str> {
|
||||
word.and_then(|word| word.parse::<f64>().ok())
|
||||
.filter(|value| value.is_finite())
|
||||
.ok_or("invalid XDV image number")
|
||||
}
|
||||
|
||||
fn length(
|
||||
pub(super) fn length(
|
||||
words: &mut Peekable<SplitAsciiWhitespace<'_>>,
|
||||
magnification: i32,
|
||||
) -> Result<f64, &'static str> {
|
||||
|
||||
@@ -4,9 +4,11 @@ use std::collections::BTreeMap;
|
||||
use lopdf::Object;
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
use super::page_resources::{encode_value, parse_value};
|
||||
use super::page_resources::parse_value;
|
||||
use super::xdv_annotation::Order;
|
||||
use super::xdv_object::{
|
||||
Dictionary, Position, Value, atom, dictionary, output_dictionary, trim_pdf,
|
||||
Dictionary, Position, Value, atom, dictionary, encode_device_value, output_dictionary,
|
||||
output_with_destination, target_name, trim_pdf,
|
||||
};
|
||||
|
||||
#[derive(Clone, Debug, Default, PartialEq, Eq, Hash, Serialize, Deserialize)]
|
||||
@@ -19,6 +21,7 @@ pub(crate) struct Navigation {
|
||||
|
||||
#[derive(Clone, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)]
|
||||
struct Outline {
|
||||
order: Order,
|
||||
depth: usize,
|
||||
force_open: bool,
|
||||
fields: Dictionary,
|
||||
@@ -48,6 +51,7 @@ impl Navigation {
|
||||
&mut self,
|
||||
bytes: &[u8],
|
||||
position: Position,
|
||||
order: Order,
|
||||
limit: usize,
|
||||
) -> Result<Vec<String>, String> {
|
||||
let (force_open, rest) = match trim_pdf(bytes) {
|
||||
@@ -72,6 +76,7 @@ impl Navigation {
|
||||
self.add_payload(bytes.len(), limit)?;
|
||||
self.lowest_level = Some(lowest);
|
||||
self.outlines.push(Outline {
|
||||
order,
|
||||
depth: depth as usize,
|
||||
force_open,
|
||||
fields,
|
||||
@@ -108,19 +113,24 @@ impl Navigation {
|
||||
_ => catalog.set(key.clone(), value.clone()),
|
||||
}
|
||||
}
|
||||
encode_value(Object::Dictionary(catalog))
|
||||
encode_device_value(Object::Dictionary(catalog))
|
||||
}
|
||||
|
||||
pub(crate) fn named_references(&self) -> impl Iterator<Item = (Order, &[u8])> {
|
||||
self.outlines
|
||||
.iter()
|
||||
.filter_map(|outline| target_name(&outline.fields).map(|name| (outline.order, name)))
|
||||
}
|
||||
|
||||
pub(crate) fn write_outlines(
|
||||
&self,
|
||||
pages: &[usize],
|
||||
objects: &mut Vec<Vec<u8>>,
|
||||
keep_destinations: bool,
|
||||
names: &BTreeMap<Vec<u8>, Vec<u8>>,
|
||||
open_depth: usize,
|
||||
) -> Result<(Option<usize>, BTreeMap<Vec<u8>, Vec<u8>>), String> {
|
||||
let mut names = BTreeMap::new();
|
||||
) -> Result<Option<usize>, String> {
|
||||
if self.outlines.is_empty() {
|
||||
return Ok((None, names));
|
||||
return Ok(None);
|
||||
}
|
||||
let root = objects.len() + 1;
|
||||
let mut entries: Vec<_> = (0..=self.outlines.len())
|
||||
@@ -168,13 +178,10 @@ impl Navigation {
|
||||
let mut fields = lopdf::Dictionary::new();
|
||||
links(&mut fields, &entries[0]);
|
||||
fields.set("Count", entries[0].count);
|
||||
objects.push(encode_value(Object::Dictionary(fields))?);
|
||||
objects.push(encode_device_value(Object::Dictionary(fields))?);
|
||||
for (offset, outline) in self.outlines.iter().enumerate() {
|
||||
let entry = &entries[offset + 1];
|
||||
let mut fields = output_dictionary(&outline.fields, pages)?;
|
||||
if !keep_destinations {
|
||||
remap_outline_destination(&mut fields, &mut names);
|
||||
}
|
||||
let mut fields = output_with_destination(&outline.fields, pages, names)?;
|
||||
fields.set("Parent", object(entry.parent));
|
||||
for field in [b"Prev".as_slice(), b"Next", b"First", b"Last", b"Count"] {
|
||||
fields.remove(field);
|
||||
@@ -188,9 +195,9 @@ impl Navigation {
|
||||
};
|
||||
fields.set("Count", sign * entry.count);
|
||||
}
|
||||
objects.push(encode_value(Object::Dictionary(fields))?);
|
||||
objects.push(encode_device_value(Object::Dictionary(fields))?);
|
||||
}
|
||||
Ok((Some(root), names))
|
||||
Ok(Some(root))
|
||||
}
|
||||
}
|
||||
|
||||
@@ -204,7 +211,10 @@ struct OutlineLinks {
|
||||
count: i64,
|
||||
}
|
||||
|
||||
fn read_fields(bytes: &[u8], position: Position) -> Result<(Dictionary, Vec<String>), String> {
|
||||
pub(super) fn read_fields(
|
||||
bytes: &[u8],
|
||||
position: Position,
|
||||
) -> Result<(Dictionary, Vec<String>), String> {
|
||||
let mut fields = dictionary(bytes, position)?;
|
||||
let mut warnings = Vec::new();
|
||||
for (key, value) in &mut fields {
|
||||
@@ -212,26 +222,3 @@ fn read_fields(bytes: &[u8], position: Position) -> Result<(Dictionary, Vec<Stri
|
||||
}
|
||||
Ok((fields, warnings))
|
||||
}
|
||||
|
||||
fn remap_outline_destination(
|
||||
fields: &mut lopdf::Dictionary,
|
||||
names: &mut BTreeMap<Vec<u8>, Vec<u8>>,
|
||||
) {
|
||||
let named = if fields.has(b"Dest") && !fields.has(b"A") {
|
||||
fields.get_mut(b"Dest").ok()
|
||||
} else if !fields.has(b"Dest")
|
||||
&& let Ok(Object::Dictionary(action)) = fields.get_mut(b"A")
|
||||
&& action.get(b"S").ok().and_then(|kind| kind.as_name().ok()) == Some(b"GoTo".as_slice())
|
||||
{
|
||||
action.get_mut(b"D").ok()
|
||||
} else {
|
||||
None
|
||||
};
|
||||
if let Some(Object::String(name, _)) = named {
|
||||
let index = names.len();
|
||||
*name = names
|
||||
.entry(name.clone())
|
||||
.or_insert_with(|| format!("{index:x}").into_bytes())
|
||||
.clone();
|
||||
}
|
||||
}
|
||||
@@ -1,9 +1,9 @@
|
||||
//! PDF objects in XDV specials, including typed references to shipped pages.
|
||||
use lopdf::{Object, StringFormat};
|
||||
use serde::{Deserialize, Serialize};
|
||||
use std::collections::BTreeMap;
|
||||
use std::{collections::BTreeMap, io::Write as _};
|
||||
|
||||
use super::page_resources::{parse_name, parse_value};
|
||||
use super::page_resources::{encode_value, parse_name, parse_value};
|
||||
use super::{magnify, print_sp};
|
||||
|
||||
pub(super) fn trim_pdf(mut bytes: &[u8]) -> &[u8] {
|
||||
@@ -268,3 +268,76 @@ impl Value {
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Return a local string destination, shared by bookmark and link export.
|
||||
pub(super) fn target_name(fields: &Dictionary) -> Option<&[u8]> {
|
||||
if fields
|
||||
.get(b"Subtype".as_slice())
|
||||
.is_some_and(|subtype| !matches!(subtype, Value::Name(name) if name == b"Link"))
|
||||
{
|
||||
return None;
|
||||
}
|
||||
let target = match (fields.get(b"Dest".as_slice()), fields.get(b"A".as_slice())) {
|
||||
(Some(target), None) => Some(target),
|
||||
(None, Some(Value::Dictionary(action))) if matches!(action.get(b"S".as_slice()), Some(Value::Name(name)) if name == b"GoTo") => {
|
||||
action.get(b"D".as_slice())
|
||||
}
|
||||
_ => None,
|
||||
};
|
||||
if let Some(Value::String(name)) = target {
|
||||
Some(name)
|
||||
} else {
|
||||
None
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) fn output_with_destination(
|
||||
fields: &Dictionary,
|
||||
pages: &[usize],
|
||||
names: &BTreeMap<Vec<u8>, Vec<u8>>,
|
||||
) -> Result<lopdf::Dictionary, String> {
|
||||
let mut dictionary = output_dictionary(fields, pages)?;
|
||||
if let Some(compact) = target_name(fields).and_then(|name| names.get(name)) {
|
||||
let compact = Object::String(compact.clone(), StringFormat::Hexadecimal);
|
||||
if dictionary.has(b"Dest") {
|
||||
dictionary.set("Dest", compact);
|
||||
} else if let Ok(Object::Dictionary(action)) = dictionary.get_mut(b"A") {
|
||||
action.set("D", compact);
|
||||
}
|
||||
}
|
||||
Ok(dictionary)
|
||||
}
|
||||
|
||||
/// The shared resource encoder limits real numbers to two fractional digits.
|
||||
/// XDV geometry and caller-provided PDF objects require their full precision.
|
||||
pub(super) fn encode_device_value(object: Object) -> Result<Vec<u8>, String> {
|
||||
fn append(bytes: &mut Vec<u8>, object: Object) -> Result<(), String> {
|
||||
match object {
|
||||
Object::Real(value) if value.is_finite() => write!(bytes, "{value}").unwrap(),
|
||||
Object::Real(_) => return Err("non-finite number in XDV PDF object".into()),
|
||||
Object::Array(values) => {
|
||||
bytes.push(b'[');
|
||||
for value in values {
|
||||
append(bytes, value)?;
|
||||
bytes.push(b' ');
|
||||
}
|
||||
bytes.push(b']');
|
||||
}
|
||||
Object::Dictionary(entries) => {
|
||||
bytes.extend_from_slice(b"<<");
|
||||
for (name, value) in &entries {
|
||||
bytes.extend(encode_value(Object::Name(name.clone()))?);
|
||||
bytes.push(b' ');
|
||||
append(bytes, value.clone())?;
|
||||
bytes.push(b' ');
|
||||
}
|
||||
bytes.extend_from_slice(b">>");
|
||||
}
|
||||
_ => bytes.extend(encode_value(object)?),
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
let mut bytes = Vec::new();
|
||||
append(&mut bytes, object)?;
|
||||
Ok(bytes)
|
||||
}
|
||||
@@ -62,6 +62,8 @@ pub(crate) struct XdvPdfPlacement {
|
||||
matrix: [u64; 6],
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
clip: Option<[u64; 4]>,
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
annotation_box: Option<[u64; 4]>,
|
||||
#[serde(default)]
|
||||
pub(crate) layout_offset: [i64; 2],
|
||||
}
|
||||
@@ -74,6 +76,11 @@ impl XdvPdfPlacement {
|
||||
pub(crate) fn clip(&self) -> Option<[f64; 4]> {
|
||||
self.clip.map(|rect| rect.map(f64::from_bits))
|
||||
}
|
||||
|
||||
pub(crate) fn annotation_box(&self) -> [f64; 4] {
|
||||
self.annotation_box.or(self.clip)
|
||||
.map_or([0.0, 0.0, 1.0, 1.0], |rect| rect.map(f64::from_bits))
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, PartialEq, Eq, Hash, serde::Serialize, serde::Deserialize)]
|
||||
@@ -175,6 +182,7 @@ impl PdfImageUse {
|
||||
page_request,
|
||||
matrix: matrix.map(f64::to_bits),
|
||||
clip: None,
|
||||
annotation_box: None,
|
||||
layout_offset: [0, 0],
|
||||
}),
|
||||
})
|
||||
@@ -184,13 +192,15 @@ impl PdfImageUse {
|
||||
id: usize,
|
||||
image: Arc<PdfImage>,
|
||||
matrix: Affine,
|
||||
clip: Option<[f64; 4]>,
|
||||
annotation_box: Option<[f64; 4]>,
|
||||
clip: bool,
|
||||
) -> Result<Self, String> {
|
||||
if matrix.0.iter().any(|value| !value.is_finite())
|
||||
|| clip.is_some_and(|rect| rect.iter().any(|value| !value.is_finite()))
|
||||
|| annotation_box.is_some_and(|rect| rect.iter().any(|value| !value.is_finite()))
|
||||
{
|
||||
return Err("XDV raster image transform exceeds capacity".into());
|
||||
}
|
||||
let clip = if clip { annotation_box } else { None };
|
||||
let [x, y, w, h] = clip.unwrap_or([0.0, 0.0, 1.0, 1.0]);
|
||||
let [x0, y0, x1, y1] = [x, y, x + w, y + h].map(|value| value.clamp(0.0, 1.0));
|
||||
let [left, bottom] = matrix.point(x0, y0);
|
||||
@@ -217,6 +227,7 @@ impl PdfImageUse {
|
||||
page_request: 0,
|
||||
matrix: matrix.map(f64::to_bits),
|
||||
clip: clip.map(|rect| rect.map(f64::to_bits)),
|
||||
annotation_box: annotation_box.map(|rect| rect.map(f64::to_bits)),
|
||||
layout_offset: [left as i64, bottom as i64],
|
||||
}),
|
||||
})
|
||||
|
||||
@@ -660,3 +660,62 @@ fn xdv_catalog_and_outlines_resolve_live_pages_and_retain_referenced_names() {
|
||||
assert_eq!(remapped.as_str().unwrap(), names[0].as_str().unwrap());
|
||||
assert_eq!(names[1].as_array().unwrap()[0].as_reference().unwrap(), page_ids[&2]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn xdv_root_annotation_keeps_its_extent_and_destination_across_shipouts() {
|
||||
use lopdf::{Document, Object};
|
||||
use texrra_tex_core::pdf::shipout_lists_to_native_pdf_document;
|
||||
|
||||
let state = State::initex().with_etex().with_input_profile(InputProfile::XeTeX);
|
||||
let result = Executor::new(state, Limits::default())
|
||||
.with_native_pages()
|
||||
.run(
|
||||
source(
|
||||
r"\catcode123=1 \catcode125=2
|
||||
\shipout\hbox{\special{pdf:bann<</Subtype/Link/Dest(topic)>>}
|
||||
\special{pdf:xann width 10pt height 7pt depth 1pt}
|
||||
\vrule width30pt height12pt depth0pt}
|
||||
\shipout\hbox{\kern20pt
|
||||
\special{pdf:extendann width 11pt height 8pt depth 2pt}
|
||||
\special{pdf:eann}
|
||||
\special{pdf:outline 1<</Title (Chapter)/Dest(chapter)>>}
|
||||
\special{pdf:dest (topic) [@thispage/Fit]}
|
||||
\special{pdf:dest (chapter) [@prevpage/Fit]}
|
||||
\vrule width10pt height8pt depth0pt}
|
||||
\end",
|
||||
),
|
||||
&mut TestDevice,
|
||||
)
|
||||
.unwrap();
|
||||
let pages = result.shipout_display_lists().unwrap();
|
||||
let output =
|
||||
shipout_lists_to_native_pdf_document(&pages, result.state.pdf_final_options()).unwrap();
|
||||
let pdf = Document::load_mem(&output.bytes).unwrap();
|
||||
let page_ids = pdf.get_pages();
|
||||
let first = pdf.get_object(page_ids[&1]).unwrap().as_dict().unwrap();
|
||||
assert!(!first.has(b"Annots"));
|
||||
let second = pdf.get_object(page_ids[&2]).unwrap().as_dict().unwrap();
|
||||
let annotations = second.get(b"Annots").unwrap().as_array().unwrap();
|
||||
assert_eq!(annotations.len(), 1);
|
||||
let annotation = pdf
|
||||
.get_object(annotations[0].as_reference().unwrap())
|
||||
.unwrap()
|
||||
.as_dict()
|
||||
.unwrap();
|
||||
assert_eq!(annotation.get(b"Dest").unwrap().as_str().unwrap(), b"0");
|
||||
let rectangle = annotation.get(b"Rect").unwrap().as_array().unwrap();
|
||||
let coordinate = |index| match &rectangle[index] {
|
||||
Object::Integer(value) => *value as f64,
|
||||
Object::Real(value) => *value,
|
||||
_ => panic!("expected physical annotation coordinate"),
|
||||
};
|
||||
assert_eq!(coordinate(0), 72.0);
|
||||
assert_eq!(coordinate(2), 102.884);
|
||||
let names = pdf.catalog().unwrap().get(b"Names").unwrap().as_dict().unwrap();
|
||||
let names = pdf.get_object(names.get(b"Dests").unwrap().as_reference().unwrap())
|
||||
.unwrap().as_dict().unwrap().get(b"Names").unwrap().as_array().unwrap();
|
||||
assert_eq!(names[0].as_str().unwrap(), b"0");
|
||||
assert_eq!(names[1].as_array().unwrap()[0].as_reference().unwrap(), page_ids[&2]);
|
||||
assert_eq!(names[2].as_str().unwrap(), b"1");
|
||||
assert_eq!(names[3].as_array().unwrap()[0].as_reference().unwrap(), page_ids[&1]);
|
||||
}
|
||||
@@ -2175,6 +2175,38 @@ PDF,恢复实际 PFB 并反转斜切时复用 1277 步,只替换第二页。
|
||||
全量编译一致。incremental-receipt.json 的 SHA-256 为
|
||||
bbc0991b0316e6d76aa58649ec873525f5544ab530d93fe491fc6e16bd00a27d。
|
||||
|
||||
### XDV 链接注释与实际矩形
|
||||
|
||||
原生发页以实际字形度量和 DVI 列表层级生成 `pdf:bann`、
|
||||
`pdf:eann` 的链接矩形。支持 `pdf:ann` 直接尺寸、`pdf:xann`
|
||||
范围扩展、暂停及恢复。嵌套层级结束时输出当前分段,最外层链接
|
||||
跨页时在实际结束的位置输出累积范围。图形变换作用于实际矩形。
|
||||
书签与注释按发页顺序共用命名目标,原义保留选项继续生效。
|
||||
PDF 数值写出保留实际坐标精度。自定义注释对象名与
|
||||
XeTeX 原语直接插入的图像尚待验证。
|
||||
[上游 DVI 层级与度量](https://github.com/TeX-Live/texlive-source/blob/279984fab6eaed8d17e02882f2668ab5caac0f27/texk/dvipdfm-x/dvi.c)
|
||||
[上游注释矩形](https://github.com/TeX-Live/texlive-source/blob/279984fab6eaed8d17e02882f2668ab5caac0f27/texk/dvipdfm-x/pdfdoc.c)
|
||||
|
||||
六份同源用例的注释矩形、目录和命名目标逐项匹配。覆盖文字、
|
||||
跨页、显式尺寸、OpenType 变换及两种图像裁切。图片矩形先换算
|
||||
原始局部范围为 DVI 单位,再应用图形变换,裁切开关独立作用于
|
||||
实际绘制。12 项 XeTeX 定向测试通过。十二页 144 DPI 彩色光栅中
|
||||
十一页逐像素一致,CMR10 样例的一页有 122 个不同像素。
|
||||
三页两文件项目跨文件编辑时保留前一页已累积的范围,
|
||||
修改链接目标只更新 PDF,随后改规则宽度只刷新第二页。分别
|
||||
复用 154 步、重放 2 次宿主调用,PDF、SVG 和来源映射
|
||||
均与独立全量一致。
|
||||
|
||||
使用原 schema71、十份冻结 ACL 文件、既有 BibTeX 产物及
|
||||
实际第二轮 aux/out 继续。第三、四轮各生成一页带引文链接的
|
||||
PDF,第四轮 aux/out 同时与第三轮和冻结参考逐字节一致。
|
||||
最终构建从稳定状态再编译,PDF、aux 和 out 与第四轮逐字节一致。
|
||||
成品仍有断行与字形排版差异。已用同一 Latin Modern 文件和
|
||||
同一源码复现 OpenType 显式断词例外没有进入原生断行的差异,
|
||||
入口为 `target/p3-xetex-native-hyphenation`。完整回执
|
||||
`target/p3-xdv-annotation/receipt.json`,SHA-256 为
|
||||
`0b572c3e4d5413ce81e52a8fd09aab992aa8b35f19bfa140dbdf301f925806b3`。
|
||||
|
||||
### XDV 文档目录、打开动作和书签
|
||||
|
||||
`pdf:docview` 按真实发页更新目录。同名字段由后一次发页覆盖,
|
||||
|
||||
@@ -749,6 +749,15 @@ XDV 文档目录和书签接入后,原样 ACL 以同一 schema71 和官方归
|
||||
回执 `target/p3-xdv-navigation/receipt.json`。
|
||||
[目录、打开动作和书签阶段记录](P2_M1_PROGRESS.md#xdv-文档目录打开动作和书签)
|
||||
|
||||
XDV 链接注释接入后,沿原样 ACL 的第二轮辅助文件和 BibTeX
|
||||
产物继续编译。同一 schema71 与十份原样文件的第三、四轮均
|
||||
生成一页 PDF,两条引文注释解析到原始命名目标。第四轮 aux
|
||||
和 out 与第三轮及冻结参考逐字节一致。最终构建重放同一稳定
|
||||
状态后,PDF、aux 和 out 与第四轮逐字节一致。参考和原生页面的
|
||||
抽取词序与部分断行仍有差异,排版比对继续开放。回执在
|
||||
`target/p3-xdv-annotation/receipt.json`。
|
||||
[链接注释阶段记录](P2_M1_PROGRESS.md#xdv-链接注释与实际矩形)
|
||||
|
||||
### 原样 Elsevier CAS 双栏与 NeurIPS 2025
|
||||
|
||||
以 `767c8ff`、既有真实 schema51 和参考格式复验官方 CAS 双栏。
|
||||
|
||||
Reference in new issue
Block a user