From af19a26c23595af0da85be1778c54997e193aaaf Mon Sep 17 00:00:00 2001 From: GloamXun Date: Fri, 27 Nov 2026 22:34:01 +0800 Subject: [PATCH] Order native PDF link continuations with shipout effects --- crates/texrra-tex-core/src/execution/boxes.rs | 6 +- .../src/execution/engine/page.rs | 68 +++-- .../src/execution/engine/pdf_links.rs | 235 ++++++++++-------- docs/P2_M1_PROGRESS.md | 20 ++ tests/native_pdf_links.rs | 85 +++++++ 5 files changed, 274 insertions(+), 140 deletions(-) diff --git a/crates/texrra-tex-core/src/execution/boxes.rs b/crates/texrra-tex-core/src/execution/boxes.rs index bf237da..dd65a9e 100644 --- a/crates/texrra-tex-core/src/execution/boxes.rs +++ b/crates/texrra-tex-core/src/execution/boxes.rs @@ -886,20 +886,22 @@ impl NativeBox { pub(super) fn visit_shipout_font_uses( &self, - mut emit: impl FnMut(usize, &std::sync::Arc, u8), + mut emit: impl FnMut(usize, usize, &std::sync::Arc, u8), ) -> Result<(), String> { use crate::math_engine_tex::MathItem; let mut output_count = 0; + let mut paint_count = 0; self.walk(0, 0, &mut |_, _, node| match node { BoxPaint::Output(_) => output_count += 1, BoxPaint::Box(b) => { if let Some(geometry) = &b.math_geometry { for item in &geometry.items { if let MathItem::NativeGlyph { font, slot, .. } = &item.item { - emit(output_count, font, *slot); + emit(output_count, paint_count, font, *slot); } } } + paint_count += 1; } _ => {} })?; diff --git a/crates/texrra-tex-core/src/execution/engine/page.rs b/crates/texrra-tex-core/src/execution/engine/page.rs index 85b8b7f..10b0003 100644 --- a/crates/texrra-tex-core/src/execution/engine/page.rs +++ b/crates/texrra-tex-core/src/execution/engine/page.rs @@ -39,6 +39,7 @@ pub(super) struct PdfSpaceProbe { struct ShipoutFontUse { before_output: usize, + before_paint: usize, font: Arc, slot: u8, } @@ -48,11 +49,11 @@ fn shipout_font_uses( ) -> Result, 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; diff --git a/crates/texrra-tex-core/src/execution/engine/pdf_links.rs b/crates/texrra-tex-core/src/execution/engine/pdf_links.rs index f44787c..3f0c41b 100644 --- a/crates/texrra-tex-core/src/execution/engine/pdf_links.rs +++ b/crates/texrra-tex-core/src/execution/engine/pdf_links.rs @@ -26,6 +26,25 @@ pub(super) struct ActiveLink { segment: Option, } +enum LinkPaint { + Graphics, + RowStart(BoxLayout), + Node(BoxLayout), +} + +pub(super) struct PdfLinkShipout { + events: std::iter::Peekable>, + output_count: usize, + active: Vec, + 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>, structure: bool, + &mut self, id: DestinationId, structure: bool, ) -> Result, 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], - numbers: (Vec, Vec>), files: &mut impl SourceProvider, - ) -> Result { - 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], + files: &mut impl SourceProvider, + ) -> Result { + 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) } } diff --git a/docs/P2_M1_PROGRESS.md b/docs/P2_M1_PROGRESS.md index 521e7ea..e3d5b74 100644 --- a/docs/P2_M1_PROGRESS.md +++ b/docs/P2_M1_PROGRESS.md @@ -940,6 +940,26 @@ next-continuation 保留同一输入的两套 aux 差异。常规重复 对照检查已有 PDF、辅助文件、DVI 与锁定时机,记录在 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 预览按实际页面资源复用 编译会话的 SVG 缓存采用预览读取器解析出的页面、有效页框、旋转和资源。 diff --git a/tests/native_pdf_links.rs b/tests/native_pdf_links.rs index fbdb594..aefc77f 100644 --- a/tests/native_pdf_links.rs +++ b/tests/native_pdf_links.rs @@ -200,6 +200,91 @@ fn checkpoint_retains_a_link_target_reserved_by_an_earlier_page() { 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::>(), [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] fn real_pdf_link_fragments_and_named_destination_match_pdftex() { let root = std::env::temp_dir().join(format!("texrra-pdf-links-{}", std::process::id()));