Order native PDF link continuations with shipout effects

This commit is contained in:
gloamxun committed 2026-11-27 22:34:01 +08:00
1 parent e95d1264da
commit af19a26c23
5 files changed
+274 -140

No files matched your search

@@ -39,6 +39,7 @@ pub(super) struct PdfSpaceProbe {
struct ShipoutFontUse {
before_output: usize,
before_paint: usize,
font: Arc<NativeFont>,
slot: u8,
}
@@ -48,11 +49,11 @@ fn shipout_font_uses(
) -> Result<Vec<ShipoutFontUse>, String> {
let mut uses = Vec::new();
let mut seen = BTreeSet::new();
b.visit_shipout_font_uses(|before_output, font, slot| {
b.visit_shipout_font_uses(|before_output, before_paint, font, slot| {
if (!programs.is_known_physical(font.id) || fonts.automatic_origin(font.id).is_some())
&& seen.insert((font.id, slot))
{
uses.push(ShipoutFontUse { before_output, font: font.clone(), slot });
uses.push(ShipoutFontUse { before_output, before_paint, font: font.clone(), slot });
}
})?;
Ok(uses)
@@ -455,9 +456,10 @@ impl Executor {
if let Some(effects) = &leader_effects {
outputs = effects.outputs.iter().collect();
}
let mut navigation_numbers = (Vec::new(), Vec::new());
let mut link_depth = self.pdf_link_stack.len();
let has_link_material = link_depth != 0 || outputs.iter().any(|node| node.is_pdf_link());
let output_count = outputs.len();
let has_link_material = !self.pdf_link_stack.is_empty() || outputs.iter().any(|node| node.is_pdf_link());
let mut pdf_link_shipout = (has_link_material && !for_form && device.pdf.is_some())
.then(|| self.begin_pdf_link_shipout(b, device));
let mut output_positions = if let Some(effects) = &leader_effects {
effects.output_positions.clone().into_iter()
} else if outputs.iter().any(|node| node.needs_shipout_position()) {
@@ -483,12 +485,17 @@ impl Executor {
let mut reopened_images = false;
let mut xdv_paper_specials = Vec::new();
let mut xdv_navigation = Vec::new();
for (index, output) in outputs.into_iter().enumerate() {
for (index, output) in outputs.iter().copied().enumerate() {
while font_uses.peek().is_some_and(|usage| usage.before_output == index) {
let usage = font_uses.next().unwrap();
if let Some(layout) = &mut pdf_link_shipout {
layout.advance(self, (index, usage.before_paint), &outputs, &shipout.pdf_graphics_steps, files)?;
}
self.current = current;
self.prepare_virtual_glyph(
shipout.virtual_glyphs.as_mut().unwrap(), font_uses.next().unwrap(), files,
)?;
self.prepare_virtual_glyph(shipout.virtual_glyphs.as_mut().unwrap(), usage, files)?;
}
if let Some(layout) = &mut pdf_link_shipout {
layout.advance(self, (index, usize::MAX), &outputs, &shipout.pdf_graphics_steps, files)?;
}
if self.pdf_loaded_space_font.is_none()
&& (uses_automatic_spaces || has_explicit_space)
@@ -665,32 +672,12 @@ impl Executor {
} else {
has_explicit_space = true;
}
} else if let OutputOperation::PdfLink(link) = &output.operation {
use crate::pdf_device::links::LinkNode;
} else if let OutputOperation::PdfLink(_) = &output.operation {
self.current = output.span;
self.tick()?;
if device.pdf.is_none() {
return self.fail("cannot ship a PDF link operation to DVI");
}
match link {
LinkNode::Start(_) if link_depth == 10 => {
return self.fail("PDF link stack capacity exceeded");
}
LinkNode::Start(layout) => {
link_depth += 1;
if !unicode_pages && !for_form {
navigation_numbers.0.push(self.register_pdf_link(layout.object_number)?);
}
}
LinkNode::End if link_depth == 0 => {
return self.fail("\\pdfendlink used without \\pdfstartlink");
}
LinkNode::End => link_depth -= 1,
LinkNode::Destination { destination, structure, .. } if !unicode_pages && !for_form => {
navigation_numbers.1.push(self.register_pdf_destination(destination, structure.is_some())?);
}
LinkNode::Running(_) | LinkNode::Destination { .. } => {}
}
} else {
if let OutputOperation::PdfImage { image, .. } = &output.operation {
reopened_images |= image.xdv.is_some() && image.image.is_metadata_only();
@@ -714,9 +701,20 @@ impl Executor {
));
}
self.current = current;
if has_link_material && for_form {
return self.fail("PDF page links and destinations require a page shipout");
}
for usage in font_uses {
if let Some(layout) = &mut pdf_link_shipout {
layout.advance(self, (output_count, usage.before_paint), &outputs, &shipout.pdf_graphics_steps, files)?;
}
self.prepare_virtual_glyph(shipout.virtual_glyphs.as_mut().unwrap(), usage, files)?;
}
if let Some(layout) = pdf_link_shipout {
let mut links = layout.finish(self, &outputs, &shipout.pdf_graphics_steps, files)?;
links.xdv_destinations = std::mem::take(&mut shipout.pdf_links.xdv_destinations);
shipout.pdf_links = links;
}
shipout.pdf_font_bindings = self.pdf_virtual_fonts.captured_font_bindings();
let has_space_settings = has_space_nodes || automatic_spaces_at_start;
let probed_page = (uses_automatic_spaces || has_explicit_space)
@@ -730,16 +728,6 @@ impl Executor {
shipout.pdf_text_spaces.as_mut().unwrap().dedicated_font =
self.pdf_loaded_space_font.clone();
}
if has_link_material {
if for_form {
return self.fail("PDF page links and destinations require a page shipout");
}
let mut links = self.ship_pdf_link_material(
b, device, &shipout.pdf_graphics_steps, navigation_numbers, files,
)?;
links.xdv_destinations = std::mem::take(&mut shipout.pdf_links.xdv_destinations);
shipout.pdf_links = links;
}
if let Some(objects) = &mut shipout.pdf_objects {
let limit = self.limits.tokens;
let compression = device.pdf.as_ref().unwrap().file.object_compression;
@@ -26,6 +26,25 @@ pub(super) struct ActiveLink {
segment: Option<Segment>,
}
enum LinkPaint {
Graphics,
RowStart(BoxLayout),
Node(BoxLayout),
}
pub(super) struct PdfLinkShipout {
events: std::iter::Peekable<std::vec::IntoIter<((usize, usize), i64, i64, LinkPaint)>>,
output_count: usize,
active: Vec<ActiveLink>,
transform: (Affine, bool),
saved: Vec<(Affine, bool)>,
graphics_index: usize,
output: PageLinks,
origin: [i64; 2],
margin: i64,
numbered: bool,
}
fn map_point(matrix: Affine, x: i64, y: i64) -> [i64; 2] {
matrix
.point(x as f64, y as f64)
@@ -234,10 +253,9 @@ impl Executor {
}
pub(super) fn register_pdf_destination(
&mut self, id: &DestinationId<Vec<Token>>, structure: bool,
&mut self, id: DestinationId<String>, structure: bool,
) -> Result<Option<u32>, Error> {
self.reads.insert(Dependency::PdfObjects);
let id = self.pdf_destination_id(id);
self.state.pdf_objects.get_or_insert_with(Default::default)
.destination_number(id, structure, true, self.limits.tokens)
.map_err(|message| self.error(message, self.current))
@@ -270,29 +288,47 @@ impl Executor {
}
}
pub(super) fn ship_pdf_link_material(
&mut self,
b: &NativeBox,
device: &ShipoutDevice,
pub(super) fn begin_pdf_link_shipout(
&mut self, b: &NativeBox, device: &ShipoutDevice,
) -> PdfLinkShipout {
let mut output_count = 0;
let mut paint_count = 0;
let mut events = Vec::new();
// The output index orders I/O and graphics, and the paint index
// places row starts relative to the font programs encountered between them.
b.walk_pdf_links(&mut |x, y, item| match item {
BoxPaint::Output(_) => output_count += 1,
BoxPaint::Box(_) => paint_count += 1,
BoxPaint::RowStart(row) => events.push(((output_count, paint_count), x, y, LinkPaint::RowStart(row))),
BoxPaint::PdfLink(_, row) => events.push(((output_count, paint_count), x, y, LinkPaint::Node(row))),
BoxPaint::PdfGraphics => events.push(((output_count, paint_count), x, y, LinkPaint::Graphics)),
_ => {}
});
PdfLinkShipout {
events: events.into_iter().peekable(),
output_count,
active: std::mem::take(&mut self.pdf_link_stack),
transform: (Affine::IDENTITY, false),
saved: Vec::new(),
graphics_index: 0,
output: PageLinks::default(),
origin: [device.horizontal_origin, device.vertical_origin + b.height],
margin: i64::from(self.read_parameter(Parameter::Pdflinkmargin).width()),
numbered: self.state.input_profile() == InputProfile::TeX8Bit,
}
}
}
impl PdfLinkShipout {
pub(super) fn advance(
&mut self, executor: &mut Executor, through: (usize, usize), outputs: &[&OutputNode],
graphics: &[Option<PdfGraphics>],
numbers: (Vec<u32>, Vec<Option<u32>>),
files: &mut impl SourceProvider,
) -> Result<PageLinks, Error> {
let margin = i64::from(self.read_parameter(Parameter::Pdflinkmargin).width());
let numbered = self.state.input_profile() == InputProfile::TeX8Bit;
let (links, destinations) = numbers;
let mut links = links.into_iter();
let mut destinations = destinations.into_iter();
let mut active = std::mem::take(&mut self.pdf_link_stack);
let mut graphics = graphics.iter();
let mut transform = (Affine::IDENTITY, false);
let mut saved = Vec::new();
let mut output = PageLinks::default();
let mut failure = None;
let origin_x = device.horizontal_origin;
let origin_y = device.vertical_origin + b.height;
b.walk_pdf_links(&mut |x, y, item| {
if failure.is_some() { return; }
) -> Result<(), Error> {
let current = executor.current;
while self.events.peek().is_some_and(|event| event.0 <= through) {
let ((output_index, _), x, y, item) = self.events.next().unwrap();
let [origin_x, origin_y] = self.origin;
let (x, y) = (x + origin_x, y + origin_y);
let absolute_row = |mut row: BoxLayout| {
row.left += origin_x;
@@ -300,95 +336,91 @@ impl Executor {
row
};
match item {
BoxPaint::PdfGraphics => match graphics.next().map(Option::as_ref) {
Some(Some(PdfGraphics::Save)) => saved.push(transform),
Some(Some(operation @ (PdfGraphics::Matrix(matrix) | PdfGraphics::SaveMatrix(matrix)))) => {
if matches!(operation, PdfGraphics::SaveMatrix(_)) {
saved.push(transform);
}
transform = (transform.0.concatenate(matrix.about(x as f64, y as f64, true)), true);
}
Some(Some(PdfGraphics::Restore { shift: [dx, dy] })) => {
if let Some(previous) = saved.pop() {
transform = (previous.0.concatenate(Affine::translation(*dx as f64, *dy as f64)),
previous.1 || *dx != 0 || *dy != 0);
}
}
Some(Some(PdfGraphics::Literal { .. }) | None) => {}
None => failure = Some(self.error("missing PDF transform at link shipout", self.current)),
},
BoxPaint::RowStart(row) if self.pdf_running_links => {
for link in active.iter_mut().filter(|link| {
link.level == row.level && link.layout.width.is_none()
}) {
let number = if numbered {
match self.register_pdf_link(None) {
Ok(number) => Some(number),
Err(error) => { failure = Some(error); return; }
LinkPaint::Graphics => {
let entry = graphics.get(self.graphics_index).ok_or_else(|| {
executor.error("missing PDF transform at link shipout", executor.current)
})?;
self.graphics_index += 1;
match entry {
Some(PdfGraphics::Save) => self.saved.push(self.transform),
Some(operation @ (PdfGraphics::Matrix(matrix) | PdfGraphics::SaveMatrix(matrix))) => {
if matches!(operation, PdfGraphics::SaveMatrix(_)) {
self.saved.push(self.transform);
}
} else {
None
};
link.start_segment(&mut output, absolute_row(row), [x, y], transform, margin);
output.annotations.last_mut().unwrap().object_number = number;
self.transform = (self.transform.0.concatenate(matrix.about(x as f64, y as f64, true)), true);
}
Some(PdfGraphics::Restore { shift: [dx, dy] }) => {
if let Some(previous) = self.saved.pop() {
self.transform = (previous.0.concatenate(Affine::translation(*dx as f64, *dy as f64)),
previous.1 || *dx != 0 || *dy != 0);
}
}
Some(PdfGraphics::Literal { .. }) | None => {}
}
}
BoxPaint::PdfLink(node, container) => {
LinkPaint::RowStart(row) if executor.pdf_running_links => {
for link in self.active.iter_mut().filter(|link| {
link.level == row.level && link.layout.width.is_none()
}) {
let number = if self.numbered { Some(executor.register_pdf_link(None)?) } else { None };
link.start_segment(&mut self.output, absolute_row(row), [x, y], self.transform, self.margin);
self.output.annotations.last_mut().unwrap().object_number = number;
}
}
LinkPaint::Node(container) => {
let node = outputs[output_index - 1];
let OutputOperation::PdfLink(link) = &node.operation else {
return executor.fail("PDF navigation and output traversal diverged");
};
let container = absolute_row(container);
self.current = node.span;
let OutputOperation::PdfLink(link) = &node.operation else { unreachable!() };
executor.current = node.span;
match link {
LinkNode::Start(layout) => {
if !container.horizontal {
failure = Some(self.error("PDF link start arrived outside a horizontal list", node.span));
return;
if self.active.len() == 10 {
return executor.fail("PDF link stack capacity exceeded");
}
let attributes = self.token_list_text(&layout.attributes);
if !container.horizontal {
return executor.fail("PDF link start arrived outside a horizontal list");
}
let number = if self.numbered {
Some(executor.register_pdf_link(layout.object_number)?)
} else {
layout.object_number
};
let attributes = executor.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::User(tokens) => AnnotationAction::User(executor.token_list_text(tokens)),
LinkAction::GotoName(tokens) => AnnotationAction::GotoName(executor.token_list_text(tokens)),
LinkAction::Catalog(action) => AnnotationAction::Catalog(action.clone()),
};
let mut start = ActiveLink { layout: layout.clone(), attributes,
action, level: container.level, segment: None };
start.start_segment(&mut output, container, [x, y], transform, margin);
let number = if numbered { links.next() } else { layout.object_number };
if numbered && number.is_none() {
failure = Some(self.error("missing PDF link number at shipout", node.span));
return;
}
output.annotations.last_mut().unwrap().object_number = number;
active.push(start);
start.start_segment(&mut self.output, container, [x, y], self.transform, self.margin);
self.output.annotations.last_mut().unwrap().object_number = number;
self.active.push(start);
}
LinkNode::End => {
let Some(link) = active.pop() else {
failure = Some(self.error("\\pdfendlink used without \\pdfstartlink", node.span));
return;
let Some(link) = self.active.pop() else {
return executor.fail("\\pdfendlink used without \\pdfstartlink");
};
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 {
failure = Some(self.error(error, node.span));
return;
}
files.observe_diagnostic(WriteDestination::TerminalAndLog,
"pdfTeX warning: pdftex: \\pdfendlink ended up in different nesting level than \\pdfstartlink\n")
.map_err(|error| executor.error(error, node.span))?;
}
link.end_segment(&mut output, x, margin);
link.end_segment(&mut self.output, x, self.margin);
}
LinkNode::Running(enabled) => self.pdf_running_links = *enabled,
LinkNode::Running(enabled) => executor.pdf_running_links = *enabled,
LinkNode::Destination { destination, view, structure } => {
let destination = self.pdf_destination_id(destination);
let object_number = if numbered {
let Some(number) = destinations.next() else {
failure = Some(self.error("missing PDF destination number at shipout", node.span));
return;
};
number
let destination = executor.pdf_destination_id(destination);
let object_number = if self.numbered {
executor.register_pdf_destination(destination.clone(), structure.is_some())?
} else {
None
};
let transform = self.transform;
let view = view.map_rectangle(|[width, height, depth]| {
let margin = i64::from(self.read_parameter(Parameter::Pdfdestmargin).width());
let margin = i64::from(executor.read_parameter(Parameter::Pdfdestmargin).width());
let top = height.map_or(container.baseline - container.height, |h| y - i64::from(h));
let right = width.map_or(container.left + container.width, |w| x + i64::from(w));
let bottom = depth.map_or(container.baseline + container.depth, |d| y + i64::from(d));
@@ -398,7 +430,7 @@ impl Executor {
[x - margin, top - margin, right + margin, bottom + margin]
}
});
output.destinations.push(PageDestination {
self.output.destinations.push(PageDestination {
object_number, destination, point: map_point(transform.0, x, y), view,
structure: *structure,
});
@@ -407,17 +439,24 @@ impl Executor {
}
_ => {}
}
});
if let Some(error) = failure {
return Err(error);
}
if links.next().is_some() || destinations.next().is_some() {
return self.fail("unused PDF navigation numbers at shipout");
executor.current = current;
Ok(())
}
pub(super) fn finish(
mut self, executor: &mut Executor, outputs: &[&OutputNode], graphics: &[Option<PdfGraphics>],
files: &mut impl SourceProvider,
) -> Result<PageLinks, Error> {
let output_count = outputs.len();
if self.output_count != output_count {
return executor.fail("PDF navigation and output traversal diverged");
}
for link in &mut active {
self.advance(executor, (output_count, usize::MAX), outputs, graphics, files)?;
for link in &mut self.active {
link.segment = None;
}
self.pdf_link_stack = active;
Ok(output)
executor.pdf_link_stack = self.active;
Ok(self.output)
}
}