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
+267 -133

No files matched your search

@@ -886,20 +886,22 @@ impl NativeBox {
pub(super) fn visit_shipout_font_uses( pub(super) fn visit_shipout_font_uses(
&self, &self,
mut emit: impl FnMut(usize, &std::sync::Arc<crate::native_font::NativeFont>, u8), mut emit: impl FnMut(usize, usize, &std::sync::Arc<crate::native_font::NativeFont>, u8),
) -> Result<(), String> { ) -> Result<(), String> {
use crate::math_engine_tex::MathItem; use crate::math_engine_tex::MathItem;
let mut output_count = 0; let mut output_count = 0;
let mut paint_count = 0;
self.walk(0, 0, &mut |_, _, node| match node { self.walk(0, 0, &mut |_, _, node| match node {
BoxPaint::Output(_) => output_count += 1, BoxPaint::Output(_) => output_count += 1,
BoxPaint::Box(b) => { BoxPaint::Box(b) => {
if let Some(geometry) = &b.math_geometry { if let Some(geometry) = &b.math_geometry {
for item in &geometry.items { for item in &geometry.items {
if let MathItem::NativeGlyph { font, slot, .. } = &item.item { if let MathItem::NativeGlyph { font, slot, .. } = &item.item {
emit(output_count, font, *slot); emit(output_count, paint_count, font, *slot);
} }
} }
} }
paint_count += 1;
} }
_ => {} _ => {}
})?; })?;
@@ -39,6 +39,7 @@ pub(super) struct PdfSpaceProbe {
struct ShipoutFontUse { struct ShipoutFontUse {
before_output: usize, before_output: usize,
before_paint: usize,
font: Arc<NativeFont>, font: Arc<NativeFont>,
slot: u8, slot: u8,
} }
@@ -48,11 +49,11 @@ fn shipout_font_uses(
) -> Result<Vec<ShipoutFontUse>, String> { ) -> Result<Vec<ShipoutFontUse>, String> {
let mut uses = Vec::new(); let mut uses = Vec::new();
let mut seen = BTreeSet::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()) if (!programs.is_known_physical(font.id) || fonts.automatic_origin(font.id).is_some())
&& seen.insert((font.id, slot)) && 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) Ok(uses)
@@ -455,9 +456,10 @@ impl Executor {
if let Some(effects) = &leader_effects { if let Some(effects) = &leader_effects {
outputs = effects.outputs.iter().collect(); outputs = effects.outputs.iter().collect();
} }
let mut navigation_numbers = (Vec::new(), Vec::new()); let output_count = outputs.len();
let mut link_depth = self.pdf_link_stack.len(); let has_link_material = !self.pdf_link_stack.is_empty() || outputs.iter().any(|node| node.is_pdf_link());
let has_link_material = link_depth != 0 || 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 { let mut output_positions = if let Some(effects) = &leader_effects {
effects.output_positions.clone().into_iter() effects.output_positions.clone().into_iter()
} else if outputs.iter().any(|node| node.needs_shipout_position()) { } else if outputs.iter().any(|node| node.needs_shipout_position()) {
@@ -483,12 +485,17 @@ impl Executor {
let mut reopened_images = false; let mut reopened_images = false;
let mut xdv_paper_specials = Vec::new(); let mut xdv_paper_specials = Vec::new();
let mut xdv_navigation = 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) { 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.current = current;
self.prepare_virtual_glyph( self.prepare_virtual_glyph(shipout.virtual_glyphs.as_mut().unwrap(), usage, files)?;
shipout.virtual_glyphs.as_mut().unwrap(), font_uses.next().unwrap(), 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() if self.pdf_loaded_space_font.is_none()
&& (uses_automatic_spaces || has_explicit_space) && (uses_automatic_spaces || has_explicit_space)
@@ -665,32 +672,12 @@ impl Executor {
} else { } else {
has_explicit_space = true; has_explicit_space = true;
} }
} else if let OutputOperation::PdfLink(link) = &output.operation { } else if let OutputOperation::PdfLink(_) = &output.operation {
use crate::pdf_device::links::LinkNode;
self.current = output.span; self.current = output.span;
self.tick()?; self.tick()?;
if device.pdf.is_none() { if device.pdf.is_none() {
return self.fail("cannot ship a PDF link operation to DVI"); 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 { } else {
if let OutputOperation::PdfImage { image, .. } = &output.operation { if let OutputOperation::PdfImage { image, .. } = &output.operation {
reopened_images |= image.xdv.is_some() && image.image.is_metadata_only(); reopened_images |= image.xdv.is_some() && image.image.is_metadata_only();
@@ -714,9 +701,20 @@ impl Executor {
)); ));
} }
self.current = current; 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 { 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)?; 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(); shipout.pdf_font_bindings = self.pdf_virtual_fonts.captured_font_bindings();
let has_space_settings = has_space_nodes || automatic_spaces_at_start; let has_space_settings = has_space_nodes || automatic_spaces_at_start;
let probed_page = (uses_automatic_spaces || has_explicit_space) let probed_page = (uses_automatic_spaces || has_explicit_space)
@@ -730,16 +728,6 @@ impl Executor {
shipout.pdf_text_spaces.as_mut().unwrap().dedicated_font = shipout.pdf_text_spaces.as_mut().unwrap().dedicated_font =
self.pdf_loaded_space_font.clone(); 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 { if let Some(objects) = &mut shipout.pdf_objects {
let limit = self.limits.tokens; let limit = self.limits.tokens;
let compression = device.pdf.as_ref().unwrap().file.object_compression; let compression = device.pdf.as_ref().unwrap().file.object_compression;
@@ -26,6 +26,25 @@ pub(super) struct ActiveLink {
segment: Option<Segment>, 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] { fn map_point(matrix: Affine, x: i64, y: i64) -> [i64; 2] {
matrix matrix
.point(x as f64, y as f64) .point(x as f64, y as f64)
@@ -234,10 +253,9 @@ impl Executor {
} }
pub(super) fn register_pdf_destination( 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> { ) -> Result<Option<u32>, Error> {
self.reads.insert(Dependency::PdfObjects); self.reads.insert(Dependency::PdfObjects);
let id = self.pdf_destination_id(id);
self.state.pdf_objects.get_or_insert_with(Default::default) self.state.pdf_objects.get_or_insert_with(Default::default)
.destination_number(id, structure, true, self.limits.tokens) .destination_number(id, structure, true, self.limits.tokens)
.map_err(|message| self.error(message, self.current)) .map_err(|message| self.error(message, self.current))
@@ -270,29 +288,47 @@ impl Executor {
} }
} }
pub(super) fn ship_pdf_link_material( pub(super) fn begin_pdf_link_shipout(
&mut self, &mut self, b: &NativeBox, device: &ShipoutDevice,
b: &NativeBox, ) -> PdfLinkShipout {
device: &ShipoutDevice, 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>], graphics: &[Option<PdfGraphics>],
numbers: (Vec<u32>, Vec<Option<u32>>),
files: &mut impl SourceProvider, files: &mut impl SourceProvider,
) -> Result<PageLinks, Error> { ) -> Result<(), Error> {
let margin = i64::from(self.read_parameter(Parameter::Pdflinkmargin).width()); let current = executor.current;
let numbered = self.state.input_profile() == InputProfile::TeX8Bit; while self.events.peek().is_some_and(|event| event.0 <= through) {
let (links, destinations) = numbers; let ((output_index, _), x, y, item) = self.events.next().unwrap();
let mut links = links.into_iter(); let [origin_x, origin_y] = self.origin;
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; }
let (x, y) = (x + origin_x, y + origin_y); let (x, y) = (x + origin_x, y + origin_y);
let absolute_row = |mut row: BoxLayout| { let absolute_row = |mut row: BoxLayout| {
row.left += origin_x; row.left += origin_x;
@@ -300,95 +336,91 @@ impl Executor {
row row
}; };
match item { match item {
BoxPaint::PdfGraphics => match graphics.next().map(Option::as_ref) { LinkPaint::Graphics => {
Some(Some(PdfGraphics::Save)) => saved.push(transform), let entry = graphics.get(self.graphics_index).ok_or_else(|| {
Some(Some(operation @ (PdfGraphics::Matrix(matrix) | PdfGraphics::SaveMatrix(matrix)))) => { 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(_)) { if matches!(operation, PdfGraphics::SaveMatrix(_)) {
saved.push(transform); self.saved.push(self.transform);
} }
transform = (transform.0.concatenate(matrix.about(x as f64, y as f64, true)), true); self.transform = (self.transform.0.concatenate(matrix.about(x as f64, y as f64, true)), true);
} }
Some(Some(PdfGraphics::Restore { shift: [dx, dy] })) => { Some(PdfGraphics::Restore { shift: [dx, dy] }) => {
if let Some(previous) = saved.pop() { if let Some(previous) = self.saved.pop() {
transform = (previous.0.concatenate(Affine::translation(*dx as f64, *dy as f64)), self.transform = (previous.0.concatenate(Affine::translation(*dx as f64, *dy as f64)),
previous.1 || *dx != 0 || *dy != 0); previous.1 || *dx != 0 || *dy != 0);
} }
} }
Some(Some(PdfGraphics::Literal { .. }) | None) => {} 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 => { LinkPaint::RowStart(row) if executor.pdf_running_links => {
for link in active.iter_mut().filter(|link| { for link in self.active.iter_mut().filter(|link| {
link.level == row.level && link.layout.width.is_none() link.level == row.level && link.layout.width.is_none()
}) { }) {
let number = if numbered { let number = if self.numbered { Some(executor.register_pdf_link(None)?) } else { None };
match self.register_pdf_link(None) { link.start_segment(&mut self.output, absolute_row(row), [x, y], self.transform, self.margin);
Ok(number) => Some(number), self.output.annotations.last_mut().unwrap().object_number = number;
Err(error) => { failure = Some(error); return; }
} }
} else { }
None 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");
}; };
link.start_segment(&mut output, absolute_row(row), [x, y], transform, margin);
output.annotations.last_mut().unwrap().object_number = number;
}
}
BoxPaint::PdfLink(node, container) => {
let container = absolute_row(container); let container = absolute_row(container);
self.current = node.span; executor.current = node.span;
let OutputOperation::PdfLink(link) = &node.operation else { unreachable!() };
match link { match link {
LinkNode::Start(layout) => { LinkNode::Start(layout) => {
if !container.horizontal { if self.active.len() == 10 {
failure = Some(self.error("PDF link start arrived outside a horizontal list", node.span)); return executor.fail("PDF link stack capacity exceeded");
return;
} }
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 { let action = match &layout.action {
LinkAction::User(tokens) => AnnotationAction::User(self.token_list_text(tokens)), LinkAction::User(tokens) => AnnotationAction::User(executor.token_list_text(tokens)),
LinkAction::GotoName(tokens) => AnnotationAction::GotoName(self.token_list_text(tokens)), LinkAction::GotoName(tokens) => AnnotationAction::GotoName(executor.token_list_text(tokens)),
LinkAction::Catalog(action) => AnnotationAction::Catalog(action.clone()), LinkAction::Catalog(action) => AnnotationAction::Catalog(action.clone()),
}; };
let mut start = ActiveLink { layout: layout.clone(), attributes, let mut start = ActiveLink { layout: layout.clone(), attributes,
action, level: container.level, segment: None }; action, level: container.level, segment: None };
start.start_segment(&mut output, container, [x, y], transform, margin); start.start_segment(&mut self.output, container, [x, y], self.transform, self.margin);
let number = if numbered { links.next() } else { layout.object_number }; self.output.annotations.last_mut().unwrap().object_number = number;
if numbered && number.is_none() { self.active.push(start);
failure = Some(self.error("missing PDF link number at shipout", node.span));
return;
}
output.annotations.last_mut().unwrap().object_number = number;
active.push(start);
} }
LinkNode::End => { LinkNode::End => {
let Some(link) = active.pop() else { let Some(link) = self.active.pop() else {
failure = Some(self.error("\\pdfendlink used without \\pdfstartlink", node.span)); return executor.fail("\\pdfendlink used without \\pdfstartlink");
return;
}; };
if !container.horizontal || container.level != link.level { if !container.horizontal || container.level != link.level {
let result = files.observe_diagnostic(WriteDestination::TerminalAndLog, files.observe_diagnostic(WriteDestination::TerminalAndLog,
"pdfTeX warning: pdftex: \\pdfendlink ended up in different nesting level than \\pdfstartlink\n"); "pdfTeX warning: pdftex: \\pdfendlink ended up in different nesting level than \\pdfstartlink\n")
if let Err(error) = result { .map_err(|error| executor.error(error, node.span))?;
failure = Some(self.error(error, node.span));
return;
} }
link.end_segment(&mut self.output, x, self.margin);
} }
link.end_segment(&mut output, x, margin); LinkNode::Running(enabled) => executor.pdf_running_links = *enabled,
}
LinkNode::Running(enabled) => self.pdf_running_links = *enabled,
LinkNode::Destination { destination, view, structure } => { LinkNode::Destination { destination, view, structure } => {
let destination = self.pdf_destination_id(destination); let destination = executor.pdf_destination_id(destination);
let object_number = if numbered { let object_number = if self.numbered {
let Some(number) = destinations.next() else { executor.register_pdf_destination(destination.clone(), structure.is_some())?
failure = Some(self.error("missing PDF destination number at shipout", node.span));
return;
};
number
} else { } else {
None None
}; };
let transform = self.transform;
let view = view.map_rectangle(|[width, height, depth]| { 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 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 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)); 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] [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, object_number, destination, point: map_point(transform.0, x, y), view,
structure: *structure, 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() { executor.current = current;
return self.fail("unused PDF navigation numbers at shipout"); Ok(())
} }
for link in &mut active {
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");
}
self.advance(executor, (output_count, usize::MAX), outputs, graphics, files)?;
for link in &mut self.active {
link.segment = None; link.segment = None;
} }
self.pdf_link_stack = active; executor.pdf_link_stack = self.active;
Ok(output) Ok(self.output)
} }
} }
+20
View File
@@ -940,6 +940,26 @@ next-continuation 保留同一输入的两套 aux 差异。常规重复
对照检查已有 PDF、辅助文件、DVI 与锁定时机,记录在 对照检查已有 PDF、辅助文件、DVI 与锁定时机,记录在
target/p3-pdf-draft-mode/reference.json。 target/p3-pdf-draft-mode/reference.json。
### pdfTeX 跨行与跨页链接的出页顺序
页面链接几何按真实出页事件次序处理。续行注释在实际行首
分配对象号,字体使用、变换及延迟写入按各自访问位置推进。
填充盒中的目标依照原版略过。链接跨页时,检查点保留未结束的
链接状态,之后的页面重新生成对应注释。
[pdfTeX 续行注释分配](https://github.com/TeX-Live/texlive-source/blob/fb6158926661cb7a7246b3a94a0cb170a9624d5a/texk/web2c/pdftexdir/pdftex.web#L33944-L33965)
五组原版对照覆盖同页续行、跨页续行、字体首次使用在两种
位置及填充盒。编号、辅助文件及注释坐标通过,五十九项压缩
XRef 通过。十一页中九页逐像素一致。两份带 CMR 字形的作业
各在第二页保留既有的 196 个像素差异,字体作业的对象流
也保持前版与原版相差一个成员的情况。二十三项链接、PDF 设备及图像定向回归通过。编辑
链接延续的第二页时恢复检查点,PDF、SVG 和来源映射与独立
全量一致,预览只更新该页。回执 SHA-256 为 e684b47c88765637fa7da1822a8b4e787d917521f4aa6feedc8277258afc5d31。
下一入口是 pdfdraftmode。原版的七组输出对照及七组模式冻结
对照在 target/p3-pdf-draft-mode,覆盖辅助文件、已存在的 PDF,
以及普通对象登记和真正开始 PDF 输出之间的界限。
### PDF 预览按实际页面资源复用 ### PDF 预览按实际页面资源复用
编译会话的 SVG 缓存采用预览读取器解析出的页面、有效页框、旋转和资源。 编译会话的 SVG 缓存采用预览读取器解析出的页面、有效页框、旋转和资源。
+85
View File
@@ -200,6 +200,91 @@ fn checkpoint_retains_a_link_target_reserved_by_an_earlier_page() {
fs::remove_dir_all(root).unwrap(); fs::remove_dir_all(root).unwrap();
} }
#[test]
fn checkpoint_restores_a_link_running_into_an_edited_page() {
use std::sync::Arc;
use texrra_engine::native::{
CompileRequest, Entry, NativeCompiler, ProjectDefinition, ProjectSnapshot,
};
use texrra_tex_core::{execution::JobTime, resources::WorldConfig};
let root = std::env::temp_dir().join(format!("texrra-pdf-running-checkpoint-{}", std::process::id()));
fs::create_dir(&root).unwrap();
let entry = root.join("probe.tex");
let second = root.join("second.tex");
let configuration = WorldConfig::new(&root);
let mut source = r"\catcode123=1 \catcode125=2
\pdfoutput=1 \pdfminorversion=5 \pdfobjcompresslevel=1
\pdfpagewidth=80pt \pdfpageheight=80pt \pdfhorigin=6pt \pdfvorigin=6pt
\shipout\hbox{\pdfstartlink goto name{anchor}\vrule width4pt height5pt}
".to_owned();
let line = format!("{}\n", "\\relax ".repeat(26));
source.push_str(&line.repeat(40));
source.push_str("\\input second.tex\n\\end\n");
let original = br"\shipout\hbox{\vrule width4pt height5pt\pdfendlink\pdfdest name{anchor} xyz}";
let changed = br"\shipout\hbox{\vrule width8pt height5pt\pdfendlink\pdfdest name{anchor} xyz}";
let project = ProjectSnapshot::new(ProjectDefinition {
configuration: configuration.clone(),
revision: 1,
roots: [root.clone()].into(),
files: [
(entry.clone(), Arc::<[u8]>::from(source.into_bytes())),
(second.clone(), Arc::from(original.as_slice())),
].into(),
directories: Default::default(),
aliases: Default::default(),
generated_roots: [root.clone()].into(),
generated: Default::default(),
}).unwrap();
let updated = project.with_file_edits(2, [(second, Arc::from(changed.as_slice()))].into()).unwrap();
let time = JobTime::new(2026, 11, 27, 600).unwrap().with_pdf_clock(0, 0).unwrap();
let mut request = CompileRequest::new(configuration, entry, "probe.pdf", time);
request.entry = Entry::Initex;
request.etex = true;
let live = NativeCompiler::default().with_automatic_entry_checkpoints();
let first = live.compile(request.clone().with_project(project)).unwrap();
let next = live.compile(request.clone().with_project(updated.clone())).unwrap();
let cold = NativeCompiler::default().compile(request.with_project(updated)).unwrap();
assert!(next.entry_checkpoint_work.reused_steps > 0);
assert_eq!(next.pdf, cold.pdf);
assert_eq!(next.source_map.pages, cold.source_map.pages);
assert_eq!(next.preview_since(None).unwrap().pages, cold.preview_since(None).unwrap().pages);
let patch = next.preview_since(Some(first.revision())).unwrap();
assert_eq!(patch.pages.iter().map(|page| page.index).collect::<Vec<_>>(), [1]);
let pdf = Document::load_mem(next.pdf.as_deref().unwrap()).unwrap();
for page in pdf.get_pages().into_values() {
let page = pdf.get_dictionary(page).unwrap();
let annotations = resolve(&pdf, page.get(b"Annots").unwrap()).as_array().unwrap();
assert_eq!(annotations.len(), 1);
}
fs::remove_dir_all(root).unwrap();
}
#[test]
fn running_link_allocates_the_continuation_before_a_write_on_that_row() {
let root = std::env::temp_dir().join(format!("texrra-pdf-continuation-order-{}", std::process::id()));
let source = r"\catcode123=1 \catcode125=2
\pdfoutput=1 \pdfminorversion=5 \pdfcompresslevel=0 \pdfobjcompresslevel=0
\pdfpagewidth=100bp \pdfpageheight=100bp \pdfhorigin=8bp \pdfvorigin=8bp
\immediate\openout0=probe.aux
\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
\write0{MARK=continuation/\pdfpageref2;}
\vrule width10pt height5pt depth2pt\pdfendlink\par}
\shipout\hbox{\pdfdest name{target} fit \vrule width10pt height5pt depth2pt}
\immediate\closeout0
\end";
let expected = describe(&compile(&root, source, false));
assert_eq!(describe(&compile(&root, source, true)), expected);
let aux = fs::read(root.join("reference/probe.aux")).unwrap();
assert_eq!(aux, b"MARK=continuation/6;\n");
assert_eq!(fs::read(root.join("native/probe.aux")).unwrap(), aux);
fs::remove_dir_all(root).unwrap();
}
#[test] #[test]
fn real_pdf_link_fragments_and_named_destination_match_pdftex() { 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 root = std::env::temp_dir().join(format!("texrra-pdf-links-{}", std::process::id()));