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

+53 -10
View File
@@ -135,16 +135,29 @@ fn text_node_count(nodes: &[TextNode]) -> usize {
})
.sum()
}
enum PackedHorizontal {
enum PackedHorizontal<'a> {
Item(HorizontalItem),
PdfColor,
PdfGraphics,
PdfLink(&'a OutputNode),
}
enum BoxPaint<'a> {
pub(super) enum BoxPaint<'a> {
Box(&'a HorizontalBox),
PdfColor,
PdfGraphics,
RowStart(RowLayout),
PdfLink(&'a OutputNode, Option<RowLayout>),
}
#[derive(Clone, Copy)]
pub(super) struct RowLayout {
pub left: i64,
pub baseline: i64,
pub width: i64,
pub height: i64,
pub depth: i64,
pub level: usize,
}
pub(super) enum GeometryItem {
@@ -200,13 +213,14 @@ impl NativeBox {
.into_iter()
.filter_map(|item| match item {
PackedHorizontal::Item(value) => Some(value),
PackedHorizontal::PdfColor | PackedHorizontal::PdfGraphics => None,
PackedHorizontal::PdfColor | PackedHorizontal::PdfGraphics
| PackedHorizontal::PdfLink(_) => None,
})
.collect(),
)
}
fn packed_horizontal(&self) -> Option<Vec<PackedHorizontal>> {
fn packed_horizontal(&self) -> Option<Vec<PackedHorizontal<'_>>> {
let BoxContent::Horizontal(nodes) = &self.content else {
return None;
};
@@ -252,6 +266,10 @@ impl NativeBox {
items.push(PackedHorizontal::PdfGraphics);
continue;
}
TextNode::Output(node) if node.is_pdf_link() => {
items.push(PackedHorizontal::PdfLink(node));
continue;
}
TextNode::Output(node) => {
let Some(image) = node.image_box() else {
continue;
@@ -614,6 +632,7 @@ impl NativeBox {
emit(GeometryItem::PdfGraphics { x, y });
return;
}
BoxPaint::RowStart(_) | BoxPaint::PdfLink(_, _) => return,
};
if let Some(child) = &b.math_geometry {
for p in &child.items {
@@ -646,11 +665,27 @@ impl NativeBox {
}
fn walk(&self, x: i64, y: i64, emit: &mut dyn FnMut(i64, i64, BoxPaint<'_>)) {
self.walk_at(x, y, 0, false, emit);
}
pub(super) fn walk_pdf_links(&self, emit: &mut dyn FnMut(i64, i64, BoxPaint<'_>)) {
self.walk_at(0, 0, 0, true, emit);
}
fn walk_at(&self, x: i64, y: i64, level: usize, links: bool,
emit: &mut dyn FnMut(i64, i64, BoxPaint<'_>)) {
if self.kind.is_unset() {
return;
}
match &self.content {
BoxContent::Horizontal(_) => walk_row(&self.packed_horizontal().unwrap(), x, y, emit),
BoxContent::Horizontal(_) => {
let row = RowLayout { 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, emit);
}
BoxContent::Vertical(nodes) => {
let mut cursor = y - self.height;
let (mut cumulative, mut previous) = (0, 0);
@@ -661,7 +696,7 @@ impl NativeBox {
continue;
}
cursor += b.height;
b.walk(x + b.shift, cursor, emit);
b.walk_at(x + b.shift, cursor, level + 1, links, emit);
cursor += b.depth;
}
NativeVerticalNode::Glue(g) | NativeVerticalNode::NamedGlue(g, _) => {
@@ -685,6 +720,11 @@ impl NativeBox {
NativeVerticalNode::Output(node) if node.is_pdf_graphics() => {
emit(x, cursor, BoxPaint::PdfGraphics);
}
NativeVerticalNode::Output(node) if node.is_pdf_link() => {
if links {
emit(x, cursor, BoxPaint::PdfLink(node, None));
}
}
NativeVerticalNode::Output(node) => {
if let Some(image) = node.image_box() {
cursor += image.height;
@@ -707,16 +747,18 @@ pub(super) fn bp(n: i64) -> i64 {
}
}
fn walk_row(
items: &[PackedHorizontal],
mut x: i64,
y: i64,
items: &[PackedHorizontal<'_>],
row: RowLayout,
links: bool,
emit: &mut dyn FnMut(i64, i64, BoxPaint<'_>),
) {
let mut x = row.left;
let y = row.baseline;
for item in items {
match item {
PackedHorizontal::Item(HorizontalItem::Box(b)) => {
if let Some(child) = &b.native_box {
child.walk(x, y + child.shift, emit);
child.walk_at(x, y + child.shift, row.level + 1, links, emit);
} else {
emit(x, y, BoxPaint::Box(b));
}
@@ -725,6 +767,7 @@ fn walk_row(
PackedHorizontal::Item(HorizontalItem::Glue { width, .. }) => x += width,
PackedHorizontal::PdfColor => emit(x, y, BoxPaint::PdfColor),
PackedHorizontal::PdfGraphics => emit(x, y, BoxPaint::PdfGraphics),
PackedHorizontal::PdfLink(node) if links => emit(x, y, BoxPaint::PdfLink(node, Some(row))),
_ => {}
}
}
@@ -25,6 +25,8 @@ pub struct NativeShipout {
pub(super) pdf_color_steps: Vec<Option<Arc<PdfColorProgram>>>,
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub(super) pdf_graphics_steps: Vec<PdfGraphics>,
#[serde(default, skip_serializing_if = "crate::pdf_device::links::PageLinks::is_empty")]
pub(super) pdf_links: crate::pdf_device::links::PageLinks,
}
impl NativeShipout {
pub fn display_list(&self) -> Result<crate::render::DisplayList, String> {
@@ -34,6 +36,7 @@ impl NativeShipout {
magnification: self.device.magnification,
units: crate::render::DisplayUnits::TeX,
pdf: self.device.pdf.clone(),
pdf_links: self.pdf_links.clone(),
..Default::default()
};
use crate::{math_engine_tex::MathItem, render::DisplayItem};
@@ -533,6 +533,14 @@ impl Printer<'_> {
}
OutputOperation::PdfSave => self.command("pdfsave"),
OutputOperation::PdfRestore => self.command("pdfrestore"),
OutputOperation::PdfLink(node) => {
use crate::pdf_device::links::LinkNode;
self.command(match node {
LinkNode::Start(_) => "pdfstartlink",
LinkNode::End => "pdfendlink",
LinkNode::Destination { .. } => "pdfdest",
});
}
OutputOperation::PdfSetMatrix(tokens) => {
self.command("pdfsetmatrix");
self.tokens(tokens)?;
+88 -57
View File
@@ -23,6 +23,7 @@ mod page;
mod paragraphs;
mod pdf_color;
mod pdf_graphics;
mod pdf_links;
mod pdf_image;
mod quantities;
mod restores;
@@ -160,6 +161,7 @@ pub struct Executor {
expansion_depth: usize,
io: IoState,
pdf_colors: crate::pdf_device::PdfColorStacks,
pdf_link_stack: Vec<pdf_links::ActiveLink>,
pdf_images: Vec<pdf_image::RegisteredImage>,
input_position: Option<(usize, usize)>,
paragraph: Option<super::paragraph::Builder>,
@@ -173,6 +175,7 @@ pub struct Executor {
math_tokens_processed: usize,
display: Option<display::DisplayFrame>,
native_page: Option<NativePageState>,
split_discards: Vec<NativeVerticalNode>,
output_frame: Option<page::OutputFrame>,
pending_shipouts: VecDeque<NativeBox>,
job_ended: bool,
@@ -226,6 +229,7 @@ impl Executor {
expansion_depth: 0,
io: IoState::default(),
pdf_colors: Default::default(),
pdf_link_stack: Vec::new(),
pdf_images: Vec::new(),
input_position: None,
paragraph: None,
@@ -239,6 +243,7 @@ impl Executor {
math_tokens_processed: 0,
display: None,
native_page: None,
split_discards: Vec::new(),
output_frame: None,
pending_shipouts: VecDeque::new(),
job_ended: false,
@@ -262,6 +267,7 @@ impl Executor {
executor.sources = execution.sources;
executor.stream_sources = execution.stream_sources;
executor.generated_inputs = execution.generated_inputs;
executor.split_discards = execution.split_discards;
executor.io = execution.io;
executor.after_assignment = execution.after_assignment;
executor.input_position = execution.input_position;
@@ -528,22 +534,44 @@ impl Executor {
return self.fail("native expansion nesting limit exceeded");
}
self.expansion_depth += 1;
let result = self.expand_one_inner(input, files, definition_context);
let result = if input.frozen {
Ok(Some(input))
} else {
match self.meaning(&input.token) {
Meaning::Primitive(Primitive::Expandafter) => self.expand_after(&input.token, files),
meaning => self.expand_one_inner(input, meaning, files, definition_context),
}
};
self.expansion_depth -= 1;
result
}
// Keep the recursive path outside the expansion dispatch frame.
fn expand_after(
&mut self,
token: &Token,
files: &mut impl SourceProvider,
) -> Result<Option<InputToken>, Error> {
if self.read_parameter(Parameter::Tracingcommands).width() > 1 {
self.trace_command(token, files)?;
}
let first = self.required_raw(files)?;
let second = self.required_raw(files)?;
if let Some(second) = self.expand_one(second, files, false)? {
self.unread(second)?;
}
self.unread(first)?;
Ok(None)
}
fn expand_one_inner(
&mut self,
input: InputToken,
meaning: Meaning,
files: &mut impl SourceProvider,
definition_context: bool,
) -> Result<Option<InputToken>, Error> {
if input.frozen {
return Ok(Some(input));
}
let token = &input.token;
use Primitive::*;
match self.meaning(token) {
match meaning {
Meaning::Undefined => {
return self.fail(format!(
"undefined native control sequence: {}",
@@ -574,14 +602,6 @@ impl Executor {
next.frozen = matches!(next.token.kind, TokenKind::Command(_));
return Ok(Some(next));
}
Expandafter => {
let first = self.required_raw(files)?;
let second = self.required_raw(files)?;
if let Some(second) = self.expand_one(second, files, false)? {
self.unread(second)?;
}
self.unread(first)?;
}
Number => {
let value = self.integer(files)?;
self.print_tokens(&value.to_string(), token)?;
@@ -1573,6 +1593,46 @@ impl Executor {
});
Ok(())
}
fn define_shorthand(
&mut self,
primitive: Primitive,
global: bool,
files: &mut impl SourceProvider,
) -> Result<(), Error> {
use Primitive::*;
let name = self.command(files)?;
// The new name can be the very next token after the number.
self.define_traced(name.clone(), Meaning::Primitive(Relax), global, files)?;
self.optional_equals(files)?;
let value = match primitive {
Chardef => Meaning::CharGiven(
u8::try_from(self.integer(files)?)
.map_err(|_| self.error("chardef must be in 0..255", self.current))?,
),
Mathchardef => {
let code = self.integer(files)?;
if !(0..32768).contains(&code) {
return self.fail("mathchardef must be in 0..32767");
}
Meaning::MathCharGiven(code as u16)
}
Countdef => Meaning::Count(self.register_index(files)?),
Toksdef => Meaning::Toks(self.register_index(files)?),
Dimendef | Skipdef | Muskipdef => {
let kind = match primitive {
Dimendef => RegisterKind::Dimen,
Skipdef => RegisterKind::Skip,
_ => RegisterKind::Muskip,
};
Meaning::Register(Register {
kind,
index: self.register_index(files)?,
})
}
_ => unreachable!("shorthand definition primitive"),
};
self.define_traced(name, value, global, files)
}
fn optional_equals(&mut self, files: &mut impl SourceProvider) -> Result<(), Error> {
let token = self.expanded_non_space(files)?;
if !matches!(token.token.kind, TokenKind::Character('=', CatCode::Other)) {
@@ -2469,6 +2529,9 @@ impl Executor {
OutputOperation::PdfColor { .. } => {
return self.fail("PDF color operation requires native PDF paint");
}
OutputOperation::PdfLink(_) => {
return self.fail("PDF link operation requires a positioned shipout");
}
OutputOperation::PdfSave
| OutputOperation::PdfSetMatrix(_)
| OutputOperation::PdfRestore => {
@@ -2549,6 +2612,7 @@ impl Executor {
job_name: self.job_name,
interaction_mode: self.interaction_mode,
native_page: self.native_page,
split_discards: self.split_discards,
after_assignment: self.after_assignment,
incoming_state,
outgoing_state: self.state.fingerprint(),
@@ -2851,6 +2915,7 @@ impl Executor {
after_assignment: self.after_assignment,
events: self.events,
native_page: self.native_page,
split_discards: self.split_discards,
outgoing_state: self.state.fingerprint(),
state: self.state,
io: self.io,
@@ -2986,6 +3051,8 @@ impl Executor {
| Primitive::Hrule
| Primitive::Unvbox
| Primitive::Unvcopy
| Primitive::Pagediscards
| Primitive::Splitdiscards
| Primitive::Halign
)
)
@@ -3187,7 +3254,9 @@ impl Executor {
files,
)?,
Raise | Lower | Moveleft | Moveright => self.shift_box(primitive, files)?,
Unhbox | Unhcopy | Unvbox | Unvcopy => self.unpackage(primitive, files)?,
Unhbox | Unhcopy | Unvbox | Unvcopy | Pagediscards | Splitdiscards => {
self.unpackage(primitive, files)?
}
Unskip | Unkern | Unpenalty => self.delete_last(primitive)?,
ItalicCorrection => self.append_italic_correction()?,
Shipout => self.scan_box(boxes::Destination::Shipout, files)?,
@@ -3277,6 +3346,9 @@ impl Executor {
Pdfsave | Pdfsetmatrix | Pdfrestore => {
self.scan_pdf_graphics(primitive, token.span, files)?
}
Pdfstartlink | Pdfendlink | Pdfdest => {
self.scan_pdf_link(primitive, token.span, files)?;
}
Pdfximage => self.scan_pdf_image(&token, false, files)?,
Pdfrefximage => self.reference_pdf_image(&token, files)?,
_ => {
@@ -3634,49 +3706,8 @@ impl Executor {
},
)?;
}
Some(Chardef | Mathchardef) => {
let name = self.command(files)?;
self.optional_equals(files)?;
let code = self.integer(files)?;
let value = if primitive == Some(Chardef) {
Meaning::CharGiven(
u8::try_from(code)
.map_err(|_| self.error("chardef must be in 0..255", self.current))?,
)
} else {
if !(0..32768).contains(&code) {
return self.fail("mathchardef must be in 0..32767");
}
Meaning::MathCharGiven(code as u16)
};
self.define_traced(name, value, global, files)?;
}
Some(Countdef | Toksdef) => {
let name = self.command(files)?;
self.optional_equals(files)?;
let index = self.register_index(files)?;
let value = if primitive == Some(Countdef) {
Meaning::Count(index)
} else {
Meaning::Toks(index)
};
self.define_traced(name, value, global, files)?;
}
Some(Dimendef | Skipdef | Muskipdef) => {
let name = self.command(files)?;
self.optional_equals(files)?;
let index = self.register_index(files)?;
let kind = match primitive {
Some(Dimendef) => RegisterKind::Dimen,
Some(Skipdef) => RegisterKind::Skip,
_ => RegisterKind::Muskip,
};
self.define_traced(
name,
Meaning::Register(Register { kind, index }),
global,
files,
)?;
Some(p @ (Chardef | Mathchardef | Countdef | Toksdef | Dimendef | Skipdef | Muskipdef)) => {
self.define_shorthand(p, global, files)?;
}
Some(Dimen | Skip | Muskip) => {
let register = self.scan_register(primitive.unwrap(), files)?;
@@ -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);
@@ -7,7 +7,7 @@ use std::{
path::Path,
};
const SCHEMA: u32 = 20;
const SCHEMA: u32 = 22;
const ENGINE: &str = concat!("texrra-native/", env!("CARGO_PKG_VERSION"));
#[derive(serde::Serialize, serde::Deserialize)]
@@ -213,7 +213,7 @@ impl PageInsertions {
let tail = insertion.nodes.split_off(cut);
nodes.append(&mut insertion.nodes);
let tail =
super::vertical_break::prune_top(tail, insertion.split_top, steps, limit)?;
super::vertical_break::prune_top(tail, insertion.split_top, None, steps, limit)?;
if !tail.is_empty() {
let b = package(tail, insertion.span)?;
insertion.natural_size = b.height + b.depth;
@@ -214,6 +214,7 @@ pub enum OutputOperation {
PdfSave,
PdfSetMatrix(Vec<Token>),
PdfRestore,
PdfLink(crate::pdf_device::links::LinkNode),
PdfImage {
image: std::sync::Arc<crate::pdf_image::PdfImageUse>,
origin: super::TokenOrigin,
@@ -227,6 +228,10 @@ pub struct OutputNode {
}
impl OutputNode {
pub(super) fn is_pdf_link(&self) -> bool {
matches!(self.operation, OutputOperation::PdfLink(_))
}
pub(super) fn is_pdf_graphics(&self) -> bool {
matches!(
self.operation,
@@ -366,6 +366,7 @@ pub enum Dependency {
Hyphenation,
BoxRegister(u16),
SplitMarks(u16),
SplitDiscards,
PageState,
PageMarks(u16),
MathCode(u8),
@@ -500,6 +501,8 @@ pub struct Execution {
#[serde(default = "default_interaction_mode")]
pub interaction_mode: u8,
pub native_page: Option<NativePageState>,
#[serde(default)]
pub split_discards: Vec<NativeVerticalNode>,
pub after_assignment: Option<Token>,
pub events: Vec<Event>,
pub state: State,
@@ -95,6 +95,8 @@ pub struct NativePageState {
pub max_depth: i32,
pub nodes: Vec<NativeVerticalNode>,
pub contributions: VecDeque<NativeVerticalNode>,
#[serde(default)]
pub(super) discards: Vec<NativeVerticalNode>,
pub dead_cycles: i32,
pub output_active: bool,
#[serde(default)]
@@ -157,6 +159,7 @@ impl NativePageState {
}
pub(super) fn resume_contributions(&mut self, output_material: Vec<NativeVerticalNode>) {
self.discards.clear();
let held = self.insertions.held.drain(..);
for node in held.chain(output_material).rev() {
self.contributions.push_front(node);
@@ -194,6 +197,23 @@ impl NativePageState {
_ => 0,
};
let dimensions = front.dimensions();
if !self.started
&& matches!(
front,
NativeVerticalNode::Glue(_)
| NativeVerticalNode::NamedGlue(_, _)
| NativeVerticalNode::Kern(_)
| NativeVerticalNode::ImplicitKern(_)
| NativeVerticalNode::Penalty(_)
)
{
let node = self.contributions.pop_front().unwrap();
reads.insert(Dependency::Parameter(Parameter::Savingvdiscards));
if state.parameter(Parameter::Savingvdiscards).width() > 0 {
self.discards.push(node);
}
continue;
}
if !self.started && dimensions.is_some() {
self.started = true;
self.freeze_specs(state, trace);
@@ -207,10 +227,6 @@ impl NativePageState {
}
let penalty = match front {
NativeVerticalNode::Glue(_) | NativeVerticalNode::NamedGlue(_, _) => {
if !self.started {
self.contributions.pop_front();
continue;
}
self.nodes
.last()
.filter(|n| {
@@ -227,10 +243,6 @@ impl NativePageState {
.map(|_| 0)
}
NativeVerticalNode::Kern(_) | NativeVerticalNode::ImplicitKern(_) => {
if !self.started {
self.contributions.pop_front();
continue;
}
if self.contributions.len() == 1 {
return Ok(None);
}
@@ -240,13 +252,7 @@ impl NativePageState {
)
.then_some(0)
}
NativeVerticalNode::Penalty(p) => {
if !self.started {
self.contributions.pop_front();
continue;
}
Some(*p)
}
NativeVerticalNode::Penalty(p) => Some(*p),
_ => None,
};
if let Some(p) = penalty.filter(|p| *p < 10000) {
@@ -32,6 +32,7 @@ pub enum Parameter {
Pdfpageheight,
Pdfhorigin,
Pdfvorigin,
Pdflinkmargin,
Errorcontextlines,
Showboxbreadth,
Showboxdepth,
@@ -80,6 +81,7 @@ pub enum Parameter {
Outputpenalty,
Floatingpenalty,
Holdinginserts,
Savingvdiscards,
Linepenalty,
Hyphenpenalty,
Exhyphenpenalty,
@@ -142,6 +144,7 @@ impl Parameter {
Self::Pdfpageheight,
Self::Pdfhorigin,
Self::Pdfvorigin,
Self::Pdflinkmargin,
Self::Errorcontextlines,
Self::Showboxbreadth,
Self::Showboxdepth,
@@ -190,6 +193,7 @@ impl Parameter {
Self::Outputpenalty,
Self::Floatingpenalty,
Self::Holdinginserts,
Self::Savingvdiscards,
Self::Linepenalty,
Self::Hyphenpenalty,
Self::Exhyphenpenalty,
@@ -230,6 +234,7 @@ impl Parameter {
| Self::Pdfpageheight
| Self::Pdfhorigin
| Self::Pdfvorigin
| Self::Pdflinkmargin
| Self::Delimitershortfall
| Self::Predisplaysize
| Self::Displaywidth
@@ -105,6 +105,9 @@ pub enum Primitive {
Pdfcolorstackinit,
Pdfcolorstack,
Pdfsave,
Pdfstartlink,
Pdfendlink,
Pdfdest,
Pdfsetmatrix,
Pdfrestore,
Pdfglyphtounicode,
@@ -232,6 +235,8 @@ pub enum Primitive {
Unhcopy,
Unvbox,
Unvcopy,
Pagediscards,
Splitdiscards,
Lastbox,
Vsplit,
Mark,
@@ -846,6 +851,9 @@ impl Default for State {
("pdfcolorstackinit", Pdfcolorstackinit),
("pdfcolorstack", Pdfcolorstack),
("pdfsave", Pdfsave),
("pdfstartlink", Pdfstartlink),
("pdfendlink", Pdfendlink),
("pdfdest", Pdfdest),
("pdfsetmatrix", Pdfsetmatrix),
("pdfrestore", Pdfrestore),
("pdfglyphtounicode", Pdfglyphtounicode),
@@ -899,6 +907,7 @@ impl Default for State {
| Parameter::Tracingscantokens
| Parameter::Tracingnesting
| Parameter::Tracingassigns
| Parameter::Savingvdiscards
) {
continue;
}
@@ -1121,6 +1130,7 @@ impl State {
Parameter::Tracingscantokens,
Parameter::Tracingnesting,
Parameter::Tracingassigns,
Parameter::Savingvdiscards,
] {
self.commands.insert(
CommandName::Control(parameter.name()),
@@ -1151,6 +1161,8 @@ impl State {
("currentgrouplevel", Currentgrouplevel),
("currentgrouptype", Currentgrouptype),
("lastnodetype", Lastnodetype),
("pagediscards", Pagediscards),
("splitdiscards", Splitdiscards),
("parshapelength", Parshapelength),
("parshapeindent", Parshapeindent),
("parshapedimen", Parshapedimen),
@@ -125,6 +125,7 @@ pub(super) fn find_break(
pub(super) fn prune_top(
nodes: Vec<NativeVerticalNode>,
mut skip: Glue,
mut discards: Option<&mut Vec<NativeVerticalNode>>,
steps: &mut usize,
limit: usize,
) -> Result<Vec<NativeVerticalNode>, String> {
@@ -148,6 +149,8 @@ pub(super) fn prune_top(
| NativeVerticalNode::Output(_)
) {
result.push(node);
} else if let Some(discards) = discards.as_deref_mut() {
discards.push(node);
}
}
Ok(result)
+52 -9
View File
@@ -1717,6 +1717,7 @@ fn write_pdf(
let mut kids = Vec::new();
let mut page_ids: Vec<usize> = Vec::new();
let mut destinations = BTreeMap::new();
let mut form_ids = BTreeMap::new();
for list in pages {
for item in &list.items {
@@ -1828,15 +1829,12 @@ fn write_pdf(
})
.collect::<Vec<_>>();
let annotation_base = image_base + used.len();
let annots = if links.is_empty() {
let annotation_count = links.len() + list.pdf_links.annotations.len();
let annots = if annotation_count == 0 {
String::new()
} else {
let refs = (0..links.len())
.map(|index| {
format!("/Annots [{}]", (annotation_base + index))
.replace("/Annots [", "")
.replacen("]", "", 1)
})
let refs = (0..annotation_count)
.map(|index| format!("{} 0 R", annotation_base + index))
.collect::<Vec<_>>()
.join(" ");
format!(" /Annots [{refs}]")
@@ -1908,6 +1906,37 @@ fn write_pdf(
.into_bytes(),
);
}
for annotation in &list.pdf_links.annotations {
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)),
};
objects.push(format!("<< /Type /Annot {} /Rect [{}] {} >>",
annotation.attributes, coordinates.join(" "), action).into_bytes());
}
for destination in &list.pdf_links.destinations {
use crate::pdf_device::links::DestinationView;
let x = physical(destination.point[0]);
let y = physical(height - destination.point[1]);
let view = match destination.view {
DestinationView::Xyz(zoom) => {
let zoom = zoom.filter(|n| *n > 0).map_or("null".to_owned(),
|n| crate::pdf_device::print_decimal(i64::from(n), 3));
format!("/XYZ {x} {y} {zoom}")
}
DestinationView::Fit => "/Fit".into(),
DestinationView::FitB => "/FitB".into(),
DestinationView::FitH => format!("/FitH {y}"),
DestinationView::FitV => format!("/FitV {x}"),
DestinationView::FitBH => format!("/FitBH {y}"),
DestinationView::FitBV => format!("/FitBV {x}"),
};
destinations.entry(destination.name.clone()).or_insert_with(|| format!("[{page_id} 0 R {view}]"));
}
}
objects[1] = format!(
"<< /Type /Pages /Kids [{}] /Count {} >>",
@@ -1916,6 +1945,7 @@ fn write_pdf(
)
.into_bytes();
let mut catalog = "<< /Type /Catalog /Pages 2 0 R".to_owned();
if !metadata.outline.is_empty() {
let root_id = objects.len() + 1;
objects.push(Vec::new());
@@ -1993,9 +2023,22 @@ fn write_pdf(
metadata.outline.len()
)
.into_bytes();
objects[0] =
format!("<< /Type /Catalog /Pages 2 0 R /Outlines {root_id} 0 R >>").into_bytes();
catalog.push_str(&format!(" /Outlines {root_id} 0 R"));
}
if !destinations.is_empty() {
let mut entries = Vec::with_capacity(destinations.len());
let first = pdf_text(destinations.first_key_value().unwrap().0);
let last = pdf_text(destinations.last_key_value().unwrap().0);
for (name, destination) in destinations {
objects.push(destination.into_bytes());
entries.push(format!("{} {} 0 R", pdf_text(&name), objects.len()));
}
objects.push(format!("<< /Names [{}] /Limits [{first} {last}] >>",
entries.join(" ")).into_bytes());
catalog.push_str(&format!(" /Names << /Dests {} 0 R >>", objects.len()));
}
catalog.push_str(" >>");
objects[0] = catalog.into_bytes();
let info_ref = match metadata_object(metadata) {
Some(object) => {
+1
View File
@@ -74,3 +74,4 @@ pub(crate) use color::{ColorResult, PdfColorStacks};
pub use color::{PdfColorProgram, PdfColorStackAction};
pub(crate) use graphics::Affine;
pub use graphics::{PdfGraphics, PdfMatrix};
pub mod links;
@@ -0,0 +1,71 @@
//! Typed link nodes and the annotations produced when TeX ships their lists.
use crate::execution::Token;
#[derive(Clone, Debug, PartialEq, Eq, Hash, serde::Serialize, serde::Deserialize)]
pub enum LinkAction {
User(Vec<Token>),
GotoName(Vec<Token>),
}
#[derive(Clone, Debug, PartialEq, Eq, Hash, serde::Serialize, serde::Deserialize)]
pub struct LinkStart {
pub width: Option<i32>,
pub height: Option<i32>,
pub depth: Option<i32>,
pub attributes: Vec<Token>,
pub action: LinkAction,
}
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, serde::Serialize, serde::Deserialize)]
pub enum DestinationView {
Xyz(Option<i32>),
Fit,
FitH,
FitV,
FitB,
FitBH,
FitBV,
}
#[derive(Clone, Debug, PartialEq, Eq, Hash, serde::Serialize, serde::Deserialize)]
pub enum LinkNode {
Start(LinkStart),
End,
Destination {
name: Vec<Token>,
view: DestinationView,
},
}
#[derive(Clone, Debug, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
pub enum AnnotationAction {
User(String),
GotoName(String),
}
#[derive(Clone, Debug, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
pub struct LinkAnnotation {
/// Left, top, right and bottom in TeX sp, with y measured down the page.
pub rect: [i64; 4],
pub attributes: String,
pub action: AnnotationAction,
}
#[derive(Clone, Debug, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
pub struct PageDestination {
pub name: String,
pub point: [i64; 2],
pub view: DestinationView,
}
#[derive(Clone, Debug, Default, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
pub struct PageLinks {
pub annotations: Vec<LinkAnnotation>,
pub destinations: Vec<PageDestination>,
}
impl PageLinks {
pub(crate) fn is_empty(&self) -> bool {
self.annotations.is_empty() && self.destinations.is_empty()
}
}
+2
View File
@@ -244,6 +244,7 @@ pub struct DisplayList {
pub magnification: i32,
pub units: DisplayUnits,
pub pdf: Option<crate::pdf_device::PdfPageData>,
pub pdf_links: crate::pdf_device::links::PageLinks,
}
impl Default for DisplayList {
fn default() -> Self {
@@ -256,6 +257,7 @@ impl Default for DisplayList {
magnification: 1000,
units: DisplayUnits::PostScript,
pdf: None,
pdf_links: Default::default(),
}
}
}
@@ -246,7 +246,7 @@ fn genuine_fraction_primitives_and_retained_boxes_survive_format_roundtrip() {
let envelope: serde_json::Value = serde_json::from_slice(&bytes).unwrap();
let payload: serde_json::Value =
serde_json::from_str(envelope["payload"].as_str().unwrap()).unwrap();
assert_eq!(payload["schema"], 20);
assert_eq!(payload["schema"], 22);
let state = State::initex().with_etex();
let loaded = FormatImage::decode(&bytes)
.unwrap()
@@ -334,7 +334,7 @@ fn old_schema_and_missing_unicode_state_are_rejected_even_with_valid_checksums()
let envelope: serde_json::Value = serde_json::from_slice(&encoded).unwrap();
let original: serde_json::Value =
serde_json::from_str(envelope["payload"].as_str().unwrap()).unwrap();
assert_eq!(original["schema"], 20);
assert_eq!(original["schema"], 22);
for (schema, expected) in [
(1, "incompatible native format"),
(2, "incompatible native format"),
@@ -355,7 +355,9 @@ fn old_schema_and_missing_unicode_state_are_rejected_even_with_valid_checksums()
(17, "incompatible native format"),
(18, "incompatible native format"),
(19, "incompatible native format"),
(20, "glyph_unicode"),
(20, "incompatible native format"),
(21, "incompatible native format"),
(22, "glyph_unicode"),
] {
let mut payload = original.clone();
payload["schema"] = schema.into();
@@ -77,6 +77,35 @@ fn quantity_scopes_aliases_state_reads_and_snapshot_restore() {
assert_eq!(messages(&e), ["0.0pt"]);
}
#[test]
fn shorthand_definition_binds_relax_during_the_operand_scan() {
let source = include_str!("fixtures/shorthand/self-referencing.tex");
let native = run(source);
let directory = std::env::temp_dir().join(format!("texrra-shorthand-{}", std::process::id()));
fs::create_dir_all(&directory).unwrap();
fs::write(directory.join("probe.tex"), source).unwrap();
let output = Command::new("pdftex")
.args([
"-ini",
"-etex",
"-interaction=nonstopmode",
"-halt-on-error",
"probe.tex",
])
.current_dir(&directory)
.output()
.unwrap();
let reference = fs::read_to_string(directory.join("probe.log")).unwrap();
assert!(output.status.success(), "{reference}");
let expected: Vec<_> = reference
.match_indices("SHORTHAND-")
.map(|(start, _)| reference[start..].split_inclusive(']').next().unwrap())
.collect();
assert_eq!(expected.len(), 6, "{reference}");
assert_eq!(messages(&native), expected);
fs::remove_dir_all(directory).unwrap();
}
#[test]
fn invalid_quantities_overflows_units_and_readonly_positions_fail() {
let relative = run(r"\dimen0=1em");
@@ -164,7 +164,7 @@ fn new_format_owns_vcenter_and_boxed_math_without_reinjecting_old_meanings() {
let envelope: serde_json::Value = serde_json::from_slice(&bytes).unwrap();
let payload: serde_json::Value =
serde_json::from_str(envelope["payload"].as_str().unwrap()).unwrap();
assert_eq!(payload["schema"], 20);
assert_eq!(payload["schema"], 22);
let executor = FormatImage::decode(&bytes)
.unwrap()
.new_job(
@@ -0,0 +1,111 @@
//! Compare discarded vertical lists and their lifetime with independent INITEX.
use std::{fs, process::Command};
use texrra_tex_core::execution::*;
const PROBE: &str = r#"
\catcode123=1 \catcode125=2 \catcode35=6
\tracingonline=1 \showboxbreadth=100 \showboxdepth=20
\topskip=0pt \splittopskip=0pt \vsize=40pt \vbadness=10000
\def\observe#1{\setbox5=\vbox{#1}\showbox5}
\def\cut{\hrule width7pt height12pt\penalty-10000\relax}
\def\prepare{\setbox1=\vbox{\hrule width1pt height8pt
\penalty-10000 \vskip3pt plus2fil minus1pt \kern5pt
\mark{KEEP} \penalty71 \hrule width2pt height9pt}}
\message{DISCARD-DEFAULT=\the\savingvdiscards}
\savingvdiscards=1
\prepare\setbox2=\vsplit1 to8pt
\showbox1
{\savingvdiscards=0 \observe\splitdiscards}
\observe\splitdiscards
\prepare\setbox2=\vsplit1 to8pt
\setbox2=\vsplit3 to8pt
\observe\splitdiscards
\prepare\setbox2=\vsplit1 to8pt
\savingvdiscards=-1
\prepare\setbox2=\vsplit1 to8pt
\observe\splitdiscards
\savingvdiscards=1
\output{\observe\pagediscards \observe\pagediscards \shipout\box255}
\vskip4pt plus1fil minus2pt \kern5pt \penalty59 \cut
\vskip6pt \cut
\output{\shipout\box255}
\vskip7pt \cut
\observe\pagediscards
\output={}
\vskip8pt \cut
\observe\pagediscards
\prepare\setbox2=\vsplit1 to8pt
\output{\observe\pagediscards \observe\splitdiscards \shipout\box255}
\vskip9pt \cut
\observe\splitdiscards
\end
"#;
struct NoFiles;
impl SourceProvider for NoFiles {
fn read(&mut self, name: &str, _: &str) -> Result<SourceFile, String> {
Err(format!("unexpected input {name}"))
}
}
#[test]
fn vertical_discards_transfer_once_and_expire_at_the_reference_boundaries() {
let dir = std::env::temp_dir().join(format!("texrra-vertical-discards-{}", std::process::id()));
fs::create_dir_all(&dir).unwrap();
fs::write(dir.join("probe.tex"), PROBE).unwrap();
let reference = Command::new("pdftex")
.args(["-ini", "-etex", "-interaction=nonstopmode", "probe.tex"])
.current_dir(&dir)
.output()
.unwrap();
let log = fs::read_to_string(dir.join("probe.log")).unwrap();
assert_eq!(reference.status.code(), Some(1), "{log}");
for line in log.lines().filter(|line| line.starts_with("! ")) {
assert_eq!(line, "! OK.", "{log}");
}
assert!(log.contains("DISCARD-DEFAULT=0"), "{log}");
let expected: Vec<_> = log
.split("> \\box")
.skip(1)
.map(|text| format!("> \\box{}", text.split("! OK.").next().unwrap().trim_end()))
.collect();
assert_eq!(expected.len(), 14, "{log}");
assert!(expected[1].contains("glue 3.0 plus 2.0fil minus 1.0"));
assert!(expected[1].contains("kern 5.0") && expected[1].contains("penalty 71"));
assert!(expected[5].contains("glue 4.0 plus 1.0fil minus 2.0"));
assert!(expected[5].contains("kern 5.0") && expected[5].contains("penalty 59"));
for profile in [InputProfile::TeX8Bit, InputProfile::UnicodeScalar] {
let state = State::initex().with_etex().with_input_profile(profile);
let native = Executor::new(state, Limits::default())
.with_native_pages()
.run(
SourceFile {
name: "probe.tex".into(),
data: PROBE.as_bytes().to_vec(),
},
&mut NoFiles,
)
.unwrap();
let actual: Vec<_> = native
.events
.iter()
.filter_map(|event| match event {
Event::ShowBox(report) => Some(report.text.trim_end()),
_ => None,
})
.collect();
assert_eq!(actual, expected, "{profile:?}");
assert!(native.events.iter().any(|event| {
matches!(event, Event::Message { text, .. } if text == "DISCARD-DEFAULT=0")
}));
assert!(
native
.reads
.contains(&Dependency::Parameter(Parameter::Savingvdiscards))
);
assert!(native.reads.contains(&Dependency::SplitDiscards));
assert!(native.reads.contains(&Dependency::PageState));
}
fs::remove_dir_all(dir).unwrap();
}
@@ -0,0 +1,16 @@
\catcode123=1 \catcode125=2
\toksdef\slot=0\slot={FIRST}
\message{SHORTHAND-FIRST=[\the\slot]}
{\toksdef\slot=1\slot={LOCAL}\message{SHORTHAND-LOCAL=[\the\slot]}}
\message{SHORTHAND-RESTORED=[\the\slot]}
\def\slot{8}
\toksdef\slot=9\slot={REBOUND}
\message{SHORTHAND-REBOUND=[\the\slot|\the\toks9]}
{\global\toksdef\slot=32767\global\slot={EXTENDED}}
\message{SHORTHAND-GLOBAL=[\the\slot|\the\toks32767]}
\countdef\amount=7\amount=37
\dimendef\length=8\length=3pt
\skipdef\spaceamount=9\spaceamount=1pt plus2fil
\muskipdef\mathspace=10\mathspace=2mu
\message{SHORTHAND-REGS=[\the\amount|\the\length|\the\spaceamount|\the\mathspace]}
\end
+5 -2
View File
@@ -89,9 +89,12 @@ pdfTeX 和 XeTeX 的14份完整列表一致,29项定向回归通过。原样 S
推进至与 Elsevier 单栏、双栏共用的 `\pdfcatalog`。原样出版矩阵原生3/10,共享
候选的七项 article 21轮原样对照通过。默认线程栈的深层展开与 CVPR 寄存器
缩略定义的组合候选通过25项定向测试,原样 CVPR 亦推进到 `\pdfcatalog`。
schema22 组合版全工作区1591项通过。按470项冻结源码指纹合入主线,
保留七项 article 共21轮和完整原样出版矩阵的复验结果。
schema23 目录候选实际写出字典、打开动作和目的地引用,519项内核及定向回归
通过。优化构建已完成,真实 LaTeX 格式与全工作区回归正在运行。四份原样项目
及完整出版矩阵从新格式开始复验。
通过。新格式已由真实 LaTeX 启动生成。原样 Springer Nature、Elsevier 单栏和
双栏推进至 `\pdfinfo`,原样 CVPR 推进至 `\firstaid@cref@updatelabeldata`。
七项 article、完整原样矩阵和全工作区回归正在复验。
检查点宿主的独立候选用真实私有文件隔离 aux、日志和账本,TeX 以原逻辑名
读取暂存内容。组合候选在同一版本门禁内发布检查点续跑的 aux、日志、账本和
+8 -1
View File
@@ -158,8 +158,15 @@ CVPR 在 cleveref 自引用的寄存器绑定首停 `\@toksa`。
两种原版引擎。用真实 schema22 格式编译的原样 Springer Nature 在下一处
`\pdfcatalog` 停止,和 Elsevier 单栏、双栏遇到的首处缺失一致。
组合候选的 CVPR 复验也越过了 cleveref 的寄存器绑定,在同一处停止。
该 schema22 组合版通过1591项工作区测试和七项 article 共21轮,已按冻结指纹
合入主线。矩阵原版10/10、原生生成3/10,报告为
`target/p3-register-shorthand/publisher-matrix/report.json`。
schema23 候选已对照 PDF 目录和打开动作,包括直接与间接目的地、外部跳转、
缺失目标、普通与流式 XRef。四份原样项目及全矩阵排入优化构建后的复验。
缺失目标、普通与流式 XRef。优化候选的四份原样项目均越过 `\pdfcatalog`。
Springer Nature、Elsevier CAS SC 和 CAS DC 的新首处缺失是 `\pdfinfo`。
CVPR 在正文的首个引用处进入实际 LaTeX firstaid 的宏调用,首停
`\firstaid@cref@updatelabeldata`。报告保存在 `target/p3-pdf-catalog`,
完整矩阵待复验完成。
单纯生成 PDF 或 DVI 只说明编译路径可达。完整验收要在参考环境闭合后比较页数、
双栏位置及跨栏材料、实际字体/字形、图表浮动、引用收敛、词框及墨迹;测试源
+126
View File
@@ -0,0 +1,126 @@
use lopdf::{Document, Object};
use std::{fs, path::Path, process::Command};
fn resolve<'a>(document: &'a Document, object: &'a Object) -> &'a Object {
match object {
Object::Reference(id) => document.get_object(*id).unwrap(),
object => object,
}
}
fn describe(document: &Document) -> (Vec<Vec<(String, String, String)>>, usize, String) {
let ids: Vec<_> = document.get_pages().into_values().collect();
let annotations = ids
.iter()
.map(|id| {
let page = document.get_object(*id).unwrap().as_dict().unwrap();
page.get(b"Annots").map_or_else(
|_| Vec::new(),
|annots| {
resolve(document, annots)
.as_array()
.unwrap()
.iter()
.map(|item| {
let item = resolve(document, item).as_dict().unwrap();
assert_eq!(item.get(b"Type").unwrap().as_name().unwrap(), b"Annot");
assert_eq!(item.get(b"Subtype").unwrap().as_name().unwrap(), b"Link");
let action = resolve(document, item.get(b"A").unwrap())
.as_dict()
.unwrap();
(
format!("{:?}", item.get(b"Rect").unwrap()),
format!("{:?}", item.get(b"Border").unwrap()),
format!("{:?}", action.get(b"D").unwrap()),
)
})
.collect()
},
)
})
.collect();
let catalog = document.catalog().unwrap();
let names = resolve(document, catalog.get(b"Names").unwrap())
.as_dict()
.unwrap();
let destinations = resolve(document, names.get(b"Dests").unwrap())
.as_dict()
.unwrap();
let pairs = destinations.get(b"Names").unwrap().as_array().unwrap();
assert_eq!(pairs.len(), 2);
assert_eq!(pairs[0].as_str().unwrap(), b"target");
let view = resolve(document, &pairs[1]);
let view = match view {
Object::Dictionary(dictionary) => resolve(document, dictionary.get(b"D").unwrap()),
view => view,
}
.as_array()
.unwrap();
let page = ids
.iter()
.position(|id| *id == view[0].as_reference().unwrap())
.unwrap();
(annotations, page, format!("{:?}", &view[1..]))
}
fn compile(root: &Path, source: &str, native: bool) -> Document {
let work = root.join(if native { "native" } else { "reference" });
fs::create_dir_all(&work).unwrap();
fs::write(work.join("probe.tex"), source).unwrap();
let mut command = if native {
let mut command = Command::new(env!("CARGO_BIN_EXE_texrra"));
command.args([
"native",
"--job",
"--initex",
"--etex",
"probe.tex",
"probe.pdf",
]);
command
} else {
let mut command = Command::new("pdftex");
command.args([
"-ini",
"-etex",
"-interaction=nonstopmode",
"-halt-on-error",
"probe.tex",
]);
command
};
let output = command
.current_dir(&work)
.env("TEXINPUTS", ":")
.env("TEXRRA_STATE_DIR", work.join("state"))
.output()
.unwrap();
assert!(
output.status.success(),
"{}",
String::from_utf8_lossy(&output.stderr)
);
Document::load(work.join("probe.pdf")).unwrap()
}
#[test]
fn real_pdf_link_fragments_and_named_destination_match_pdftex() {
let root = std::env::temp_dir().join(format!("texrra-pdf-links-{}", std::process::id()));
let source = r"\catcode123=1 \catcode125=2
\pdfoutput=1 \pdfcompresslevel=0 \pdfobjcompresslevel=0
\pdfpagewidth=140pt \pdfpageheight=100pt \pdfhorigin=20pt \pdfvorigin=30pt
\pdflinkmargin=1pt
\shipout\vbox{\hsize=40pt \baselineskip=16pt \lineskiplimit=0pt
\parfillskip=0pt plus1fil \noindent
\pdfstartlink attr{/Border [0 0 0]} goto name{target}
\vrule width10pt height5pt depth2pt
\hfil\penalty-10000\relax
\vrule width10pt height5pt depth2pt\pdfendlink\par}
\shipout\hbox{\pdfdest name{target} xyz \vrule width10pt height5pt depth2pt}
\end";
let expected = describe(&compile(&root, source, false));
assert_eq!(expected.0.iter().map(Vec::len).collect::<Vec<_>>(), [2, 0]);
assert_eq!(expected.1, 1);
assert_eq!(describe(&compile(&root, source, true)), expected);
fs::remove_dir_all(root).unwrap();
}