Implement native PDF links and vertical discard lists

This commit is contained in:
gloamxun committed 2026-11-18 23:39:45 +08:00
1 parent b6567f67e2
commit a53d9c9bf9
29 files changed
+980 -109

No files matched your search

@@ -114,13 +114,31 @@ impl Executor {
p: Primitive,
files: &mut impl SourceProvider,
) -> Result<(), Error> {
let vertical = matches!(p, Primitive::Unvbox | Primitive::Unvcopy);
use Primitive::*;
let vertical = matches!(p, Unvbox | Unvcopy | Pagediscards | Splitdiscards);
if vertical && self.paragraph.is_some() {
if self.restricted() || !self.math.is_empty() {
return self.fail("native vertical unboxing requires vertical mode");
}
self.end_paragraph(files)?;
}
if matches!(p, Pagediscards | Splitdiscards) {
if !self.math.is_empty() {
return self.fail("native vertical discards require vertical mode");
}
let nodes = if p == Pagediscards {
self.reads.insert(Dependency::PageState);
self.native_page
.as_mut()
.map(|page| std::mem::take(&mut page.discards))
.unwrap_or_default()
} else {
self.reads.insert(Dependency::SplitDiscards);
std::mem::take(&mut self.split_discards)
};
self.append_unboxed_vertical(nodes);
return Ok(());
}
let index = self.register_index(files)?;
self.reads.insert(Dependency::BoxRegister(index));
let Some(b) = self.state.box_register(index) else {
@@ -145,16 +163,16 @@ impl Executor {
.expect("unhbox starts an actual paragraph")
.nodes
.extend(nodes),
BoxContent::Vertical(nodes) => {
let start = self.vertical.nodes.len();
self.vertical.extend(nodes);
// unpackage transfers nodes without append_to_vlist. In
// particular it neither inserts glue nor updates prev_depth.
self.emit_vertical(start);
}
BoxContent::Vertical(nodes) => self.append_unboxed_vertical(nodes),
}
Ok(())
}
fn append_unboxed_vertical(&mut self, nodes: Vec<NativeVerticalNode>) {
let start = self.vertical.nodes.len();
self.vertical.extend(nodes);
// Transferred list nodes leave prev_depth unchanged.
self.emit_vertical(start);
}
pub(super) fn start_discretionary(
&mut self,
span: Span,
@@ -330,8 +348,9 @@ impl Executor {
}
let height = self.dimension(false, false, files)?.amount;
self.reads.insert(Dependency::BoxRegister(index));
// Splitting clears all split classes globally, including a void box.
// Even splitting a void box clears results from the previous split.
self.state.split_marks.clear();
self.split_discards.clear();
let Some(original) = self.state.box_register(index) else {
return self.deliver_box(None, destination, files);
};
@@ -354,9 +373,11 @@ impl Executor {
.map_err(|e| self.error(e, span))?;
let tail = nodes.split_off(cut.index);
self.collect_split_marks(&nodes)?;
let save = self.read_parameter(Parameter::Savingvdiscards).width() > 0;
let tail = super::super::vertical_break::prune_top(
tail,
skip,
save.then_some(&mut self.split_discards),
&mut self.steps,
self.limits.steps,
)
@@ -271,6 +271,8 @@ impl Executor {
let mut pdf_graphics_steps = Vec::new();
let mut graphics_stack = Vec::new();
let outputs = b.output_nodes();
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 mut graphics_positions = if outputs.iter().any(|node| node.is_pdf_graphics()) {
b.pdf_graphics_positions().into_iter()
} else {
@@ -295,6 +297,20 @@ impl Executor {
&mut graphics_stack,
files,
)?);
} else if let OutputOperation::PdfLink(link) = &output.operation {
use crate::pdf_device::links::LinkNode;
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(_) => link_depth += 1,
LinkNode::End if link_depth == 0 => return self.fail("\\pdfendlink used without \\pdfstartlink"),
LinkNode::End => link_depth -= 1,
LinkNode::Destination { .. } => {}
}
} else {
self.output_node(output, files)?;
}
@@ -311,6 +327,11 @@ impl Executor {
*span,
));
}
let pdf_links = if has_link_material {
self.ship_pdf_link_material(&b, &device, &pdf_graphics_steps, files)?
} else {
Default::default()
};
self.current = current;
self.native_page.as_mut().unwrap().dead_cycles = 0;
let before = self.statistics_before_shipout(&b, files)?;
@@ -320,6 +341,7 @@ impl Executor {
pdf_color_start,
pdf_color_steps,
pdf_graphics_steps,
pdf_links,
})));
self.statistics_after_shipout(before, files)?;
Ok(())
@@ -0,0 +1,296 @@
use super::*;
use crate::pdf_device::{
Affine, PdfGraphics,
links::{
AnnotationAction, DestinationView, LinkAction, LinkAnnotation, LinkNode, LinkStart,
PageDestination, PageLinks,
},
};
use crate::execution::boxes::{BoxPaint, RowLayout};
#[derive(Clone, Copy)]
struct Segment {
index: usize,
rect: [i64; 4],
transform: Affine,
transformed: bool,
}
pub(super) struct ActiveLink {
layout: LinkStart,
attributes: String,
action: AnnotationAction,
level: usize,
segment: Option<Segment>,
}
fn map_point(matrix: Affine, x: i64, y: i64) -> [i64; 2] {
matrix
.point(x as f64, y as f64)
.map(|value| value.round() as i64)
}
fn link_rect(rect: [i64; 4], matrix: Affine, margin: i64) -> [i64; 4] {
let [left, top, right, bottom] = rect;
let corners = [
map_point(matrix, left, top),
map_point(matrix, right, top),
map_point(matrix, left, bottom),
map_point(matrix, right, bottom),
];
[
corners.iter().map(|p| p[0]).min().unwrap() - margin,
corners.iter().map(|p| p[1]).min().unwrap() - margin,
corners.iter().map(|p| p[0]).max().unwrap() + margin,
corners.iter().map(|p| p[1]).max().unwrap() + margin,
]
}
impl ActiveLink {
fn start_segment(
&mut self,
output: &mut PageLinks,
row: RowLayout,
point: [i64; 2],
transform: (Affine, bool),
margin: i64,
) {
let [x, y] = point;
let rect = [
x,
self.layout
.height
.map_or(row.baseline - row.height, |h| y - i64::from(h)),
self.layout
.width
.map_or(row.left + row.width, |w| x + i64::from(w)),
self.layout
.depth
.map_or(row.baseline + row.depth, |d| y + i64::from(d)),
];
self.segment = Some(Segment {
index: output.annotations.len(),
rect,
transform: transform.0,
transformed: transform.1,
});
output.annotations.push(LinkAnnotation {
rect: link_rect(rect, transform.0, margin),
attributes: self.attributes.clone(),
action: self.action.clone(),
});
}
fn end_segment(self, output: &mut PageLinks, x: i64, margin: i64) {
if let Some(segment) = self.segment
&& self.layout.width.is_none()
{
let painted = &mut output.annotations[segment.index].rect;
if segment.transformed {
let mut rect = segment.rect;
// The device extends the running right edge before recalculating
// the transformed rectangle, then applies the annotation margins.
rect[2] = x + margin;
*painted = link_rect(rect, segment.transform, margin);
} else {
painted[2] = x + margin;
}
}
}
}
impl Executor {
fn link_tokens(&mut self, files: &mut impl SourceProvider) -> Result<Vec<Token>, Error> {
self.with_scanner(ScannerStatus::Absorbing, |s| {
s.scan_expanded_group_mode(files, false)
})
}
pub(super) fn scan_pdf_link(
&mut self,
command: Primitive,
span: Span,
files: &mut impl SourceProvider,
) -> Result<(), Error> {
if self.native_page.is_none() || self.read_parameter(Parameter::Pdfoutput).width() <= 0 {
return self.fail("PDF link operation not allowed in DVI mode");
}
if command != Primitive::Pdfdest && self.paragraph.is_none() && self.math.is_empty() {
return self.fail(if command == Primitive::Pdfstartlink {
"\\pdfstartlink cannot be used in vertical mode"
} else {
"\\pdfendlink cannot be used in vertical mode"
});
}
let operation = match command {
Primitive::Pdfstartlink => {
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 attributes = if self.keyword("attr", files)? {
self.link_tokens(files)?
} else {
Vec::new()
};
let action = if self.keyword("user", files)? {
LinkAction::User(self.link_tokens(files)?)
} else if self.keyword("goto", files)? && self.keyword("name", files)? {
LinkAction::GotoName(self.link_tokens(files)?)
} else {
return self.fail("expected a user or named goto PDF link action");
};
LinkNode::Start(LinkStart {
width,
height,
depth,
attributes,
action,
})
}
Primitive::Pdfendlink => LinkNode::End,
Primitive::Pdfdest => {
if !self.keyword("name", files)? {
return self.fail("expected a named PDF destination");
}
let name = self.link_tokens(files)?;
let view = if self.keyword("xyz", files)? {
let zoom = if self.keyword("zoom", files)? {
Some(self.integer(files)?)
} else {
None
};
DestinationView::Xyz(zoom)
} else {
let mut view = None;
for (name, candidate) in [
("fitbh", DestinationView::FitBH),
("fitbv", DestinationView::FitBV),
("fitb", DestinationView::FitB),
("fith", DestinationView::FitH),
("fitv", DestinationView::FitV),
("fit", DestinationView::Fit),
] {
if self.keyword(name, files)? {
view = Some(candidate);
break;
}
}
view.ok_or_else(|| self.error("expected PDF destination view", span))?
};
LinkNode::Destination { name, view }
}
_ => unreachable!(),
};
self.defer_output(OutputNode {
operation: OutputOperation::PdfLink(operation),
span,
})
}
pub(super) fn ship_pdf_link_material(
&mut self,
b: &NativeBox,
device: &ShipoutDevice,
graphics: &[PdfGraphics],
files: &mut impl SourceProvider,
) -> Result<PageLinks, Error> {
let margin = i64::from(self.read_parameter(Parameter::Pdflinkmargin).width());
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; }
let (x, y) = (x + origin_x, y + origin_y);
let absolute_row = |mut row: RowLayout| {
row.left += origin_x;
row.baseline += origin_y;
row
};
match item {
BoxPaint::PdfGraphics => match graphics.next() {
Some(PdfGraphics::Save) => saved.push(transform),
Some(PdfGraphics::Matrix(matrix)) => {
transform = (transform.0.concatenate(matrix.about(x as f64, y as f64, true)), true);
}
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);
}
}
None => failure = Some(self.error("missing PDF transform at link shipout", self.current)),
},
BoxPaint::RowStart(row) => {
for link in active.iter_mut().filter(|link| {
link.level == row.level && link.layout.width.is_none()
}) {
link.start_segment(&mut output, absolute_row(row), [x, y], transform, margin);
}
}
BoxPaint::PdfLink(node, row) => {
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 {
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)),
};
let mut start = ActiveLink { layout: layout.clone(), attributes,
action, level: row.level, segment: None };
start.start_segment(&mut output, row, [x, y], transform, margin);
active.push(start);
}
LinkNode::End => {
let Some(link) = active.pop() else {
failure = Some(self.error("\\pdfendlink used without \\pdfstartlink", node.span));
return;
};
if row.is_none_or(|r| r.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;
}
}
link.end_segment(&mut output, x, margin);
}
LinkNode::Destination { name, view } => output.destinations.push(PageDestination {
name: self.token_list_text(name), point: map_point(transform.0, x, y), view: *view,
}),
}
}
_ => {}
}
});
if let Some(error) = failure {
return Err(error);
}
for link in &mut active {
link.segment = None;
}
self.pdf_link_stack = active;
Ok(output)
}
}
@@ -41,6 +41,7 @@ impl Executor {
c.paragraph_builder(p);
}
c.vertical(&self.vertical.nodes, Active);
c.vertical(&self.split_discards, Active);
if let Some(d) = &self.display {
d.collect_statistics(&mut c);
}
@@ -59,6 +60,7 @@ impl Executor {
if let Some(p) = &self.native_page {
c.vertical(&p.nodes, Active);
c.vertical(&p.contributions, Active);
c.vertical(&p.discards, Active);
}
for b in &self.pending_shipouts {
c.native_box(b, Active);