Reuse cached layouts for relocated native shipouts

This commit is contained in:
gloamxun committed 2026-12-01 22:30:37 +08:00
1 parent 41a459b4ca
commit 57c05d9635
8 files changed
+394 -26

No files matched your search

@@ -43,6 +43,7 @@ mod scheduling;
mod specials;
mod statistics;
mod continuation;
pub use continuation::RelocatedShipoutSuffix;
mod xdv_annotation;
#[derive(Clone, Copy, Debug, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
@@ -87,10 +87,43 @@ impl InputFrame {
}
}
/// Source coordinates for the shipouts copied from a moved execution suffix.
pub struct RelocatedShipoutSuffix {
first_page: usize,
map: SourceRelocation,
}
impl RelocatedShipoutSuffix {
/// Relocate a raw local layout from the exact donor execution at the
/// given zero-based shipout index. The host must match that execution
/// before supplying a cached list.
pub fn relocate_layout(
&self,
index: usize,
layout: &crate::render::DisplayList,
) -> Option<crate::render::DisplayList> {
if index < self.first_page {
return None;
}
layout.relocate_sources(|span| self.map.relocate_span(span))
}
}
impl EntryCheckpoint {
/// Construct an execution with the current prefix and a previously
/// completed suffix. The host must still validate and replay that suffix.
pub fn splice_settled_suffix(&self, prior: &Self, completed: &Execution) -> Option<Execution> {
self.splice_settled_suffix_with_layout(prior, completed)
.map(|(execution, _)| execution)
}
/// Also return the coordinate mapping for copied shipouts whose cached
/// local layouts belong to the supplied completed execution.
pub fn splice_settled_suffix_with_layout(
&self,
prior: &Self,
completed: &Execution,
) -> Option<(Execution, Option<RelocatedShipoutSuffix>)> {
if self.entry != self.active_source
|| prior.entry != prior.active_source
|| self.entry != prior.entry
@@ -190,7 +223,13 @@ impl EntryCheckpoint {
execution.events.push(offset_event_steps(event, offset)?);
}
}
Some(execution)
let layout = relocation.map(|map| RelocatedShipoutSuffix {
// The executor records one top-level shipout event whenever
// this count advances. Form canvases do not enter this sequence.
first_page: old.shipped_pages,
map,
});
Some((execution, layout))
}
/// Carry later checkpoints from the suffix accepted by
/// splice_settled_suffix into this revision. The host must still replay
+3 -1
View File
@@ -71,7 +71,9 @@ pub use case::CaseCode;
pub use context::{ContextFrame, ContextKind, InputContext};
pub use device::{NativeShipout, ShipoutDevice, ShipoutSpecial};
pub use diagnostics::{DiagnosticBox, DiagnosticNode, ShowBoxReport};
pub use engine::{CheckpointDecision, CheckpointSource, EntryCheckpoint, Executor, Limits};
pub use engine::{
CheckpointDecision, CheckpointSource, EntryCheckpoint, Executor, Limits, RelocatedShipoutSuffix,
};
pub use font_catalog::{
FontCatalog, FontCharacter, FontId, FontInstance, FontLimits, FontResource,
};
+205
View File
@@ -6,6 +6,7 @@
//! wired up.
use crate::cmr10::Cmr10Metrics;
use crate::execution::{Span, TokenOrigin};
use crate::math::{self, MathAtom, MathColumnAlign};
use crate::paragraph::ParagraphFont;
use crate::{CellAlignment, Float, FloatPlacement, Halign, HorizontalItem, Page, VerticalItem};
@@ -355,6 +356,78 @@ impl SvgTransparency {
}
impl DisplayList {
/// Reuse a raw shipout layout with a verified map of its source spans.
/// The current execution still projects forms and resolves PDF resources.
#[doc(hidden)]
pub fn relocate_sources(
&self,
mut relocate_span: impl FnMut(Span) -> Option<Span>,
) -> Option<Self> {
if !self.forms.is_empty() {
return None;
}
let mut relocate_origin = |mut origin: TokenOrigin| {
origin.span = relocate_span(origin.span)?;
if let Some(invocation) = origin.invocation {
origin.invocation = Some(relocate_span(invocation)?);
}
Some(origin)
};
let mut layout = self.clone();
for (old, moved) in self.sources.values().zip(layout.sources.values_mut()) {
for (index, origin) in old.tokens.iter().enumerate() {
let shifted = relocate_origin(*origin)?;
// Keep the lowered origin order and its equality classes. A
// newly merged or split origin would change PaintSource::merge.
if old.tokens[..index]
.iter()
.zip(&moved.tokens[..index])
.any(|(left, right)| (left == origin) != (*right == shifted))
{
return None;
}
moved.tokens[index] = shifted;
}
}
use crate::pdf_device::PdfGraphics;
for item in &mut layout.items {
match item {
DisplayItem::PdfGraphics { operation, .. } => match operation {
PdfGraphics::XdvFormUse { source, .. } => *source = relocate_origin(*source)?,
PdfGraphics::Save
| PdfGraphics::Matrix(_)
| PdfGraphics::Restore { .. }
| PdfGraphics::Literal { .. }
| PdfGraphics::SaveMatrix(_)
| PdfGraphics::TextBoundary
| PdfGraphics::XdvFormBegin(_)
| PdfGraphics::XdvFormEnd(_) => {}
},
DisplayItem::NativeGlyph { .. }
| DisplayItem::OpenTypeGlyph { .. }
| DisplayItem::OpenTypeActualText(_)
| DisplayItem::OpenTypeColor(_)
| DisplayItem::MathGlyph { .. }
| DisplayItem::Text { .. }
| DisplayItem::Rule { .. }
| DisplayItem::Line { .. }
| DisplayItem::Image { .. }
| DisplayItem::PdfImage { .. }
| DisplayItem::PdfImageObject(_)
| DisplayItem::PdfForm { .. }
| DisplayItem::Rect { .. }
| DisplayItem::Frame { .. }
| DisplayItem::Link { .. }
| DisplayItem::Background(_)
| DisplayItem::Fill(_)
| DisplayItem::PdfColor { .. }
| DisplayItem::PdfTextSpace { .. }
| DisplayItem::Special(_) => {}
}
}
Some(layout)
}
/// Whether page or captured form colors depend on a PDF default color space.
pub fn has_pdf_default_colors(&self) -> bool {
self.pdf_resources.has_default_color_spaces
@@ -2507,6 +2580,138 @@ impl Page {
mod tests {
use super::*;
#[test]
fn relocates_raw_shipout_origins_without_changing_paint_or_virtual_packets() {
use crate::math_engine_tex::{MathItem, PositionedItem};
use crate::pdf_device::PdfGraphics;
use crate::provenance::{Derivation, PaintSource};
use std::sync::Arc;
let span = |source, start| Span {
source,
start,
end: start + 1,
};
let glyph_origin = TokenOrigin {
span: span(2, 7),
invocation: Some(span(3, 12)),
};
let other_origin = TokenOrigin {
span: span(3, 4),
invocation: None,
};
let form_origin = TokenOrigin {
span: span(3, 15),
invocation: Some(span(2, 5)),
};
let packet = Arc::new(vec![PositionedItem {
x: 2,
y: 3,
item: MathItem::Rule {
width: 4,
height: 5,
},
source: PaintSource::default(),
}]);
let mut layout = DisplayList {
items: vec![
DisplayItem::Rule {
x: 1,
y: 2,
width: 3,
height: 4,
},
DisplayItem::PdfGraphics {
x: 5,
y: 6,
operation: PdfGraphics::XdvFormUse {
number: 7,
options: Default::default(),
source: form_origin,
available: true,
},
},
],
xdv_horizontal_offsets: vec![(1, 8)],
prepared_virtual_glyphs: Some([(0, packet.clone())].into()),
..Default::default()
};
layout.sources.insert(
0,
PaintSource {
tokens: vec![glyph_origin, other_origin],
derivations: vec![Derivation::FontMapping],
},
);
let relocated = layout
.relocate_sources(|value| {
Some(if value.source == 3 && value.start >= 10 {
span(value.source, value.start + 2)
} else {
value
})
})
.unwrap();
let mut expected = layout.clone();
expected.sources.get_mut(&0).unwrap().tokens[0].invocation = Some(span(3, 14));
let DisplayItem::PdfGraphics {
operation: PdfGraphics::XdvFormUse { source, .. },
..
} = &mut expected.items[1]
else {
unreachable!();
};
source.span = span(3, 17);
assert_eq!(relocated, expected);
assert!(Arc::ptr_eq(
&relocated.prepared_virtual_glyphs.unwrap()[&0],
&packet
));
}
#[test]
fn rejects_a_new_collision_or_unproved_invocation_in_relocated_origins() {
use crate::provenance::PaintSource;
let span = |offset| Span {
source: 0,
start: offset,
end: offset,
};
let layout = DisplayList {
items: vec![DisplayItem::Rule {
x: 0,
y: 0,
width: 1,
height: 1,
}],
sources: [(
0,
PaintSource {
tokens: vec![
TokenOrigin {
span: span(5),
invocation: Some(span(8)),
},
TokenOrigin {
span: span(6),
invocation: Some(span(8)),
},
],
derivations: Vec::new(),
},
)]
.into(),
..Default::default()
};
assert!(layout.relocate_sources(|_| Some(span(3))).is_none());
assert!(
layout
.relocate_sources(|value| { (value != span(8)).then_some(value) })
.is_none()
);
}
#[test]
fn tall_delimiters_are_lowered_to_stay_centered() {
let atom = crate::math::parse_math(r"\left(\frac{a}{b}\right)");